點擊上方藍字關注我!
python
一個簡單的接口案例
sql
def test_movie_check():'http://api.douban.com/v2/movie/in_theaters' url = params = {'apikey': '0df993c66c0c636e29ecbb5344252a4a', 'start': 0, 'count': 10 } headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" } r = requests.get(url=url, params=params, headers=headers) response = r.json()'count'] == params['count'] assert response['start'] == params['start'] assert response['title'] == '正在上映的電影-北京' assert response[
pytest+yaml
shell
◆ yaml.load() : 讀取yaml文件;json
◆ yaml.load_all() : 生成迭代器,若存在多塊yaml文檔的時候,使用解析所有文檔;api
◆ yaml.dump(params1,params2) : yaml.dump將python對象生成yaml文檔 params1 json格式的文檔 ,params2 打卡一個文本或二進制文件,將生成的yaml文件寫到文件中;微信
◆ yaml.dump_all() 將多個段輸出到一個文件;app
第一步:編寫yaml文件,準備測試接口數據
框架
test: case: 驗證響應參數是否一致 requests: method: GET path: /v2/movie/in_theaters headers: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 : params: apikey: 0df993c66c0c636e29ecbb5344252a4a start: 0 count: 10 validate: title: 正在上映的電影-北京 count: 10 start: 0
第二步:編寫test_movie.py文件,get_test_data方法返回測試數據編輯器
python的zip用法:學習
def get_test_data(filepath): case = [] # 存放測試用例名 requests = [] # 存放http請求對象 validate = [] # 存放斷言 with open(filepath, encoding='utf-8') as f: data = yaml.load(f.read(), Loader=yaml.SafeLoader) case.append(data.get('test')) requests.append(data.get('requests')) validate.append(data.get('validate')) params = zip(case, requests, validate) return case, paramscases, parameters = comm_function.get_test_data('D:/workFile/test/pytest_demo/data/test_movie.yaml')list_params = list(parameters)print(list_params[0][1])
@pytest.mark.parametrize 參數化,若yaml中有多條案例,會執行屢次。
class TestInTheaters(object): def test_in_theaters(self, case, http, validate): host = 'http://api.douban.com' res = requests.request(http['method'], url=host+http['path'], headers=http['headers'], params=http['params']) response = res.json() assert response['count'] == validate['count'] assert response['start'] == validate['start'] assert response['title'] == validate['title']
歡迎小夥伴們進羣一塊兒學習,一塊兒加油!
本文分享自微信公衆號 - 軟件測試小助手(gh_2282fef3410c)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。