導包:pip3 install xlutilspython
注意⚠️:xlutils在介些Execl文件的時候,只識別.xls後綴的文件,若是是.xlsx後綴的文件被解析,.xlsx後綴的文件會被破壞mysql
#!/user/bin/env python #coding:utf-8 #Author:shenqiang '''xlrd寫入文件,同時清空原文件''' import xlrd import os '''拿到文件的路徑''' def base_path(filename = None): return os.path.join(os.path.dirname(__file__),filename) '''讀取文件內容''' work = xlrd.open_workbook(base_path('tryExeclRead.xls')) '''如下標或者sheet名取對應的哪頁''' sheet = work.sheet_by_index(0) # sheet = work.sheet_by_name() '''查看文件有多少行''' print(sheet.nrows) '''獲取單元格內容,第10行,第3列''' print(sheet.cell_value(9,2))
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import xlrd import os from xlutils.copy import copy '''拿到文件的路徑''' def base_path(filename = None): return os.path.join(os.path.dirname(__file__),filename) '''打開文件''' work = xlrd.open_workbook(base_path('tryExeclRead.xls')) '''把文件內存存在一個變量裏''' file_content = copy(work) '''拿到文件須要改寫的sheet頁''' file = file_content.get_sheet(0) # print(file_content) '''定位文件位置寫入內容''' file.write(9,3,'強強') '''保存文件''' file_content.save(base_path('tryExeclRead.xls'))
配置文件名linux
config.iniweb
文件內容:sql
[linux]
ip:10.0.13.26
port:22
username:root
password:W2ynE6b58wheeFho
[mysql]
ip:10.0.13.26
port:22
username:root
password:W2ynE6b58wheeFho
文件名數據庫
tryConfigparser.pyjson
文件內容:瀏覽器
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import os import configparser '''拿到文件的路徑''' def base_path(filename = None): return os.path.join(os.path.dirname(__file__),filename) def getConfigparser(Linux = 'linux'): '''實例化對象''' config = configparser.ConfigParser() '''讀取文件內容''' config.read(base_path('config.ini')) ip = config.get(Linux,'ip') port = config.get(Linux,'port') username = config.get(Linux,'username') password = config.get(Linux,'password') return [ip,port,username,password] '''遍歷文件內容''' for i in range(len(getConfigparser())): print(getConfigparser()[i])
啓動MySQL服務 sudo / usr / local / mysql / support - files / mysql.server start 中止MySQL服務 sudo / usr / local / mysql / support - files / mysql.server stop 重啓MySQL服務 sudo / usr / local / mysql / support - files / mysql.server restart 進入MySQL數據庫 mysql - u root - p Password: 密文傳輸(shen6409175) '''查看數據庫''' show databases; '''選中數據庫''' use students; '''查看錶''' show tables; '''建立表''' create table student( -> id int primary key, -> name varchar(50), -> age varchar(10), -> address varchar(100) -> ); '''查看錶結構''' desc student; '''查看錶設計''' show create table student \g;
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import pymysql def connectMysql(): try: '''連接數據庫''' connect = pymysql.connect( host='127.0.0.1', user='root', password='shen6409175', db='students' ) except Exception as e: return e.args else: '''建立遊標''' cur = connect.cursor() '''SQL語句分離''' # sql = 'select * from student where id = %s' # params = (1,) # '''查重''' # cur.execute(sql,params) # '''單個語句的查詢''' # data = cur.fetchone() # return datas sql = 'select * from student' '''查重''' cur.execute(sql) '''返回多個數據''' datas = cur.fetchall() '''方法一,遍歷''' # for data in datas: # print(data) '''方法二,列表推倒式''' db = [data for data in datas] print(db) finally: # 關閉遊標和連接 cur.close() connect.close() connectMysql()
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import pymysql def connectMysql(): try: '''連接數據庫''' connect = pymysql.connect( host='127.0.0.1', user='root', password='shen6409175', db='students' ) except Exception as e: return e.args else: '''建立遊標''' cur = connect.cursor() '''導入數據''' # 單條語句的插入 # sql = 'insert into student values(%s,%s,%s,%s);' # params = (6,'沈~','24','南京') '''批量插入數據''' sql = 'insert into student values(%s,%s,%s,%s);' params = [ (7, '沈~', '24', '南京'), (8, '沈~', '24', '南京') ] cur.executemany(sql,params) '''insert後必需要commit()''' connect.commit() finally: # 關閉遊標和連接 cur.close() connect.close() connectMysql()
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import pymysql def connectMysql(): try: '''連接數據庫''' connect = pymysql.connect( host='127.0.0.1', user='root', password='shen6409175', db='students' ) except Exception as e: return e.args else: '''建立遊標''' cur = connect.cursor() '''導入數據''' sql = 'delete from student where id = %s' params = (7,) cur.execute(sql,params) '''執行後必需要commit()''' connect.commit() finally: # 關閉遊標和連接 cur.close() connect.close() connectMysql()
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import pymysql class MysqlTry: '''連接數據庫''' def connectMysql(self): '''嘗試連接數據庫''' try: connect =pymysql.connect( host = '127.0.0.1', user='root', password='shen6409175', db='students' ) except Exception as e: print(e.args) return connect def selectMysql(self,sql,params): '''建立遊標''' cur = self.connectMysql().cursor() '''查重''' cur.execute(sql,params) '''查詢''' result = cur.fetchone() return result def checkValid(username,age): opera = MysqlTry() sql = "select * from student where name = %s and age = %s" params=(username,age) return opera.selectMysql(sql=sql,params=params) def checkinfo(): username = input('請輸入用戶名 \n') age = input('請輸入用戶年齡 \n') result = checkValid(username,age) if result: print('該用戶在數據庫中,測試經過!') else: print('該用戶不在數據庫中,存在bug!') if __name__ == '__main__': checkinfo()
1.取csv文件內容的方法app
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import csv '''讀取csv文件的方法''' def ReadCsvlist(): '''方法一:列表方式取數據''' # '''經過列表提取csv文件''' # with open('csv.csv') as file: # '''reader是csv的迭代器''' # reader = csv.reader(file) # '''跳過首行''' # next(reader) # '''列表推倒式''' # db = [item for item in reader] # return db # # print(ReadCsvlist(),type(ReadCsvlist())) '''方法二:字典方式取數據''' with open('csv.csv',encoding='utf-8') as file: reader = csv.DictReader(file) for item in reader: print(dict(item)) ReadCsvlist()
注意⚠️:有相同執行步驟的測試用例能夠使用ddtpost
爲了建立數據驅動測試,須要在測試類上使用 @ddt 裝飾符,在測試方法上使用 @data 裝飾符。@data 裝飾符能夠把參數當作測試數據,參數能夠是單個值,列表,元組,字典,對於列表和元組,須要使用 @unpack 裝飾符把元組和列表解析成多個參數。
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import csv import requests import ddt import unittest url='https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false' def getHeaders(): headers={ 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', 'Cookie':'_ga=GA1.2.1237290736.1534169036; user_trace_token=20180813220356-b7e42516-9f01-11e8-bb78-525400f775ce; LGUID=20180813220356-b7e428ad-9f01-11e8-bb78-525400f775ce; index_location_city=%E5%85%A8%E5%9B%BD; _gid=GA1.2.675811712.1540794503; JSESSIONID=ABAAABAAAGFABEF93F47251563A52306423D37E945D2C54; _gat=1; LGSID=20181029213144-fa3c8e13-db7e-11e8-b51c-525400f775ce; PRE_UTM=; PRE_HOST=www.bing.com; PRE_SITE=https%3A%2F%2Fwww.bing.com%2F; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1539529521,1539785285,1540794503,1540819902; SEARCH_ID=ae3ae41a58d94802a68e848d36c30711; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1540819909; LGRID=20181029213151-fe7324dc-db7e-11e8-b51c-525400f775ce', 'Referer':'https://www.lagou.com/jobs/list_%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88?labelWords=sug&fromSearch=true&suginput=%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95'} return headers def f(): list1=[] t=[i for i in range(1,31)] list1.append(t) return list1 @ddt.ddt class LaGou(unittest.TestCase): @ddt.data((1,),(2,),(3,)) @ddt.unpack def test_laGou(self,page): positions = [] r = requests.post( url=url, headers=getHeaders(), data={'first': False, 'pn': page, 'kd': '自動化測試工程師'}) self.assertEqual(r.json()['success'],True) print(r.json()['content']['positionResult']['result'][0]['city']) if __name__ == '__main__': unittest.main(verbosity=2)
#!/user/bin/env python #coding:utf-8 #Author:shenqiang from ddt import data,unpack,ddt import unittest @ddt class MyDdtTest(unittest.TestCase): @data((1,1),(2,2),(3,3)) @unpack def test_ddt(self,value1,value2): print('實際參數{0},預期參數{1}'.format(value1,value2)) print(self.assertEqual(value1,value2)) if __name__ == '__main__': unittest.main(verbosity=2)
#!/user/bin/env python #coding:utf-8 #Author:shenqiang import logging from selenium import webdriver import unittest def log(log_content): # 定義文件 logFile = logging.FileHandler('log.md', 'a',encoding='utf-8') # log格式 fmt = logging.Formatter(fmt='%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s') logFile.setFormatter(fmt) # 定義日誌 logger1 = logging.Logger('', level=logging.DEBUG) logger1.addHandler(logFile) logger1.info(log_content) class Ui(unittest.TestCase): def setUp(self): self.driver=webdriver.Chrome() log('初始化瀏覽器') def test_001(self): log('開始測試') pass def tearDown(self): log('測試結束') self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)