pytest.ini
[pytest]
miniversion = 5.0.0
;base_url = http://localhost:8080/ -m=login,sys
addopts = --strict --html=reports/report.html --self-contained-html -m=login,sys
base_dir = "c://d/"
testpaths = test_cases/
markers =
login: scene case
sys: ksdlk
email_subject = Test Report
email_receivers = [email protected],[email protected]
email_body = Hi,all\n, Please check the attachment for the Test Report.
log_cli = true
log_cli_level = info
log_cli_format = %(asctime)s %(levelname)s %(message)s
log_cli_date_format = %Y-%m-%d %H:%M:%S
timeout = 10
timeout_func_only = true
current_path
import os
base_dir = os.path.dirname(__file__)
print(base_dir)
assert
def assert_eq_text(self,body,expected_value):
try:
# assert body == expected_value
check.almost_equal(expected_value,body)
self.log.info(f"断言成功。实际的是{body},期待的是{expected_value}")
return True
except:
self.log.error(f"断言错误。不相等。实际的是{body},期待的是{expected_value}")
raise
log.py
import logging
import os
import time
'''
日志级别
'''
LEVELS={
'debug':logging.DEBUG,
'info':logging.INFO,
'warning':logging.WARNING,
'error':logging.ERROR,
'critical':logging.CRITICAL
}
logger = logging.getLogger()
level = 'default'
def create_file(filename):
'''
创建文件
:param filename:
:return:
'''
path = filename[0:filename.rfind('/')]
if not os.path.isdir(path):
os.makedirs(path)
if not os.path.isfile(filename):
fd = open(filename,mode="w",encoding='utf-8')
fd.close()
else:
pass
def set_handler(levels):
'''
设置画板
:param levels:
:return:
'''
if levels == "error":
logger.addHandler(MyLog.err_handler)
logger.addHandler(MyLog.handler)
def remove_handler(levels):
'''
移除画板
:param levels:
:return:
'''
if levels == 'error':
logger.removeHandler(MyLog.err_handler)
logger.removeHandler(MyLog.handler)
def get_current_time():
return time.strftime(MyLog.date,time.localtime(time.time()))
class MyLog:
'''
'''
#绝对路径
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
log_file = path +"/log/log.log"
err_file = path +"/log/err.log"
logger.setLevel(LEVELS.get(level,logging.NOTSET))
create_file(log_file)
create_file(err_file)
date = '%Y-%m-%d %H:%M:%S'
#在哪里写文件
handler = logging.FileHandler(log_file,encoding='utf-8')
err_handler = logging.FileHandler(err_file,encoding='utf-8')
@staticmethod
def debug(log_meg):
set_handler("debug")
logger.debug("[DEBUG " + get_current_time() +"] " + log_meg)
remove_handler("debug")
@staticmethod
def info(log_meg):
set_handler('info')
logger.info("[INFO " + get_current_time() + "] " + log_meg)
remove_handler('info')
@staticmethod
def warning(log_meg):
set_handler('warning')
logger.warning("[WARNING " + get_current_time() + "] " + log_meg)
remove_handler('warning')
@staticmethod
def error(log_meg):
set_handler('error')
logger.error("[ERROR " + get_current_time() + "] " + log_meg)
remove_handler('error')
@staticmethod
def critical(log_meg):
set_handler('critical')
logger.error("[CRITICAL " + get_current_time() + "] " + log_meg)
remove_handler('critical')
if __name__ == '__main__':
MyLog.debug("This is debug message")
MyLog.info("This is info message")
MyLog.warning("This is warning message")
MyLog.error("This is error")
MyLog.critical("This is critical message")
import requests
from utils.log import MyLog
TIMEOUT = 30
class Api(object):
def __init__(self, base_url=None):
self.session = requests.session()
self.base_url = base_url
self.log = MyLog()
def request(self, method, url, **kwargs):
url = self.base_url + url if self.base_url else url
kwargs['timeout'] = kwargs.get('timeout', TIMEOUT)
res = self.session.request(method, url, **kwargs)
print(f"发送请求: {method} {url} {kwargs} 响应数据: {res.text}")
return res
def session_get(self, url, **kwargs):
try:
url = self.base_url + url if self.base_url else url
r= self.session.request('get', url, **kwargs)
print("getSession",self.session)
except requests.RequestException as e:
print(f"RequestException的url:{url}")
print(e)
self.log.error(f"RequestException的url:{url},测试数据:{kwargs}")
return ()
except Exception as e:
print(f"Exception的url:{url},测试数据:{kwargs}")
print(e)
self.log.error(f"Exception的url:{url},测试数据:{kwargs}")
return ()
self.log.info(f"url:{url},测试数据:{kwargs}")
return r
def session_post(self, url, **kwargs):
msg = f"url:{url},测试数据:{kwargs}"
try:
url = self.base_url + url if self.base_url else url
r=self.session.request('post', url, **kwargs)
print("postSession", self.session)
# r = self.session.post(url,data=kwargs["data"])
except requests.RequestException as e:
print(f"RequestException的url:{url}")
print(e)
self.log.error("RequestException"+msg)
return ()
except Exception as e:
print("RequestException"+msg)
print(e)
self.log.error("RequestException"+msg)
return ()
self.log.info("成功的请求。"+msg)
return r
config = configparser.ConfigParser()
config.read(base_dir+r'\config.ini')
loginName = config.get("myConfig", "loginName")