Pytest裝飾器@pytest.mark.parametrize數據驅動(三)​

  • 2019 年 11 月 6 日
  • 筆記

Python Pytest裝飾器@pytest.mark.parametrize詳解

【Pytest篇】裝飾器@pytest.mark.parametrize多樣參數化(二)

一、測試用例用excel管理,存放地址:C:UserswangliPycharmProjectsTesttestfilesapiCase.xls

二、程式碼實現如下:

1、封裝讀取excel用例數據

2、Pytest裝飾器@pytest.mark.parametrize('參數名',list)實現登錄模組2條測試用例數據驅動

    import pytest,xlrd,os,requests,json    #獲取excel用例數據  def get_case_data():      case_path = os.path.join(os.path.dirname(__file__), r'filesapiCase.xls')      book = xlrd.open_workbook(case_path)      sheet = book.sheet_by_name('sheet1名字')      case = []      for i in range(0, sheet.nrows):          if sheet.row_values(i)[0] == 'C端登錄' and sheet.row_values(i)[3]=='YES':              case.append(sheet.row_values(i))      return case    class Test(object):        def setup_class(self):          pass        def teardown_class(self):          pass        #調用獲取測試用例數據      case_data=get_case_data()      #使用裝飾器參數化用例數據      @pytest.mark.parametrize('Function,TestCase,Type,Run,URL,Headers,Parameter,SQL1,SQL2,SQL3,AssertType,Expect1,Expect2,Expect3', case_data)      def test_login1(self,Function,TestCase,Type,Run,URL,Headers,Parameter,SQL1,SQL2,SQL3,AssertType,Expect1,Expect2,Expect3):          r=requests.post(url=URL,headers=eval(Headers),json=eval(Parameter))          response=r.json()          print(response)          assert eval(Expect1)['code']==response['code']          assert eval(Expect1)['msg'] == response['msg']      if __name__=="__main__":      pytest.main(["-s","test02.py"])      "C:Program FilesPython35python.exe" C:/Users/wangli/PycharmProjects/Test/test/test02.py  ============================= test session starts =============================  platform win32 -- Python 3.5.2, pytest-5.1.2, py-1.8.0, pluggy-0.12.0  rootdir: C:UserswangliPycharmProjectsTesttest  plugins: allure-pytest-2.8.5, html-1.22.0, metadata-1.8.0  collected 2 items    test02.py {'msg': '成功', 'code': 0, 'data': {'token': 'bearereyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9tZW1iZXItYXBpLnN0Mi50ZXN0LmxhbnhpbmthLmNvbVwvMi4wXC91c2Vyc1wvbG9naW4iLCJpYXQiOjE1NzI3NTE4MDUsImV4cCI6MTU3NDA0NzgwNSwibmJmIjoxNTcyNzUxODA1LCJqdGkiOiJpS2ZKZGdBam0xQWoyRmc1Iiwic3ViIjo1ODQ5MDIsInBydiI6IjNhN2IwNmU5NTBkMDhlMjMzMjkyMjdjN2E2YTUyMzQyYWJiNGYxOWIiLCJidXNpbmVzc190eXBlIjoiNiJ9.1bYj4VslhNMU3yjBtxccCG6fAWNwH8jhAacC6cl-f_A'}}  .{'msg': '驗證碼錯誤', 'code': 220002, 'data': {}}  .    ============================== 2 passed in 0.75s ==============================    Process finished with exit code 0

通過以上實驗,我們可以看出如果測試模組有100條測試用例,同樣用以上程式碼可以實現測試並斷言出結果,是不是很簡單呢。