天天看點

接口自動化練習

一、考試系統

1. 導入類

import unittest
import requests
from public.get_exam_cookie import get_exam_cookie
import time
           

2. 用例1-考試系統背景-登入

class MyTestCase(unittest.TestCase):
    def test_008_exam_login(self):
        '''考試系統背景-登入'''
        url = 'http://182.92.178.83:8088/api/user/login'
        payload_login = {"userName": "admin", "password": "123456", "remember": False}
        login = requests.post(url, json=payload_login, timeout=30)
        self.assertEqual('成功',login.json()['message'])
           

3. 用例2-考試系統背景-使用者管理-管理者-添加

def test_009_new_admin(self):
    '''考試系統背景-使用者管理-管理者-添加'''
    #添加
    url = 'http://182.92.178.83:8088/api/admin/user/edit'
    global now_time
    now_time = int(time.time())
    payload_new_admin ={"id":'null',
                        "userName":'大白貓%d'%now_time,
                        "password":now_time,
                        "realName":"大白貓",
                        "role":3,"status":1,"age":"2","sex":"1",
                        "birthDay":'2020-11-09 00:00:00',
                        "phone":'13434544567'}
    global headers_admin
    headers_admin ={'Cookie':get_exam_cookie()}
    new_admin = requests.post(url,json=payload_new_admin,headers =headers_admin ,timeout =30)
    response = new_admin.json()
    global admin_id
    admin_id = response['response']['id']
    #斷言
    self.assertEqual('成功',response['message'])  #傳回資訊為成功
    global exp_userName
    exp_userName = payload_new_admin['userName']
    act_userName = response['response']['userName']
    self.assertEqual(exp_userName, act_userName)  #傳回添加的使用者名與實際添加的使用者名相等
           

4. 用例3-考試系統背景-使用者管理-管理者清單-查詢

def test_010_admin_search(self):
    '''考試系統背景-使用者管理-管理者清單-查詢'''
    #查詢
    url = 'http://182.92.178.83:8088/api/admin/user/page/list'
    payload_search = {"userName":exp_userName,"role":3,"pageIndex":1,"pageSize":10}
    search = requests.post(url, json=payload_search, headers=headers_admin, timeout=30)
    response = search.json()
    #斷言
    self.assertEqual('成功', response['message'])
    exp_search_name = payload_search['userName']
    act_search_name = response['response']['list'][0]['userName']
    self.assertEqual(exp_search_name, act_search_name)
           

5. 用例4-考試系統背景-使用者管理-管理者-編輯

def test_011_admin_edit(self):
        '''考試系統背景-使用者管理-管理者-編輯'''
        url = 'http://182.92.178.83:8088/api/admin/user/edit'
        payload_admin_edit = {"id":admin_id,
                              "userUuid":"",
                              "userName":'胖白%d'%now_time,
                              "realName":"胖白",
                              "age":'3', "role":3,"sex":'2',
                              "birthDay":"2020-12-09 00:00:00",
                              "phone":'13412345567',
                              "lastActiveTime":"","createTime":"","modifyTime":"","status":1,
                              "userLevel":'null',
                              "imagePath":'null',
                              "password":"admin%d"%now_time}
        admin_edit = requests.post(url,json=payload_admin_edit,headers=headers_admin ,timeout=30)
        response = admin_edit.json()
        # 斷言
        self.assertEqual('成功', response['message'])  # 傳回資訊為成功
        exp_userName = payload_admin_edit['userName']
        act_userName = response['response']['userName']
        self.assertEqual(exp_userName, act_userName)  # 傳回更改的使用者名與實際更改的使用者名相等
           

6. 用例5-考試系統背景-使用者管理-管理者-更改狀态

def test_012_change_status(self):
    '''考試系統背景-使用者管理-管理者-更改狀态'''
    #修改狀态
    url = 'http://182.92.178.83:8088/api/admin/user/changeStatus/'+str(admin_id)
    change_status = requests.post(url,headers=headers_admin ,timeout=30)
    #斷言
    response = change_status.json()
    self.assertEqual('成功',response['message'] )
           

7. 用例6-考試系統背景-使用者管理-管理者-删除

def test_013_admin_delete(self):
    '''考試系統背景-使用者管理-管理者-删除'''
    #删除
    url = 'http://182.92.178.83:8088/api/admin/user/delete/'+str(admin_id)
    admin_delete = requests.post(url,headers=headers_admin ,timeout=30)
    #斷言
    response = admin_delete.json()
    self.assertEqual('成功', response['message'])
           

8. get_exam_cookie.py

import requests

