我正在尝试计算数据数组中的用户数量(见下文)。如您所见,我可以成功从response.json获取数据。所以基本上我能够打印DATA,但我发现很难找到一个代码来计算数据中的用户数量,我知道用户数量是5但是我想在我添加一个额外的用户时计数会自动增加。
代码:
'''
security service tests
'''
import sys
sys.path.append('..')
import requests
import json
from common.constants import *
from config.settings import environment
security_environment = environment()['security_service']
service_url = "%s://%s:%d" % (
security_environment['protocol'],
security_environment['host'],
security_environment['port'])
def test1():
print "TEST 1 - get user details"
headers = {'Accept': 'application/json'}
url = "%s/users" % service_url
response = requests.get(url, headers=headers)
status_code = response.status_code
print "STATUS: %s" % status_code
print "DATA: %s" % response.json()
return status_code == HTTP_OK
if __name__ == "__main__":
num_pass = 0
num_fail = 0
for test in [test1]:
print "-----------------------------------------------------------"
if test():
num_pass += 1
print "PASS"
else:
num_fail += 1
print "FAIL"
print "==========================================================="
print "%d passed, %d failed" % (num_pass, num_fail)
结果:
TEST 1 - get user details
STATUS: 200
DATA: [{u'status': u'enabled', u'created_at': u'2016-02-09 10:49:28', u'id': 1, u'updated_at': u'2016-02-09 10:49:28', u'name': u'bart'}, {u'status': u'disabled', u'created_at': u'2016-02-09 10:49:28', u'id': 2, u'updated_at': u'2016-02-09 10:49:28', u'name': u'lisa'}, {u'status': u'enabled', u'created_at': u'2016-02-09 10:49:28', u'id': 3, u'updated_at': u'2016-02-09 10:49:28', u'name': u'homer'}, {u'status': u'disabled', u'created_at': u'2016-02-09 10:49:28', u'id': 4, u'updated_at': u'2016-02-09 10:49:28', u'name': u'marge'}, {u'status': u'enabled', u'created_at': u'2016-02-09 10:49:28', u'id': 5, u'updated_at': u'2016-02-09 10:49:28', u'name': u'maggie'}]
PASS
===========================================================
1 passed, 0 failed
任何帮助?
答案 0 :(得分:0)
如果列表仅包含用户,则最直接的解决方案是使用 len()功能。
此代码输出5:
.html("");