搜尋
首頁後端開發Python教學使用 Sheepy 在 Python 中進行單元測試

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
python中兩個列表的串聯替代方案是什麼?python中兩個列表的串聯替代方案是什麼?May 09, 2025 am 12:16 AM

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

Python:合併兩個列表的有效方法Python:合併兩個列表的有效方法May 09, 2025 am 12:15 AM

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

編譯的與解釋的語言:優點和缺點編譯的與解釋的語言:優點和缺點May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:對於循環,最完整的指南Python:對於循環,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

python concatenate列表到一個字符串中python concatenate列表到一個字符串中May 09, 2025 am 12:02 AM

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

了解python的' for”和' then”循環之間的差異了解python的' for”和' then”循環之間的差異May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串聯列表與重複Python串聯列表與重複May 08, 2025 am 12:09 AM

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版

SublimeText3 Mac版

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

mPDF

mPDF

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

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具