class BaseSeleniumTestCase(TestCase): def get_web_driver(self): driver = webdriver.Chrome() driver.maximize_window() return driver def setUp(self): self.selenium = self.get_web_driver() self.log = Log("[%s][%s]" % (self.get_current_case_file_name(), self.get_current_case_class_name())) self.logger = self.log.get_logger() self.dataDict = self.get_excel_data_by_casename(settings.TEST_DATA_EXCEL_FILE) # 获取当前在执行的case的测试数据[dict] self.log.build_start_line(self.dataDict['caseName'], self.dataDict['description']) # 打印case开始线到日志 def tearDown(self): self.log.build_end_line(self.dataDict['caseName']) # 打印case结束线到日志 self.selenium.quit() def get_excel_data_by_casename(self, excelFile, colIndex=0, sheetName=u'test_csv'): # 修改自己路径 test_name = self.get_current_case_name() # 获取调用函数的函数名称(test_name) data = xlrd.open_workbook(excelFile) table = data.sheet_by_name(sheetName) # 获得表格 nrows = table.nrows # 拿到总共行数 colnames = table.row_values(colIndex) # 某一行数据 ['姓名', '用户名', '联系方式', '密码'] rownums = 0 findrow = 0 for i in range(nrows): cell_value = table.cell_value(i, colIndex) if test_name == str(cell_value): findrow += 1 rownums = i assert findrow == 1, 'None or more than one test name in excel sheet, please check!' row = table.row_values(rownums) excelDict = {} for j in range(0, len(colnames)): # if row[j] == '': # continue excelDict[colnames[j]] = row[j] # 表头与数据对应 return excelDict def get_current_case_name(self): '获取当前运行的case的name' return super().id().split(".")[-1] def get_current_case_class_name(self): '获取当前运行的case所在的类名' return super().id().split(".")[-2] def get_current_case_file_name(self): '获取当前运行的case所在的文件名' return "%s.py" % super().id().split(".")[-3]
def wrapper(*args, **kwargs): instance, selector = args[0], args[1] try: return function(*args, **kwargs) except (TimeoutException, NoSuchElementException, InvalidElementStateException) as ex: log = Log(os.getenv('trace_info')) logger = log.get_logger() logger.info("Could not find the selector: [{}]".format(selector)) filename = "{}.png".format(get_current_time_str()) logger.debug(instance.selenium.page_source) if rc.get_open_close("IS_SCREENSHOT") == "True": # 设置为True时保存截图 screenshot_path = os.path.join(get_screenshot_dir(), filename) instance.selenium.save_screenshot(screenshot_path) raise ex
class ReadYaml(object): __log = Log("ReadYaml") def __init__(self, filename): self.path = filename def get_yaml(self): """ 读取yaml文件 :return: """ try: f = open(self.path, encoding="utf-8") data = yaml.load(f, Loader=yaml.FullLoader) f.close() # print(type(data)) return data except Exception as e: return str(e.__class__.__name__) + " " + e.args[1] def all_data(self): data = self.get_yaml() try: if not isinstance(data, list): return list(data) elif not isinstance(data, dict): return data except Exception as e: self.__log.error(str(e)) return
class TestPassengerQueryTicket(unittest.TestCase): __yaml_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "yaml_case_file/") config = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config/config.ini") __config = ConfigUtils(configfile=config) __data = ReadYaml(__yaml_path+"passenger_query_ticket.yaml").all_data() __log = Log("test_passenger_query_ticketr") __server = XiaMenShipApi(host=__config.get_value_by_section_and_option("server", "host")) def setUp(self): super().setUp() @classmethod def setUpClass(cls): super().setUpClass() def tearDown(self): super().tearDown() @classmethod def tearDownClass(cls): super().tearDownClass() def __init__(self, methodName='runTest'): super().__init__(methodName) def __str__(self): return super().__str__() @data(*__data) @unpack def test_01(self, **value): self.__log.info("开始进行测试"+" "+value["casetitle"]) try: res = self.__server.api_passenger_ticket_checking_query(op=1, bodynew=value["body"]) dict_data = json.loads(res.text) self.assertEqual(dict_data["status"], value["expect"]) self.__log.info("用例{}执行成功".format(value["casetitle"])+"\n"+str(value["body"])) except Exception as e: print(res.text, file=sys.stderr) self.__log.error("用例{}执行失败,失败的原因为{}".format(value["casetitle"], str(e))+"\n"+res.text) self.fail() def test_02(self): try: res = self.__server.api_passenger_ticket_checking_query(reqId="222466546445", pageIndex=0, pageSize=1, passengerName="", verifyResults="", passportId="", idNumber="idNumberA0041", checkingTimeSt="", checkingTimeEnd="" ) print(res.text) except Exception as e: print(e.__class__.__name__) print()
class TestPassengerOfficeUpLoad(unittest.TestCase): config = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config/config.ini") __config = ConfigUtils(configfile=config) __log = Log("test_passenger_officeUpload") __server = XiaMenShipApi( host=__config.get_value_by_section_and_option("server", "host")) def tearDown(self): super().tearDown() @classmethod def tearDownClass(cls): super().tearDownClass() @classmethod def setUpClass(cls): super().setUpClass() def setUp(self): super().setUp() def test_01(self): a = 2 json_array = [] info_1 = { "checkinId": PublicMethod.get_uuid(), "userBarcode": "", "checkingTime": "", "checkDeviceNo": "" } for i in range(0, a): info = { "checkinId": PublicMethod.get_uuid(), "userBarcode": "000000000006", "checkingTime": PublicMethod.get_time_format(), "checkDeviceNo": "device_id1" } json_array.append(info) try: res = self.__server.api_ticket_officeUpload(reqId="uuid32位", json_array=json_array) self.__log.info(res.text) except Exception as e: self.__log.error(str(e))
class TestPassengerTicketChecking(unittest.TestCase): __yaml_path = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "yaml_case_file/") config = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config/config.ini") __data = ReadYaml(__yaml_path + "passenger_ticket_checking.yaml").all_data() __config = ConfigUtils(configfile=config) __log = Log("test_passenger_ticket_checking") __server = XiaMenShipApi( host=__config.get_value_by_section_and_option("server", "host")) def setUp(self): super().setUp() @classmethod def setUpClass(cls): super().setUpClass() def tearDown(self): super().tearDown() @classmethod def tearDownClass(cls): super().tearDownClass() def __init__(self, methodName='runTest'): super().__init__(methodName) def __str__(self): return super().__str__() @data(*__data) @unpack def test_01(self, **value): self.__log.info("开始进行测试" + " " + value["casetitle"]) try: res = self.__server.api_passenger_ticket_checking( op=1, bodynew=value["body"]) dict_data = json.loads(res.text) self.assertEqual(dict_data["status"], value["expect"]) self.__log.info("用例{}执行成功".format(value["casetitle"])) except Exception as e: print(res, file=sys.stderr) self.__log.error("用例{}执行失败,失败的原因为{}".format( value["casetitle"], str(e))) self.fail() def test_02(self): try: res = self.__server.api_passenger_ticket_checking( reqId="1645", userBarcode="userBarcode001", checkinId="1125", checkingTime=PublicMethod.get_time_format(), checkDeviceNo="testNo001") print(res.text) except Exception as e: print(e)
# @Software: PyCharm import json import os import time from public.Config import ConfigUtils from public.Log import Log from public.XiaMenShipApi import XiaMenShipApi from public.public_method import PublicMethod _config = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config/config.ini") __config = ConfigUtils(configfile=_config) __log = Log("process_test") __server = XiaMenShipApi( host=__config.get_value_by_section_and_option("server", "host")) def process_test(): """对流程从-添加旅客信息->验票再进行查询进行全流程测试""" # 进行旅客信息添加 a = 1 while True: __log.info("开始进行第{}次流程".format(a)) res = __server.api_passenger_info_new_add( reqId=PublicMethod.get_uuid(), userId="userIdA00{}".format(a), flightId="a027d0582e6842a59ab2f9eacd544213", groupNo="groupNoA00{}".format(a),
class TestPassengerByPrinter(unittest.TestCase): yaml_path = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "yaml_case_file/") config = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config/config.ini") __config = ConfigUtils(configfile=config) __data = ReadYaml(yaml_path + "test.yaml").all_data() __log = Log("test_passenger_query_ByPrinter") __server = XiaMenShipApi( host=__config.get_value_by_section_and_option("server", "host")) def __init__(self, methodName='runTest'): super().__init__(methodName) def setUp(self): super().setUp() @classmethod def setUpClass(cls): super().setUpClass() def __str__(self): return super().__str__() def tearDown(self): super().tearDown() @classmethod def tearDownClass(cls): super().tearDownClass() # @file_data(path+"test.yaml") @data(*__data) @unpack def test_01(self, **value): self.__log.info("开始进行测试" + " " + value["casetitle"]) try: res = self.__server.api_passenger_query_by_printer( op=1, bodynew=value["body"]) dict_data = json.loads(res.text) self.assertEqual(dict_data["status"], value["expect"]) self.__log.info("用例{}执行成功".format(value["casetitle"]) + "\n" + str(value["body"])) except Exception as e: print(res.text, file=sys.stderr) self.__log.error( "用例{}执行失败,失败的原因为{}".format(value["casetitle"], str(e)) + "\n" + res.text) self.fail() def test_02(self): try: res = self.__server.api_passenger_query_by_printer( passportId="passportId1", idNumber="500238199312134390", sailDateSt="", sailDateEnd="2019-07-08 17:09:20") print(res.text) except Exception as e: print(e.__class__.__name__) def test_03(self): print( type( self.__config.get_value_by_section_and_option( "server", "host")))
def setUp(self): self.selenium = self.get_web_driver() self.log = Log("[%s][%s]" % (self.get_current_case_file_name(), self.get_current_case_class_name())) self.logger = self.log.get_logger() self.dataDict = self.get_excel_data_by_casename(settings.TEST_DATA_EXCEL_FILE) # 获取当前在执行的case的测试数据[dict] self.log.build_start_line(self.dataDict['caseName'], self.dataDict['description']) # 打印case开始线到日志