接口测试python实现脚本测试笔记。

一、requests模块

(1)安装pip install requests
(2)使用前导入import requests

二、GET请求ddt自动化

(1)代码结构:

1)构造Header
2)构造cookies
3)发送Get请求
4)获取返回值
5)对结果进行校验

(2)代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python3
#coding=utf-8

import requests
import unittest
import ddt

@ddt.ddt
class ApiTestClass(unittest.TestCase):

@ddt.data('android','','ios')
def test_Get(self,os_phone):
#header部分配置
headers = {'User-Agent':'Dalvik/1.6.0 (Linux; U; Android 4.3; Coolpad 8720L Build/JSS15Q)',
'Host':'bdsp.x.jd.com',
'Connection':'Keep-Alive',
'Accept-Encoding':'gzip'
}

#cookies部分配置
cookies = dict(search_test = '1')

#get请求获得返回数据
res = requests.get('http://bdsp.x.jd.com/app/config?os='+os_phone+'&key=wx3ebc9e606b4f9242&sdkv=5',
headers = headers,
cookies = cookies)

print(res.text)
print(res.status_code)

#测试点校验
self.assertTrue('15*1000' in res.text)

if __name__ == '__main__':
cases = unittest.TestLoader().loadTestsFromTestCase(ApiTestClass)
suite = unittest.TestSuite([cases])
#suite.addTest(ApiTestClass('test_Get'))

runner = unittest.TextTestRunner()
runner.run(suite)

三、POST请求ddt自动化

(1)代码结构:

1)构造Keyword(即request body)
2)构造Header
3)构造cookies
4)发送Get请求
5)获取返回值
6)对结果进行校验

(2)代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import requests
import unittest
import ddt

@ddt.ddt
class ApiTestClass(unittest.TestCase):

@ddt.data(('60.206.137.140','hjfwp9VflXZU3FsuM3cu6PBV'),
('','')
)
@ddt.unpack
def test_Post(self,m_host,m_accessToken):
#header部分配置
headers = {'Content-Type':'application/x-www-form-urlencoded',
'Content-Length':'36',
'Host':m_host,
'Connection':'Keep-Alive',
'Accept-Encoding':'gzip',
'User-Agent':'okhttp/3.8.1'
}

#cookies部分配置
cookies = dict(search_test = '1')

#data部分配置
keyword = {'accessToken':m_accessToken}

#post请求获得返回数据
res = requests.post('http://60.206.137.140/iot_api/family/queryFamilyList.json',
headers = headers,
cookies = cookies,
data = keyword
)

print(res.text)
print(res.status_code)

#测试点校验
self.assertTrue('北京市北京市' in res.text)

if __name__ == '__main__':
cases = unittest.TestLoader().loadTestsFromTestCase(ApiTestClass)
suite = unittest.TestSuite([cases])
#suite.addTest(ApiTestClass('test_Post'))

runner = unittest.TextTestRunner()
runner.run(suite)

持续更新…

最后更新: 2018年05月11日 15:10

原始链接: http://pythonfood.github.io/2018/04/01/接口测试-python/

× 多少都行~
打赏二维码