基於API接口自動化測試框架設計

最近 python 寫測試腳本愈來愈流行,筆者結合平時工做實踐,基於 python+requests+unittest 框架編寫了一個關於http協議的接口測試自動化框架,分享以下:html

一、代碼結構:python

基於API接口自動化測試框架設計

核心代碼以下:mysql

一、commsql

數據庫訪問層:數據庫

import pymysql.cursorsjson

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

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])

二、businessdom

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

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

三、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)

**四、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)
相關文章
相關標籤/搜索