def get_exam_cookie():   #擷取考試系統背景的cookie
    url = 'http://182.92.178.83:8088/api/user/login'
    payload_login = {"userName": "admin", "password": "123456", "remember": False}
    login = requests.post(url, json=payload_login, timeout=30)
    dict_cookie = requests.utils.dict_from_cookiejar(login.cookies)
    cookie = 'SESSION='+dict_cookie['SESSION']
    return cookie
           

二、V部落

1. 導入類

import unittest
import requests
from public.get_vblog_cookie import get_vblog_cookie
import time
           

2. 用例1-V部落-登入

class MyTestCase(unittest.TestCase):
    def test_001_login_vblog(self):
        '''V部落-登入'''
        url = 'http://182.92.178.83:8081/login'
        payload = {'username': 'sang', 'password': '123'}
        login = requests.post(url, data=payload,timeout=30)
        exp = '登入成功'
        act = login.json()['msg']
        self.assertEqual(exp, act)
           

3. 用例2-V部落-發表文章

def test_002_new_article(self):
        '''V部落-發表文章'''
        # 新增
        url1 = 'http://182.92.178.83:8081/article/'
        global now_time
        now_time = int(time.time())
        payload = {'id': '-1', 'title': '咕噜咕噜%d' % now_time, 'mdContent': '春眠不覺曉',
                   'htmlContent': '', 'cid': '62','state': '1', 'dynamicTags': '貓'}
        global vblog_headers
        vblog_headers = {'Cookie': get_vblog_cookie()}
        requests.post(url1, data=payload, headers=vblog_headers, timeout=30)
        # 查詢
        url2 = 'http://182.92.178.83:8081/article/all'
        result = requests.get(url2, headers=vblog_headers, timeout=30)
        #斷言
        exp = payload['title']
        act = '123'
        for chaxun_info in result.json()['articles']:
            if chaxun_info['title'] == exp:
                global article_id
                article_id = chaxun_info['id']
                act = chaxun_info['title']
        self.assertEqual(exp, act)
           

4. 用例3-V部落-文章清單-已發表-編輯

def test_003_edit_atrtical(self):
        '''V部落-文章清單-已發表-編輯'''
        # 編輯
        url = 'http://182.92.178.83:8081/article/'
        global payload_edit
        payload_edit = {'id': article_id, 'title': '胖白%d' % now_time, 'mdContent': '處處聞啼鳥',
                        'htmlContent': '', 'cid': '62', 'state': '1', 'dynamicTags': '大白貓'}
        requests.post(url, data=payload_edit, headers=vblog_headers)

        # 查詢
        url2 = 'http://182.92.178.83:8081/article/all'
        result = requests.get(url2, headers=vblog_headers, timeout=30)

        #斷言
        exp = payload_edit['title']
        act = '123'
        for chaxun_info2 in result.json()['articles']:
            if chaxun_info2['title'] == exp:
               act = chaxun_info2['title']
        self.assertEqual(exp, act)
           

5. 用例4-V部落-文章清單-已發表-删除

def test_004_delete_atrtical(self):
    '''V部落-文章清單-已發表-删除'''
    # 删除
    url = 'http://182.92.178.83:8081/article/dustbin'
    payload3 = {'aids': article_id, 'state': '1'}
    requests.put(url, data=payload3, headers=vblog_headers, timeout=30)

    # 查詢
    url2 = 'http://182.92.178.83:8081/admin/article/all?page=1&count=6&keywords='
    result_delete = requests.get(url2, headers=vblog_headers, timeout=30)

    #斷言
    act =True
    delete_title = payload_edit['title']
    for chaxun_info in result_delete.json()['articles']:
        if chaxun_info['title'] == delete_title:
            act=False
        else:
            continue
    self.assertEqual(True, act)
           

6. 用例5-V部落-欄目管理-新增欄目

def test_005_new_catenames(self):
    '''V部落-欄目管理-新增欄目'''
    # 新增
    url = 'http://182.92.178.83:8081/admin/category/'
    payload = {'cateName': 'lxh%d' % now_time}  # 将時間戳拼到新增欄目後面
    requests.post(url, data=payload, headers=vblog_headers)

    # 查詢
    url_chaxun = 'http://182.92.178.83:8081/admin/category/all'
    chaxun = requests.get(url_chaxun, headers=vblog_headers)

    # 斷言
    exp = payload['cateName']  # 預期輸入值
    act = '123'  # 先随便賦給act一個值,如果在下面的清單中沒有找到期望值,則act等于這個值
    for catenameinfo in chaxun.json():
        if catenameinfo['cateName'] == exp:
            global cateName_id  # 将cateName_id定義為全局變量
            cateName_id = catenameinfo['id']
            act = catenameinfo['cateName']
    self.assertEqual(exp, act)
           

