首頁  >  文章  >  後端開發  >  使用 Sheepy 在 Python 中進行單元測試

使用 Sheepy 在 Python 中進行單元測試

Patricia Arquette
Patricia Arquette原創
2024-09-25 06:27:32292瀏覽

Unit testing in Python with sheepy

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn