postman接口用例转化为python自动化测试用例

1,161 阅读2分钟

这是我参与8月更文挑战的第15天,活动详情查看:8月更文挑战 

很多人可能会用postman,python,但是不会写测试脚本,想要快速写python自动化测试的脚本, postman里面有完成的用例。可是不会写python脚本,想要转化,本次呢,我就将postman复制code到python代码里面,需要的步骤。给大家讲解一下。

首先我们去打开postman,我们可以将我们写好的用例呢,导出成python代码,

    示例用的图灵接口:

image.png 那么我们有了这条postman用例,我们点击Code,

image.png 选择要导出的语言,这里我选择的是python,选择requests库去导出代码

image.png 那么我们看看生成的代码,


import requests

url = "http://openapi.tuling123.com/openapi/api/v2"

payload = "{\r\n\t\r\n    \"userInfo\": {\r\n        \"apiKey\": \"\",\r\n        \"userId\": \"\"\r\n    }\r\n}"
headers = {
    'Content-Type': "application/json",
    'User-Agent': "PostmanRuntime/7.19.0",
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Postman-Token': "25132ec6-9d02-421c-ab22-773b1fd70035,65c29f56-030a-4d3d-862f-ad0de3ed50a6",
    'Host': "openapi.tuling123.com",
    'Accept-Encoding': "gzip, deflate",
    'Content-Length': "78",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

我们将代码复制到编辑器中,

        如果没有reuqests库,可能会报错,我们需要安装reuqests库。

        命令:

pip install reuqests

那么我们去运行一下。

image.png 我们看下执行结果,

image.png 这里缺少断言,我们去增加我们断言就好。

image.png 我们的断言是假设 里面有code字段就认为成功了。 运行代码结果

image.png 我们这样 就是一个简单的测试脚本。

        有人会问,怎么转成unittest测试用例呢。

        我们先去引入unittest

        然后去定义一个测试类继承unittest.TestCase

   去写测试用例。

import requests
import unittest

class Testcase(unittest.TestCase):
    def tearDown(self) -> None:
        pass
    def setUp(self) -> None:
        pass
    def testone(self):
        url = "http://openapi.tuling123.com/openapi/api/v2"

        payload = "{\r\n\t\r\n    \"userInfo\": {\r\n        \"apiKey\": \"\",\r\n        \"userId\": \"\"\r\n    }\r\n}"
        headers = {
            'Content-Type': "application/json",
            'User-Agent': "PostmanRuntime/7.19.0",
            'Accept': "*/*",
            'Cache-Control': "no-cache",
            'Postman-Token': "25132ec6-9d02-421c-ab22-773b1fd70035,65c29f56-030a-4d3d-862f-ad0de3ed50a6",
            'Host': "openapi.tuling123.com",
            'Accept-Encoding': "gzip, deflate",
            'Content-Length': "78",
            'Connection': "keep-alive",
            'cache-control': "no-cache"
            }

        response = requests.request("POST", url, data=payload, headers=headers)

        self.assertTrue("code" in response.text)
if __name__=="__main__":
    unittest.main()

接下来我们去执行这个测试用例。

image.png 这样 我们就直接把postman里面的一个用例到到python形成一个自动化测试用例。然而这只是一个开始。