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-tw/n/325100.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
BRBPZ的頭像BRBPZ
上一篇 2025-01-13 13:23
下一篇 2025-01-13 13:23

相關推薦

  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29

發表回復

登錄後才能評論