使用 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 则以高性能和底层控制能力闻名。

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python在游戏和GUI开发中表现出色。1)游戏开发使用Pygame,提供绘图、音频等功能,适合创建2D游戏。2)GUI开发可选择Tkinter或PyQt,Tkinter简单易用,PyQt功能丰富,适合专业开发。

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。
