本文目錄一覽:
- 1、python寫的測試框架怎麼使用
- 2、python里pickle是什麼意思
- 3、python pickle模塊有什麼用
- 4、python中的pickle如何使用
- 5、python中pickle模塊的作用是什麼?為什麼不直接把數據存到文件中?
python寫的測試框架怎麼使用
安裝
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-8class 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 pytestdef test_main(): assert 5 != 5if __name__ == ‘__main__’:
pytest.main()
直接運行該程序,sublime 中按Ctrl+B 運行。結果如下:
============================= test session starts =============================platform win32 — Python 2.7.10 — py-1.4.30 — pytest-2.7.2rootdir: D:\pyse\pytest, inifile:
collected 4 itemstest_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 != 5E assert 5 != 5test_main.py:4: AssertionError_________________________________ test_answer _________________________________
def test_answer(): assert func(3) == 5E assert 4 == 5E + 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-8import pytestdef test_main(): assert 5 != 5if __name__ == ‘__main__’:
pytest.main(“-q test_main.py”) # 指定測試文件
運行結果:
F================================== FAILURES ===================================__________________________________ test_main __________________________________
def test_main(): assert 5 != 5E assert 5 != 5test_main.py:4: AssertionError1 failed in 0.01 seconds
那如果我想運行某個目錄下的測試用例呢?指定測試目錄即可。
#coding=utf-8import pytestdef test_main(): assert 5 != 5if __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 sysimport base64import zlibclass 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 resif __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還有許多需要討論的地方,做為這個系列的第一節,先介紹到這裡。
python里pickle是什麼意思
pickle模塊是對Python對象結構進行二進制序列化和反序列化的協議實現,就是把Python數據變成流的形式。
Python, 是一種面向對象的解釋型計算機程序設計語言,由荷蘭人Guido van Rossum於1989年發明,第一個公開發行版發行於1991年。Python是純粹的自由軟件, 源代碼和解釋器CPython遵循 GPL(GNU General Public License)協議 。Python語法簡潔清晰,特色之一是強制用空白符(white space)作為語句縮進。
python pickle模塊有什麼用
import pickle
# An arbitrary collection of objects supported by pickle.
data = {
‘a’: [1, 2.0, 3, 4+6j],
‘b’: (“character string”, b”byte string”),
‘c’: {None, True, False}
}
with open(‘data.pickle’, ‘wb’) as f:
# Pickle the ‘data’ dictionary using the highest protocol available.
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
import pickle
with open(‘data.pickle’, ‘rb’) as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.
data = pickle.load(f)
pickle模塊是對Python對象結構進行二進制序列化和反序列化的協議實現,簡單說就是把Python數據變成流的形式。像上面的例子,把數據保存或者讀入。
python中的pickle如何使用
pickle是為了序列化/反序列化一個對象的,可以把一個對象持久化存儲。
比如你有一個對象,想下次運行程序的時候直接用,可以直接用pickle打包存到硬盤上。或者你想把一個對象傳給網絡上的其他程序,可以用pickle打包,然後傳過去,那邊的python程序用pickle反序列化,就可以用了。
用法上,它主要有兩個函數:load和dump,load是從序列化之後的數據中解出來,dump是把對象序列化。看看幫助就好了,很簡單的。
python中pickle模塊的作用是什麼?為什麼不直接把數據存到文件中?
Pickle模塊中最常用的函數為:
(1)pickle.dump(obj, file, [,protocol])
函數的功能:將obj對象序列化存入已經打開的file中。
參數講解:
obj:想要序列化的obj對象。
file:文件名稱。
protocol:序列化使用的協議。如果該項省略,則默認為0。如果為負值或HIGHEST_PROTOCOL,則使用最高的協議版本。
(2)pickle.load(file)
函數的功能:將file中的對象序列化讀出。
參數講解:
file:文件名稱。
(3)pickle.dumps(obj[, protocol])
函數的功能:將obj對象序列化為string形式,而不是存入文件中。
參數講解:
obj:想要序列化的obj對象。
protocal:如果該項省略,則默認為0。如果為負值或HIGHEST_PROTOCOL,則使用最高的協議版本。
(4)pickle.loads(string)
函數的功能:從string中讀出序列化前的obj對象。
原創文章,作者:BRBPZ,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/325100.html