天天看點

python接口測試jason_淺談Python接口對json串的處理方法

最近學習Python接口測試,對于接口測試完全小白。大概一周的學習成果進行總結。

1.接口測試:

目前涉及到的隻是對簡單單一的接口進行參數傳遞,得到傳回自。

2.關于各種概念:

2.1 http請求包含post方法、get方法。通過json串或XML傳遞,但後者未做研究

2.2 GET: 浏覽器告訴伺服器,隻擷取頁面資訊,并發送給我。

2.3 POST:浏覽器告訴伺服器想法不一些資訊到某個網址,伺服器需確定資料被存儲且隻存儲一次。

2.4 HEAD:浏覽器告訴伺服器,給我消息頭,像get那樣被接收。

2.5 Python對資料的處理子產品可以使用urllib、urllib2子產品或requests子產品

3.urllib、urllib2執行個體

#coding=utf_8

import urllib2,urllib

import json

import unittest,time,re

class APITest():

"""

接口測試類

"""

def api_test(self, method, url, getparams, postparams):

str1 = ''

#GET方法調用

if method == 'GET':

if getparams != "":

for x in getparams:

str1 = str1 + x + '=' + urllib2.quote(str(getparams.get(x)))

if len(getparams) > 2:

str1 = str1 + "&"

url = url + "&" + str1

result = urllib2.urlopen(url).read()

#POST方法調用

if method=='POST':

if postparams != "":

data = urllib.urlencode(postparams)

req = urllib2.Request(data)

response = urllib2.urlopen(req)

result = response.read()

#result轉為json資料

jsdata = json.loads(result)

return jsdata

class APIGetRes(unittest.TestCase):

def test_call(self):

api = APITest()

getparams={'keyword':'測試'}

postparams=''

data = api.api_test('GET','http://api.zhongchou.cn/deal/list?v=1',getparams,postparams)

print data

if (data['errno']!=""):

self.assertEqual(0, data['errno'])

print"接口 deal/list-------------OK!"

else:

print"接口 deal/list-------------Failure!"

self.assertEqual(0, data['errno'])

if __name__ == '__main__':

unittest.main()

Requests執行個體

#coding=utf_8

import requests

import json

import unittest,time,re

class APIGetAdlis(unittest.TestCase):

def test_call(self):

github_url='http://api.zhongchou.cn/deal/list?v=1'

data = json.dumps({'keyword':'測試'})

resp = requests.post(github_url,data)

print resp.json

#if (data['errno']!=''):

# self.assertEqual(0, data['errno'])

# print"接口 deal/list-------------OK!"

#else:

# print"接口 deal/list-------------Failure!"

# self.assertEqual(0, data['errno'])

粗略了解,待深入學習!

以上這篇淺談Python接口對json串的處理方法就是小編分享給大家的全部内容了,希望能給大家一個參考,也希望大家多多支援我們。

本文标題: 淺談Python接口對json串的處理方法

本文位址: http://www.cppcns.com/jiaoben/python/247914.html