首页  >  文章  >  后端开发  >  使用 Sheepy 在 Python 中进行单元测试

使用 Sheepy 在 Python 中进行单元测试

Patricia Arquette
Patricia Arquette原创
2024-09-25 06:27:32291浏览

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