最近 python 写测试脚本越来越流行,笔者结合平时工作实践,基于 python+requests+unittest 框架编写了一个关于http协议的接口测试自动化框架,分享如下:

1、代码结构:

基于API接口自动化测试框架设计_第1张图片

核心代码如下:

1、comm

数据库访问层:

import pymysql.cursors

mysql_host = '192.168..'
mysql_user ='root'
mysql_password = '123456'
mysql_database = 'account'

class mysql_operation():
def init(self,mysql_host,mysql_user,mysql_password,mysql_database):
self.host = mysql_host
self.user = mysql_user
self.password = mysql_password
self.database = mysql_database

def connect_select(self,sql):
    conn = pymysql.Connect(self.host,self.user,self.password,self.database,charset='utf8')
    cur=conn.cursor()
    cur.execute(sql)
    d = list(cur.fetchone())
    conn.close()
    return (d[0])

2、business

import requests
import random
import logging
from comm.mysql_operation import mysql_operation,mysql_host,mysql_user,mysql_password

mobile = '130123456787'
host='http://consumer-app.test.cn/'

class consumer_app():
def init(self,mobile,host):
self.host= host
self.mobile_rand = '13455' + str(random.randint(111111, 999999))
self.mobile = mobile
self.s = requests.Session()

    def CopyCart(self):
    url = host + '/copyCart'
    sql = "SELECT ID from order  where order_status=\'finish\' ORDER BY id ASC;"
    mysql_operation_new = mysql_operation(mysql_host, mysql_user, mysql_password, 'order')
    card_copyid = mysql_operation_new.connect_select(sql)

    data = {"orderId": card_copyid}
    try:
        Copy_Cart = self.s.post(url=url, json=data)

    except Exception as e:
        logging.exception(e)
    else:
        if Copy_Cart.json()['code'] == 'success':
            print('再来一单购买成功!')
            return 1

3、testcase

import unittest
from business.consumer_app import consumer_app,mobile,host
import time

class Account(unittest.TestCase):
def setUp(self):
self.account_new = consumer_app(mobile, host)

def tearDown(self):
    pass

def test01_login_success(self):
    result = self.account_new.login()
    self.assertEqual(result,1)
    time.sleep(1)

    def test02_CopyCart(self):
    result = self.account_new.CopyCart()
    self.assertEqual(result,1)

**4、run testcase**

import unittest
import time
import os.path
from testcase.testcase import Account
from comm import HTMLTestRunner_PY3
from comm.send_mail import send_mail,From_addr,To_addr,smtpserver,password
import os.path

report_path = os.path.join(os.getcwd(), 'report')

if name=="main":
now = time.strftime("%Y-%m-%d-%H%M%S", time.localtime(time.time()))

suite1 = unittest.TestLoader().loadTestsFromTestCase(Account)
suite = unittest.TestSuite([suite1])

file_path = os.path.join(report_path, "result_" + now + ".html")
fr = open(file_path, 'wb')
report = HTMLTestRunner_PY3.HTMLTestRunner(stream=fr,verbosity=2,title='测试报告', description='测试报告详情')
report.run(suite)
fr.close()

send_mail(From_addr, To_addr, smtpserver, password,file_path)