大家好,今天我來跟大家介紹一個新的單元測試庫,叫做sheepy,但是首先我們來談談單元測試的重要性。該庫不適合初學者,要使用它進行單元測試,您需要額外注意。它僅具有用於使用端點和 http 錯誤檢查模組進行 API 測試的斷言。
Github連結:github
PyPi 連結:pypi
生產中所有成熟、有自尊的軟體都有單元測試,無論是為了了解程式碼中已有的內容是否仍然有效,為了防止先前已經報告和修復的錯誤,還是為了測試新功能,它很好地表明他們正在向前推進,並且沒有累積技術債。我們以火狐瀏覽器為例,每個目錄下都有一個tests子目錄,針對已經報告的bug進行專門的測試,這樣就保證了已經修復的bug不會再憑空出現,已經修復的bug就會出現又無處可去這叫丟錢。隨著時間的推移,您將失去時間、金錢、效率和市場份額,而競爭對手卻比您做得更好,資源更少。
每個覺得自己無能為力的人都會試圖誹謗那件事,單元測試也不例外。創建覆蓋每個用例的更好的單元測試需要時間,就像生活中的一切一樣,你的後端我懷疑你只閱讀了一個教程並做出了完美的api,對於你的前端來說也是如此,我懷疑你看了一門課程並來了使介面變得完美。所以不要認為單元測試會有什麼不同!
斷言方法
+-----------------------+-------------------------------------------------------+ | Assertion Method | Description | +-----------------------+-------------------------------------------------------+ | assertEqual(a, b) | Checks if two values are equal. | | assertNotEqual(a, b) | Checks if two values are not equal. | | assertTrue(expr) | Verifies that the expression is True. | | assertFalse(expr) | Verifies that the expression is False. | | assertRaises(exc, fn) | Asserts that a function raises a specific exception. | | assertStatusCode(resp) | Verifies if the response has the expected status code.| | assertJsonResponse(resp)| Confirms the response is in JSON format. | | assertResponseContains(resp, key) | Ensures the response contains a given key. | +-----------------------+-------------------------------------------------------+
安裝
安裝非常簡單,只需打開您選擇的終端,安裝 pip 並輸入 pip install Sheepy
使用範例
from sheepy.sheeptest import SheepyTestCase class ExampleTest(SheepyTestCase): def test_success(self): self.assertTrue(True) def test_failure(self): self.assertEqual(1, 2) def test_error(self): raise Exception("Forced error") @SheepyTestCase.skip("Reason to ignore") def test_skipped(self): pass @SheepyTestCase.expectedFailure def test_expected_failure(self): self.assertEqual(1, 2)
SheepyTestCase 類別提供了用於建立和執行單元測試的多種功能,包括用於配置特殊行為的斷言方法和機制,例如跳過測試或處理預期的失敗。
在ExampleTest類別中,定義了五個測試方法:
test_success:此測試檢查傳遞給assertTrue方法的表達式是否為true。由於 True 值已明確傳遞,因此此測試將成功。
test_failure:此測試使用assertEqual方法檢查兩個值之間的相等性。然而,比較值1和2不同,這導致測試失敗。這演示了預期失敗的情況,其中測試必須檢測到不一致。
test_error:此方法會引發一個有目的的異常,並顯示訊息「強制錯誤」。目標是測試系統在處理測試執行期間發生的錯誤時的行為。由於該方法拋出異常而不對其進行處理,因此測試結果將是錯誤。
test_skipped:此測試已使用 SheepyTestCase 類別的 Skip 方法進行修飾,這表示在執行測試時將跳過它。跳過測試的原因被提供為“忽略的原因”,並且這個理由可以在最終的測試報告中顯示。
test_expected_failure:此方法使用expectedFailure裝飾器,表示預期會發生失敗。在方法內部,在1 和2 之間存在相等性檢查,這通常會導致失敗,但是隨著裝飾器的應用,框架認為這種失敗是預期行為的一部分,不會被視為錯誤,但是作為“預期的失敗」。
輸出
測試結果:
ExampleTest.test_error:失敗 - 強制錯誤
ExampleTest.test_expected_failure:預期失敗
ExampleTest.test_failure: FAIL - 1 != 2
ExampleTest.test_skipped: 跳過 -
ExampleTest.test_success: 好的
API 測試案例
Sheepy 測試框架中的 API 測試設計簡單但功能強大,允許測試人員使用常見的 HTTP 方法(如 GET、POST、PUT 和 DELETE)與 API 進行互動。該框架提供了一個專用類別 ApiRequests 來簡化發送請求和處理回應,並透過 HttpError 異常類別進行內建錯誤管理。
測試API時,測試類別繼承自SheepyTestCase,它配備了各種斷言方法來驗證API的行為。其中包括用於驗證 HTTP 狀態碼的assertStatusCode、用於確保回應採用 JSON 格式的assertJsonResponse 以及用於檢查回應正文中是否存在特定鍵的assertResponseContains。
For instance, the framework allows you to send a POST request to an API, verify that the status code matches the expected value, and assert that the JSON response contains the correct data. The API requests are handled through the ApiRequests class, which takes care of constructing and sending the requests, while error handling is streamlined by raising HTTP-specific errors when the server returns unexpected status codes.
By providing built-in assertions and error handling, the framework automates much of the repetitive tasks in API testing, ensuring both correctness and simplicity in writing tests. This system allows developers to focus on verifying API behavior and logic, making it an efficient tool for ensuring the reliability of API interactions.
from sheepy.sheeptest import SheepyTestCase class TestHttpBinApi(SheepyTestCase): def __init__(self): super().__init__(base_url="https://httpbin.org") def test_get_status(self): response = self.api.get("/status/200") self.assertStatusCode(response, 200) def test_get_json(self): response = self.api.get("/json") self.assertStatusCode(response, 200) self.assertJsonResponse(response) self.assertResponseContains(response, "slideshow") def test_post_data(self): payload = {"name": "SheepyTest", "framework": "unittest"} response = self.api.post("/post", json=payload) self.assertStatusCode(response, 200) self.assertJsonResponse(response) self.assertResponseContains(response, "json") self.assertEqual(response.json()["json"], payload) def test_put_data(self): payload = {"key": "value"} response = self.api.put("/put", json=payload) self.assertStatusCode(response, 200) self.assertJsonResponse(response) self.assertResponseContains(response, "json") self.assertEqual(response.json()["json"], payload) def test_delete_resource(self): response = self.api.delete("/delete") self.assertStatusCode(response, 200) self.assertJsonResponse(response)
Output example
Test Results: TestHttpBinApi.test_delete_resource: OK TestHttpBinApi.test_get_json: OK TestHttpBinApi.test_get_status: OK TestHttpBinApi.test_post_data: OK TestHttpBinApi.test_put_data: OK
Summary:
The new sheepy library is an incredible unit testing library, which has several test accession methods, including a module just for API testing, in my opinion, it is not a library for beginners, it requires basic knowledge of object-oriented programming such as methods, classes and inheritance.
以上是使用 Sheepy 在 Python 中進行單元測試的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

Python的statistics模塊提供強大的數據統計分析功能,幫助我們快速理解數據整體特徵,例如生物統計學和商業分析等領域。無需逐個查看數據點,只需查看均值或方差等統計量,即可發現原始數據中可能被忽略的趨勢和特徵,並更輕鬆、有效地比較大型數據集。 本教程將介紹如何計算平均值和衡量數據集的離散程度。除非另有說明,本模塊中的所有函數都支持使用mean()函數計算平均值,而非簡單的求和平均。 也可使用浮點數。 import random import statistics from fracti

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

文章討論了虛擬環境在Python中的作用,重點是管理項目依賴性並避免衝突。它詳細介紹了他們在改善項目管理和減少依賴問題方面的創建,激活和利益。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

記事本++7.3.1
好用且免費的程式碼編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),