在python测试中使用http存档(har)文件

test-har的Python项目详细描述


要将此请求发送到api后端并断言api响应与 响应…

{"log":{"version":"1.2","entries":[{"request":{"method":"POST","url":"mock://example.com/users/","headers":[{"name":"Accept","value":"application/json"}],"postData":{"mimeType":"application/json","text":{"username":"foo_username","email":"foo@example.com","group":"479e75e6-755a-46f1-a949-d6fee3671b3c"}},"comment":"Test validation errors"},"response":{"status":201,"statusText":"Created","headers":[{"name":"Allow","value":"GET, POST, HEAD, OPTIONS"},{"name":"Vary","value":"Accept, Cookie"}],"content":{"mimeType":"application/json","text":{"username":"foo_username"}}}}]}}

使用此测试:

importdatetime# Import the appropriate backend for your framework.# Currently there are backends for the `requests` library...fromtest_har.requests_harastest_har# and for the Django ReST Framework.# from test_har.django_rest_har as test_har# Contributions for other frameworks welcome!from..importmodelsclassMyAPITest(test_har.HARTestCase):"""
    Specify the HAR file to use by default.
    """# Path to file relative to this test file# Set to `None` to skip automatic HAR parsing and set upexample_har='example.har.json'deftest_my_response(self):"""
        Write your test as you would.
        """# For convenience, `self.example` is the parsed JSON in# `self.example_har`, `self.entry` is the first request/response# entry from `log/entries/0` in the HAR., `self.headers` is a# dictionary of the response headers for that entry, and# `self.content` is the response body content from that entry.# Make any changes to the test fixture necessary for the test such# as creating related objects before a POST that requires them.group=models.Group(name='foo_group',uuid=self.entry["request"]["postData"]["text"]["group"])# Make any changes to the HAR necessary for the assertions to work# before sending the requestsself.content["some_dynamic_value"]=models.my_dynamic_function()# Send the HAR requests, assert responses match the HAR, and return# the responses.  Currently, assertions are made against the# response: `Status` code, `Status` reason text, `Content-Type`# MIME type, other headers in the HAR, and the response body# content.  If the response MIME type is a JSON type,# then assertions will be made against each top-level key# individually and ignore any key in the response not included in# the HAR.now=datetime.datetime.now()responses=self.assertHAR(self.example)# Make any other assertions, or do anything else you'd like to do,# with the responses.self.assertAlmostEqual(datetime.strptime(response[0].json()['created'],format='...'),now,delta=datetime.timedelta(seconds=1),msg='Wrong automatic creation time')deftest_my_other_response(self):"""
        Test a different HAR file.
        """# Replace `self.example` and the other convenience attributes with# the content form another HAR fileself.setUpHAR('other.har.json')responses=self.assertHAR(self.example)...

为什么?

为api后端编写测试通常会涉及到 用于构造内容的测试,该内容可以发布到api,也可以是预期的 对其作出断言的响应中的内容。例如, 构造一个python字典来表示发布到或返回的json 从API。类似地,测试返回的内容通常需要很多 详细的断言,以便充分涵盖api的行为方式。

虽然编写这种重复的测试代码是乏味的,但更重要的是,它不是 可读性强,能够识别测试的预期行为 掩盖不必要的困难。理想情况下,人们应该能够描述 API的预期行为格式与 应用程序编程接口。另外,理想情况下,一个人应该能够清楚地阅读相关的请求和 一起回应。

浏览器用于记录的基于json的HTTP Archive(har)格式 浏览器会话提供了这样一种格式,特别是基于json的 原料药。test-har包提供了使用har文件驱动的支持 测试并对响应做出更常见的断言 允许开发人员继续使用 har文件和其他文件一样。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
如何使用java在linux上编写系统日志   如何在同一个现有变量上多次更改变量的值?(爪哇)   易失性字符串Java   java需要帮助通过PreparedStatement编写适当的搜索查询   JavaMaven项目是否获得其他Maven项目的版本?   java如何在Eclipse中使用Drool应用程序抑制信息和警告调试信息   Java中FileReader和FileInputStream的区别是什么?   java如何为此编写HQL查询?   java方法根本不返回任何内容   VLCJ通过单个java程序控制多个音频文件   java为什么这个println命令不开始一个新行?   java如何创建自己的文件扩展名。odt或。医生?   声明字符串后,java在条件语句中设置int值   通过k8s作业文件将cmd参数传递给docker容器中的java应用程序