7. 用例6-V部落-欄目管理-編輯欄目

def test_006_edit_catename(self):
        '''V部落-欄目管理-編輯欄目'''
        #編輯
        url = 'http://182.92.178.83:8081/admin/category/'

        payload_edit_catename = {'id':cateName_id,'cateName':'啊啊啊啊%d'%now_time}  #使用全局變量cateName_id
        requests.put(url,data=payload_edit_catename,headers=vblog_headers)  #使用全局變量vblog_headers

        #查詢
        url_chaxun = 'http://182.92.178.83:8081/admin/category/all'
        chaxun = requests.get(url_chaxun, headers=vblog_headers)

        exp = payload_edit_catename['cateName']  #預期欄目
        act = 'abc'
        for catenameinfo_edit in chaxun.json():
            if catenameinfo_edit['id']==cateName_id:  #如果找到了編輯欄目的id,則将該欄目的cateName指派給實際結果
                act = catenameinfo_edit['cateName']
        self.assertEqual(exp,act)
           

8. 用例7-V部落-欄目管理-删除欄目

def test_007_delete_catename(self):
        '''V部落-欄目管理-删除欄目'''
        #删除
        url = 'http://182.92.178.83:8081/admin/category/'+str(cateName_id)
        requests.delete(url,headers=vblog_headers)

        #查詢
        url = 'http://182.92.178.83:8081/admin/category/all'
        result_delete = requests.get(url,headers=vblog_headers)

        #斷言
        act = True
        delete_catename_id = cateName_id
        for chaxun_info in result_delete.json():
            if chaxun_info['id'] == delete_catename_id:
                act = False
            else:
                continue
        self.assertEqual(True, act)
           

9. get_vblog_cookie.py

import requests
def get_vblog_cookie():   #擷取V部落cookie
    url = 'http://182.92.178.83:8081/login'
    payload = {'username': 'sang', 'password': '123'}
    login = requests.post(url, data=payload)
    cookies = login.cookies
    dict_cookie = requests.utils.dict_from_cookiejar(cookies)  # 從cookiejar裡面傳回一個字典
    cookie = 'JSESSIONID=' + dict_cookie['JSESSIONID']  # 拿到需要的cookie資訊,将其拼接起來
    return cookie
           

三、testrunner.py

import unittest
import time
import os,sys
from report.HTMLTestRunner import HTMLTestRunner  #HTMLTestRunner是一個開源的生成一個HTML報告的類


# 擷取目前py檔案路徑位址,并進行路徑分割(分割成目錄路徑和檔案名稱)
dirname,filename=os.path.split(os.path.abspath(sys.argv[0]))  #分割TestRunner.py檔案執行的絕對路徑
#前一部分(路徑)給dirname,後一部分(py檔案名稱)給filename
print(dirname,filename)
case_path = ".\\case\\"  #定義case_path為目前路徑下的case下的路徑
result = dirname+"\\report\\"  #定義result為目前路徑下的report路徑

def Creatsuite():
    #定義單元測試容器
    testunit = unittest.TestSuite()  #初始化對象,TestSuite是測試套件

    #定義搜尋用例檔案的方法,将所有py檔案放到discover裡面
    discover = unittest.defaultTestLoader.discover(case_path, pattern='*.py', top_level_dir=None)

    #将測試用例加入測試容器中
    for test_suite in discover:  #周遊所有discover的所有py檔案
        for casename in test_suite:
            testunit.addTest(casename)  #将py檔案中的所有test方法加到測試套件中
        #print testunit
    return testunit

test_case = Creatsuite()   #調用了上面的方法

#擷取系統目前時間
now = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))  #年月日時分秒
day = time.strftime('%Y-%m-%d', time.localtime(time.time()))  #年月日

#定義個報告存放路徑,支援相對路徑
tdresult = result + day

if os.path.exists(tdresult): # 檢驗檔案夾路徑是否已經存在
    filename = tdresult + "\\" + now + "_result.html"  #定義報告名稱,精确到秒
    fp = open(filename, 'wb')  #打開
    #定義測試報告
    runner = HTMLTestRunner(stream=fp,  #以流的形式寫
                            title='測試報告',
                            description='執行情況:')

    #運作測試用例
    runner.run(test_case)
    fp.close()  #關閉報告檔案
else:
    os.mkdir(tdresult) # 建立測試報告檔案夾
    filename = tdresult + "\\" + now + "_result.html"
    fp = open(filename, 'wb')
    #定義測試報告
    runner = HTMLTestRunner(stream=fp,
                            title='Selenium測試報告',
                            description='執行情況:')

    #運作測試用例
    runner.run(test_case)
    fp.close()  #關閉報告檔案
           

繼續閱讀