51Testing软件测试论坛

标题: 微服务平台API测试 [打印本页]

作者: 测试积点老人    时间: 2019-1-2 13:44
标题: 微服务平台API测试
1. 项目结构是这样的。

[attach]120590[/attach]

2. 通用函数代码
  1. <font size="3">import json,pymysql,collections

  2. def read_json(path):
  3.     with open(path,'r',encoding = 'utf-8') as load_f:
  4.         load_dict = json.load(load_f)
  5.     return load_dict

  6. def read_sql():
  7.     db = pymysql.connect(db='chameleon_user', host='172.16.78.71', port=3306, user='root', passwd='1qazxsw2',charset='utf8')
  8.     cursor = db.cursor()
  9.     sql = 'select * from `%s`' % ('role')
  10.     cursor.execute(sql)
  11.     rows = cursor.fetchall()
  12.     objects_list = []
  13.     for row in rows:
  14.         d = collections.OrderedDict()
  15.         d['cardnum'] = row[0]
  16.         d['bankname'] = row[1]
  17.         d['phonenumber'] = row[2]
  18.         d['rest'] = row[3]
  19.         d['id_main'] = row[4]
  20.         objects_list.append(d)

  21.         j = json.dumps(objects_list)
  22.         return j

  23. if __name__ == "__main__":
  24.     json_from_sql = read_sql()
  25.     print(json_from_sql)
  26. </font>
复制代码
3. 登陆代码
  1. <font size="3">import requests
  2. import json

  3. class login():
  4.     headers = {'Content-Type': 'application/json;charset=utf-8',
  5.                 'token': 'planceholder',
  6.                 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
  7.                 'userId': 'planceholder'
  8.                 }

  9.     def __init__(self):
  10.         self.login_url = 'http://172.16.78.72:8301/v1/chameleon-user/user/login'
  11.         self.form_data = {'account':'admin',
  12.                          'password':'zs123YL!'}


  13.     def get_login_token(self):
  14.         try:
  15.             r = requests.post(self.login_url,headers=self.headers,data = json.dumps(self.form_data))
  16.             login_return_dicts = r.json()
  17.             self.headers['token'] = login_return_dicts['token']
  18.             self.headers['userId']= str(login_return_dicts['data']['userId'])
  19.             #print(login_return_dicts)
  20.         except:
  21.             print('登陆平台失败!获取Token失败')
  22.         return

  23. if __name__ == '__main__':
  24.     l = login()
  25.     l.get_login_token()
  26.     print(login.headers['token'])
  27.     print(login.headers['userId'])
  28. </font>
复制代码
4. 模块运行
  1. <font size="3"># coding=utf-8
  2. import requests,sys
  3. import unittest
  4. import json
  5. from common.read_file import read_json as readjson
  6. from common.login_platform import login as login

  7. login = login()
  8. login.get_login_token()

  9. class RunInstance(unittest.TestCase):
  10.       def setUp(self):
  11.             self.headers = login.headers
  12.             self.instance_data = readjson(r'C:\Users\wenhuifu\PycharmProjects\xu_api\Data\cloudmanager\RunInstance.json')
  13.             self.url = 'http://172.16.78.73:3011/api/chameleon-cvg/instance'

  14.       #@unittest.skip('不测试!')
  15.       def test_run_instance(self):
  16.             try:
  17.               r = requests.post(self.url,headers = self.headers,json = self.instance_data)
  18.               print(r.json())
  19.             except:
  20.               #print(err)
  21.               print('创建机器失败!')

  22.             assert r.status_code == 200

  23.       def tearDown(self):
  24.             pass


  25. if __name__ == '__main__':
  26.       create = RunInstance()
  27.       create.test_run_instance()
  28. </font>
复制代码
5. 生成测试报告
  1. <font size="3">from HTMLTestRunner_PY3 import HTMLTestRunner
  2. from email.mime.text import MIMEText
  3. from email.header import Header
  4. import smtplib
  5. import unittest
  6. import time
  7. import os

  8. #发送邮件
  9. def send_mail(file_new):
  10.     f = open(file_new,'rb')
  11.     mail_body = f.read()
  12.     f.close()

  13.     msg = MIMEText(mail_body,'html','utf-8')
  14.     msg['Subject'] = Header("自动化测试报告",'utf-8')

  15.     smtp = smtplib.SMTP()
  16.     smtp.connect('smtp.126.com')
  17.     smtp.login("username@126.com","123456")
  18.     smtp.sendmail("username@126.com","receive@126.com",msg.as_string())
  19.     smtp.quit()
  20.     print('Email has been send out!')

  21. def new_report(testreport):
  22.     lists = os.listdir(testreport)
  23.     lists.sort(key = lambda fn:os.path.getmtime(testreport + "\\" + fn))
  24.     file_new = os.path.join(testreport,lists[-1])
  25.     print(file_new)
  26.     return file_new

  27. if __name__ == "__main__":
  28.     now = time.strftime("%Y-%m-%d %H_%M_%S")
  29.     filename = './Report/' + now + ' result.html'
  30.     fp = open(filename,'wb')
  31.     runner = HTMLTestRunner(stream=fp,title = 'XU API Test Result',description= '环境 Windows 10')
  32.     discover = unittest.defaultTestLoader.discover('./Testcase',pattern= '*_case.py')
  33.     runner.run(discover)
  34.     fp.closed
  35. </font>
复制代码
6. 测试报告还是很直观的。

[attach]120591[/attach]








欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2