""" 管家app2.0接口 管家-租入-租入申请-审批-驳回 """ import unittest import paramunittest from common import common from common.Log import MyLog import readConfig from common import configHttp_new from common import encryptLib from common import configDB import json from config.settings import token_fiel_path localReadConfig = readConfig.ReadConfig() # 读取excel表格里的case tag = int(localReadConfig.get_setting('tag').encode('utf-8')) guanjia_accounts_xls = common.get_xls("app_v2.0.xlsx", "lease_rentapply_docheck_back", tag=tag) print 'excel里测试用例列表:\n', guanjia_accounts_xls @paramunittest.parametrized(*guanjia_accounts_xls) class GuanJiaLeaseRentApplyShow(unittest.TestCase): def setParameters(self, CaseName, CaseDescribe, Method, Token, ServiceID, Data, Result, ExpectState, ExpectMsg): """ 初始化excel表格里的数据 set params
import json import unittest from common.configHttp import RunMain import geturlParams import readConfig as readConfig import utils.S3 as s3 import time url = geturlParams.geturlParams().get_Url() # 调用我们的geturlParams获取我们拼接的URL readconfig = readConfig.ReadConfig() bucketName = 'interfacetest' objectName = 'logo.png' ak = readconfig.get_params('accessKey') sk = readconfig.get_params('secretKey') endpoint = readconfig.get_params('endPoint') class TestOssBucket(unittest.TestCase): def setUp(self): print("测试开始前准备") result = s3.create_bucket(ak=ak, sk=sk, endpoint=endpoint, bucket_name=bucketName) if result: print("桶创建成功") else: print("桶创建失败") result = s3.put_object(ak=ak, sk=sk, endpoint=endpoint, bucket_name=bucketName, object_name=objectName, src_data=objectName) if result: print("文件上传成功") else: print("文件上传失败")
count_element += 1 #caluate element numbers #print(list_element) time.sleep(delay_sec) #延遲delay_sec秒,證交所會根據IP進行流量統計,流量過大會斷線 if list_element != []: collection.insert_many(list_element)#bulk insert all documents return count_element if __name__ == '__main__': t0 = time.time() count = 0 configPath=os.path.join(strdirname,"config.ini") localReadConfig = readConfig.ReadConfig(configPath) mongo_host = localReadConfig.get_MongoDB('mongo_host') mongo_db = localReadConfig.get_MongoDB('mongo_db') mongo_collection = localReadConfig.get_MongoDB('mongo_collection') mongo_username = localReadConfig.get_MongoDB('mongo_username') mongo_password = localReadConfig.get_MongoDB('mongo_password') str_last_year_month = localReadConfig.get_SeymourExcel("last_year_month") str_last_year = str_last_year_month.split(',')[0] str_last_month = str_last_year_month.split(',')[1] str_stkidx = localReadConfig.get_SeymourExcel("stkidx") str_delay_sec = localReadConfig.get_SeymourExcel("delay_sec") collection = connectMongoDB.MongoDBConnection.connect_mongo(mongo_host,mongo_db, mongo_collection,mongo_username,mongo_password) #連線資料庫
import os import win32com.client as win32 import datetime import readConfig import getpathInfo from common.Log import logger import smtplib from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart read_conf = readConfig.ReadConfig() mailSmtpServer = read_conf.get_email('mailSmtpServer') mailSmtpUser = read_conf.get_email('mailSmtpUser') mailSmtpPwd = read_conf.get_email('mailSmtpPwd') mailTitle = read_conf.get_email('mailTitle') mailBody = read_conf.get_email('mailBody') #从配置文件中读取,邮件主题 mailAppType = str(read_conf.get_email('mailAppType')) #从配置文件中读取,邮件类型 mailFromPerson = str(read_conf.get_email('mailFromPerson')) mailToPerson = read_conf.get_email('mailToPerson') #从配置文件中读取,邮件收件人 mailToCC = read_conf.get_email('mailToCC') #从配置文件中读取,邮件抄送人 mailFilePath = os.path.join(getpathInfo.get_Path(), 'result', 'report.html') #获取测试报告路径 logger = logger class send_email(): def mailMain(self): try: # 创建一个实例 with open(mailFilePath, 'rb') as f:
import os import common.HTMLTestRunner as HTMLTestRunner import getpathInfo import unittest import readConfig from common.configEmail import send_email from apscheduler.schedulers.blocking import BlockingScheduler import pythoncom import common.Log send_mail = send_email() path = getpathInfo.get_Path() report_path = os.path.join(path, 'result') on_off = readConfig.ReadConfig().get_email('on_off') log = common.Log.logger class AllTest: # 定义一个类AllTest def __init__(self): # 初始化一些参数和数据 global resultPath resultPath = os.path.join(report_path, "report.html") # result/report.html self.caseListFile = os.path.join(path, "caselist.txt") # 配置执行哪些测试文件的配置文件路径 self.caseFile = os.path.join(path, "testCase") # 真正的测试断言文件路径 self.caseList = [] log.info('resultPath' + resultPath) # 将resultPath的值输入到日志,方便定位查看问题 log.info('caseListFile' + self.caseListFile) # 同理 log.info('caseList' + str(self.caseList)) # 同理 def set_case_list(self):
import json import requests import readConfig sessionRequest = requests.session() # payload = {"loginname":"17644444444","loginpwd":"vip17644444444","userFlage":"1"} payload = readConfig.ReadConfig().get_login_user('payload') sessionRequest.post(url="https://pre2sellermall.gree.com/mobile-seller/login", json=json.loads(payload))
def checkResult(self): # 断言 """ check test result :return: """ #------使用eval方法将参数str类型转换为dict global ss data = eval(self.query) bodyType = self.bady_type headers = self.header url1 = url + self.path try: # 根据Excel中的method调用run_main来进行requests请求,并拿到响应 info = RunMain().run_main(self.method, url1, data, headers, bodyType) ss = json.loads(info) # 将响应转换为字典格式 except: print('请求结果转换json失败') if self.case_name == 'applyCarAttend': self.assertEqual(ss[self.assertKey], self.code) G.applyId = ss['data'] print(G.applyId) key = 'apply_progress' table = 'vehicle_license_apply_info' conditions = 'id' value = G.applyId a = configDB.DBsql( readConfig.ReadConfig().get_content('DATABASE', 'host'), readConfig.ReadConfig().get_content('DATABASE', 'user'), readConfig.ReadConfig().get_content('DATABASE', 'password'), readConfig.ReadConfig().get_content('DATABASE', 'databaseCar')).Select( key, table, conditions, value) self.assertIn('1', str(a)) elif self.case_name == 'getCarList': self.assertEqual(ss[self.assertKey], self.code) self.assertEqual(ss['success'], True) elif self.case_name == 'updateType3': self.assertEqual(ss[self.assertKey], self.code) key = 'apply_progress' table = 'vehicle_license_apply_info' conditions = 'id' value = G.applyId a = configDB.DBsql( readConfig.ReadConfig().get_content('DATABASE', 'host'), readConfig.ReadConfig().get_content('DATABASE', 'user'), readConfig.ReadConfig().get_content('DATABASE', 'password'), readConfig.ReadConfig().get_content('DATABASE', 'databaseCar')).Select( key, table, conditions, value) self.assertIn('3', str(a)) elif self.case_name == 'updateType4': self.assertEqual(ss[self.assertKey], self.code) key = 'apply_progress' table = 'vehicle_license_apply_info' conditions = 'id' value = G.applyId a = configDB.DBsql( readConfig.ReadConfig().get_content('DATABASE', 'host'), readConfig.ReadConfig().get_content('DATABASE', 'user'), readConfig.ReadConfig().get_content('DATABASE', 'password'), readConfig.ReadConfig().get_content('DATABASE', 'databaseCar')).Select( key, table, conditions, value) self.assertIn('4', str(a)) elif self.case_name == 'updateType4': self.assertEqual(ss[self.assertKey], self.code) elif self.case_name == 'getUserList': self.assertEqual(ss[self.assertKey], self.code) self.assertNotEqual(len(ss['data']), 0) elif self.case_name == 'end': table = 'vehicle_license_apply_info' conditions = 'id' value = G.applyId configDB.DBsql( readConfig.ReadConfig().get_content('DATABASE', 'host'), readConfig.ReadConfig().get_content('DATABASE', 'user'), readConfig.ReadConfig().get_content('DATABASE', 'password'), readConfig.ReadConfig().get_content('DATABASE', 'databaseCar')).Delete( table, conditions, value)
# -*-coding:utf-8-*- __author__ = 'tuihou' import os import requests from multiprocessing import Process import readConfig import threading import time cf = readConfig.ReadConfig() class AppiumServer: def __init__(self): global openAppium, baseUrl, stopAppium openAppium = cf.getcmdValue("openAppium") stopAppium = cf.getcmdValue("stopAppium") baseUrl = cf.getConfigValue("baseUrl") def start_server(self): """start the appium server :return: """ t1 = RunServer(openAppium) p = Process(target=t1.start()) p.start() def stop_server(self): """stop the appium server :return: """
from apscheduler.schedulers.blocking import BlockingScheduler import pythoncom import readConfig import common.Email as Email from runCase import AllTest import runAll on_off = readConfig.ReadConfig().get_email('on_off') case_switch = readConfig.ReadConfig().get_cases('caseswitch') class RunMain: def run(self): # 判断跑全部的case还是部分的 if case_switch == 'on': AllTest.run() else: runAll.run() # 判断邮件发送的开关 if on_off == 'on': Email.send_mail() else: print("邮件发送开关配置关闭,请打开开关后可正常自动发送测试报告") # 定时任务 pythoncom.CoInitialize() scheduler = BlockingScheduler() scheduler.add_job(RunMain().run, 'cron', day_of_week='1-5', hour=8, minute=30)
import unittest import paramunittest import common import readConfig as ReadConfig from common import configHttp, common_utils from common import businessCommon from common.LogUtil import MyLog localReadConfig = ReadConfig.ReadConfig() localConfigHttp = configHttp.ConfigHttp() localLogout_xls = common_utils.get_xls("userCase.xlsx", "logout") @paramunittest.parametrized(*localLogout_xls) class Logout(unittest.TestCase): def setParameters(self, case_name, method, token, result, code, msg): """ set parameters :param case_name: :param method: :param token: :param result: :param code: :param msg: :return: """ self.case_name = str(case_name) self.method = str(method) self.token = str(token)
def set_case_suite(): #用例的控制应当做好,并且要做全,这样可以很好地控制用例的执行。 #第一档,从模块级别进行控制loadTestsFromTestModule(module, pattern=None).此处的module是指装有测试用例的py文件 #第二档,从测试类进行控制loadTestsFromTestCase(testCaseClass),testCaseClass,即测试类,及其子类,孙类。类方法也可以用suite=unittest.TestSuite(unittest.makeSuite(TestDiv))添加 #第三档,从测试类进行控制loadTestsFromName(name, module=None),name是一个string,string需要是是这种格式的“module.class”. #加载单条用例tests=['test_001','test_002'] unittest.TestSuite(map(TestDiv,tests))map辅助,直接映射存储到测试套里面 #第四档,加载大量(所有)用例,不加限制discover(start_dir, pattern=’test*.py’, top_level_dir=None),从start_dir中获取文件自动加载所有匹配的用例 #查看是否要运行所有用例 runAll = readConfig.ReadConfig().get_runAll("runAllCases") test_suite = unittest.TestSuite() suite_model = [] #如果运行所有,直接调用discover方法 if runAll == "Yes": case_file = os.path.join(readConfig.proDir, "testCase") discover = unittest.defaultTestLoader.discover(case_file, pattern="test*" + '.py', top_level_dir=None) suite_model.append(discover) if len(suite_model) > 0: for suite in discover: for test_name in suite: test_suite.addTest(test_name) else: return None else: casePath = os.path.join(readConfig.proDir, "testFile", "interfaces.xlsx") xlsContent = commons.get_xls_BySheetName(casePath, "allCases") caseSet = [] testclass = [] testclass2 = [] caseList = [] # 从模块级别加载需要运行的用例 for i in range(1, len(xlsContent)): caseSet.append(xlsContent[i][2]) if xlsContent[i][0] != "" and not str( xlsContent[i][0]).startswith("#"): testclass.append(xlsContent[i][1]) # 从类级别加载需要执行的用例 for j in range(0, len(testclass)): if not str(testclass[j]).startswith("#"): #剔除不需要运行的测试类 testclass2.append(testclass[j]) #去重,得出最后的测试类.不改变原来顺序 caseClass = list(set(testclass2)) caseClass.sort(key=testclass2.index) #从单条用例级别加载所需执行的用例 for cs in caseSet: tp = str(cs).split(".") # 关联需要测试的类 for sn in caseClass: if str(tp[1]).strip() == str(sn).strip() and not str( tp[0]).startswith("#"): print(tp[2]) caseList.append(tp[2]) #根据得出的最终测试用例,加载进入测试套 c_caseSet = C_caseList().caseSet() for tc in c_caseSet: tn = str(tc).split("(") cName = str(tn[0]).strip() if not cName.startswith("#") and cName in caseList: test_suite.addTest(tc) return test_suite
# -*- coding:utf-8 -*- """ 获取、打开driver """ import readConfig import os from appium import webdriver from selenium.common.exceptions import WebDriverException from urllib.error import URLError readConfigValue = readConfig.ReadConfig() class MyDriver: driver = None deviceName = readConfigValue.getConfigValue("deviceName") platformName = readConfigValue.getConfigValue("platformName") platformVersion = readConfigValue.getConfigValue("platformVersion") appPackage = readConfigValue.getConfigValue("appPackage") appActivity = readConfigValue.getConfigValue("appActivity") baseUrl = readConfigValue.getConfigValue("baseUrl") app = os.path.join(os.path.dirname(__file__), "jiankemall.apk") desired_caps = { "deviceName": deviceName, "platformName": platformName, "platformVersion": platformVersion, "app": app }
def setUpClass(cls): f = readConfig.ReadConfig() Authorization = f.getUserValue("authorization") cls.header = {"Authorization": Authorization}