Python單元測試框架之pytest 1 ---如何執行測試用例


From: https://www.cnblogs.com/fnng/p/4765112.html

介紹                                                                     

  pytest是一個成熟的全功能的Python測試工具,可以幫助你寫出更好的程序。

適合從簡單的單元到復雜的功能測試

  • l 模塊化parametrizeable裝置(在2.3,持續改進)
  • l 參數化測試函數(用例)
  • l 標記測試功能與屬性
  • l Skip和xfail:處理不成功的測試用例(在2.4改進)
  • l 通過xdist插件分發測試到多個CPU
  • l 不斷地重新運行失敗的測試
  • l 靈活約定的Python測試發現

Home Page: http://pytest.org

 

 

安裝                                                                    

>pip install -U pytest   # 通過pip安裝

>py.test --version        # 查看pytest版本

 This is pytest version 2.7.2, imported from C:\Python27\lib\site-packages\pytest.pyc

 

 

簡單的測試                                                           

  

  讓我們創建第一個文件,對個簡單的功能進行測試。

復制代碼
#coding=utf-8 # 功能 def func(x): return x + 1 # 測試用例 def test_answer(): assert func(3) == 5
復制代碼

 切換到測試文件所在的目錄,通過“py.test”命令運行測試。

>py.test 

執行結果如下圖:

 

===================================================================

在一個測試類中創建多個測試用例:

復制代碼
#coding=utf-8 class TestClass: def test_one(self): x = "this" assert "h" in x def test_two(self): x = "hello" assert x == "hi"
復制代碼

運行測試:

>py.test -q test_class.py

-q  quiet。表示在安靜的模式輸出報告訴。加不加這個參有什么區別呢? 讀者可以對比一下兩次輸出的日志。其實,就是少了一些pytest的版本信息。

 

===================================================================

 

Python代碼中調用pytest

pytest中同樣提供了main() 來函數來執行測試用例。

pytest/

├── test_sample.py

├── test_class.py

└── test_main.py

此目錄為我們練習的目錄,打開test_mian.py

復制代碼
import pytest def test_main(): assert 5 != 5 if __name__ == '__main__': pytest.main()
復制代碼

 直接運行該程序,sublime 中按Ctrl+B 運行。結果如下:

復制代碼
============================= test session starts ============================= platform win32 -- Python 2.7.10 -- py-1.4.30 -- pytest-2.7.2 rootdir: D:\pyse\pytest, inifile: collected 4 items test_class.py .F test_main.py F test_sample.py F ================================== FAILURES =================================== _____________________________ TestClass.test_two ______________________________ self = <test_class.TestClass instance at 0x000000000304F548> def test_two(self): x = "hello" > assert x == "hi" E assert 'hello' == 'hi' E - hello E + hi test_class.py:11: AssertionError __________________________________ test_main __________________________________ def test_main(): > assert 5 != 5 E assert 5 != 5 test_main.py:4: AssertionError _________________________________ test_answer _________________________________ def test_answer(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:9: AssertionError ===================== 3 failed, 1 passed in 0.03 seconds ====================== [Finished in 0.3s]
復制代碼

 

  從執行結果看到,main() 默認執行了當前文件所在的目錄下的所有測試文件。

  那么,如果我們只想運行某個測試文件呢?可以向main()中添加參數,就像在cmd命令提示符下面一樣:

復制代碼
#coding=utf-8 import pytest def test_main(): assert 5 != 5 if __name__ == '__main__': pytest.main("-q test_main.py") # 指定測試文件
復制代碼

 運行結果:

復制代碼
F ================================== FAILURES =================================== __________________________________ test_main __________________________________ def test_main(): > assert 5 != 5 E assert 5 != 5 test_main.py:4: AssertionError 1 failed in 0.01 seconds
復制代碼

 

那如果我想運行某個目錄下的測試用例呢?指定測試目錄即可。

復制代碼
#coding=utf-8 import pytest def test_main(): assert 5 != 5 if __name__ == '__main__': pytest.main("d:/pyse/pytest/") # 指定測試目錄
復制代碼

 

 

 創建運行測試腳本                                                  

 

  有時候我們的測試用例文件分散在不同的層級目錄下,通過命令行的方式運行測試顯示不太方便,如何編寫一個運行所有測試用例的腳本呢? pytest可以自動幫我們生成這樣的腳本。

>py.test --genscript=runtests.py

打開生成的測runtests.py文件:

復制代碼
sources = """ eNrsve2S3EiSIDa3+jhtnvZ293Ra6SSdCZMUF0AzK1nk9OzM1nV2L4dNznKnm6TxY6dX1XVJVAJV halMIAkgWVU3O2d6Ar3CPYQeQn/1QjKTf8UnAplZ7O6ZPTNxpiszgQiPCA8PD3cPD/f/449+9/5H yds/W99M58v6fDqfl1XZzefv/9nbvxuPxxE8Oy+r8+jRy2dREq+bOt8siqaNo6zKo3hRV+1mRb/h a1UsuiKPPpRZdFncXNVN3qYRABmN3v/R23+OLbRd/v6/ePOf/tmPflSu1nXTRe1NOxotllnbRq+7 PKlPfwMw0qNR …… """ import sys import base64 import zlib class DictImporter(object): def __init__(self, sources): self.sources = sources def find_module(self, fullname, path=None): if fullname == "argparse" and sys.version_info >= (2,7): # we were generated with <python2.7 (which pulls in argparse) # but we are running now on a stdlib which has it, so use that. return None if fullname in self.sources: return self if fullname + '.__init__' in self.sources: return self return None def load_module(self, fullname): # print "load_module:", fullname from types import ModuleType try: s = self.sources[fullname] is_pkg = False except KeyError: s = self.sources[fullname + '.__init__'] is_pkg = True co = compile(s, fullname, 'exec') module = sys.modules.setdefault(fullname, ModuleType(fullname)) module.__file__ = "%s/%s" % (__file__, fullname) module.__loader__ = self if is_pkg: module.__path__ = [fullname] do_exec(co, module.__dict__) # noqa return sys.modules[fullname] def get_source(self, name): res = self.sources.get(name) if res is None: res = self.sources.get(name + '.__init__') return res if __name__ == "__main__": if sys.version_info >= (3, 0): exec("def do_exec(co, loc): exec(co, loc)\n") import pickle sources = sources.encode("ascii") # ensure bytes sources = pickle.loads(zlib.decompress(base64.decodebytes(sources))) else: import cPickle as pickle exec("def do_exec(co, loc): exec co in loc\n") sources = pickle.loads(zlib.decompress(base64.decodestring(sources))) importer = DictImporter(sources) sys.meta_path.insert(0, importer) entry = "import pytest; raise SystemExit(pytest.cmdline.main())" do_exec(entry, locals()) # noqa
復制代碼

 好吧!其實, 我也不理解這段代碼的含義,但是執行它的可運行測試用例了。

pytest/

├── test_case/

│   ├── test_sample.py

│   ├── test_class.py

│   ├── __init__.py

│   └── test_case2/

│          ├── test_main.py

│          ├── test_time.py

│          └── __init__.py

└── runtests.py

 

執行runtest.py文件。

>python runtest.py

當然,你也可以打開runtests.py 文件運行它。

 

===================================================================

最后,pytest是如果識別測試用例的呢?它默認使用檢查以test_ *.py 或*_test.py命名的文件名,在文件內部查找以test_打頭的方法或函數,並執行它們。

pytest還有許多需要討論的地方,做為這個系列的第一節,先介紹到這里。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM