在网上找的接口测试的代码,自己稍微修改了一下,
参数写成这样的时候
postparams = {'desc': {'areaCode': '010', 'username': u'立春', 'Password': '123456'}, 'method': 'tutorLogin'}
报错如下:
Error
Traceback (most recent call last):
File "E:\Users\Administrator\PycharmProjects\APITestDemo\TestMyLogin\TestLoginInter02.py", line 57, in test_call
data = api.apicall('POST', 'http://180.76.139.233/ceshi/liveReportRest', getparams, postparams)
File "E:\Users\Administrator\PycharmProjects\APITestDemo\TestMyLogin\TestLoginInter02.py", line 39, in apicall
response = urllib2.urlopen(req)
File "C:\Python27\lib\urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 437, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 475, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 409, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 500: Internal Server Error
如果把立春前面的 u 去掉的时候
postparams = {'desc': {'areaCode': '010', 'username': '立春', 'Password': '123456'}, 'method': 'tutorLogin'}
执行后的结果
{u'msg': u'\u7528\u6236\u540d\u3001\u5bc6\u7801\u9519\u8bef', u'rlt': u'false', u'totalPage': 0, u'code': u'000000', u'data': u''}
转成中文提示用户名密码错误,可是我用 jmeter 里面跑这个接口是能正常生成结果的,请看图片
最后贴上代码,各位大神帮忙看看问题出在哪里?用户名到底该怎样传入?
# -*- coding: utf_8 -*-
import urllib2
import urllib
import json
import unittest
class APITest():
def apicall(self, method, url, getparams, postparams):
str1 = ''
# GET
if method == 'GET':
if getparams != "":
for k in getparams:
str1=str1+k+'='+urllib2.quote(str(getparams.get(k)))
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(url, data)
response = urllib2.urlopen(req)
result = response.read()
jsdata = json.loads(result)
return jsdata
class APIGetAdList(unittest.TestCase):
def test_call(self):
api = APITest()
getparams = ''
postparams = {'desc': {'areaCode': '010', 'username': '立春', 'Password': '123456'}, 'method': 'tutorLogin'}
data = api.apicall('POST', 'http://180.76.139.233/ceshi/liveReportRest', getparams, postparams)
print '-----------' + u'立春'
print '-----------' + '立春'
print data
print '-----------'
if __name__ == "__main__":
unittest.main()