使用 Sheepy 在 Python 中進行單元測試
大家好,今天我來跟大家介紹一個新的單元測試庫,叫做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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

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

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

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。
