pytest使用

前置安裝

pip install -U requests -i https://mirrors.aliyun.com/pypi/simple/

requests模塊安裝

pip install -U pytest -i https://mirrors.aliyun.com/pypi/simple/

pytest模塊安裝

requests創(chuàng)建接口請求
def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) <timeouts>` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'https://httpbin.org/get')
      >>> req
      <Response [200]>
    """

常用封裝好的POST、GET、PUT等請求

requests.post(url="http://www.xxxx", params={"key": "value"}, data={"key": "value"})
requests.get(url="http://www.xxxx", params={"key": "value"}, data={"key": "value"})
pytest文件/文件夾命名要求

1.模塊名稱必須格式test_*.py*_test.py
2.測試類必須以Test開頭,且沒有構(gòu)造方法
3.函數(shù)方法必須以test_開頭

案例

import requests

class ECMobile():
    baseUrl = "http://localhost/ECMobile/?url="
    loginUrl = f"{baseUrl}/user/signin"
    addToCartUrl = f"{baseUrl}/cart/create"
    orderUrl = f"{baseUrl}/flow/done"

    sid = ""
    uid = ""
    isLogin = False
    status = None

    def login(self, username = None, password = None):
        content = {}
        if username != None:
            content["name"] = username
        if password != None:
            content["password"] = password
        content = str(content)
        content = content.replace("\'", "\"")
        data = {
            "json": content
        }
        print("request_body: ")
        print(data) 
        req = requests.post(url=self.loginUrl, data=data)
        requests.post(url="http://www.xxxx", params={"key": "value"}, data={"key": "value"})
        jsondata = req.json()
        print("login json start " + "=" * 80)
        print(jsondata)
        print("login json end " + "=" * 80)
        self.status = req.status_code
        if jsondata["status"]["succeed"] == 1:
            self.isLogin = True
            self.sid = jsondata["data"]["session"]["sid"]
            self.uid = jsondata["data"]["session"]["uid"]
            print("login_success")
        else:
            self.isLogin = False
            self.sid = ""
            self.uid = ""
            print("login_fail")

    def addToCart(self, goods_id = None, spec = None, num = None):
        content = {}
        if self.isLogin:
            userinfo = {}
            userinfo["sid"] = self.sid
            userinfo["uid"] = self.uid
            content["session"] = userinfo
        if goods_id != None:
            content["goods_id"] = str(goods_id)
        if spec != None:
            content["spec"] = [spec]
        if num != None:
            content["number"] = str(num)
        content = str(content)
        content = content.replace("\'", "\"")
        data = {
            "json": content
        }
        print("request_body: ")
        print(data)
        req = requests.post(url=self.addToCartUrl, data=data)
        jsondata = req.json()
        print("addToCart json start " + "=" * 80)
        print(jsondata)
        print("addToCart json end " + "=" * 80)
        self.status = jsondata["status"]["succeed"]
        if jsondata["status"]["succeed"] == 1:
            print("addToCart_success")
        else:
            print("addToCart_fail")

    def order(self, pay_id = None, shipping_id = None, bonus = None, integral = None, inv_type = None, inv_content = None, inv_payee = None):
        content = {}
        if self.isLogin:
            userinfo = {}
            userinfo["sid"] = self.sid
            userinfo["uid"] = self.uid
            content["session"] = userinfo
        if pay_id != None:
            content["pay_id"] = pay_id
        if shipping_id != None:
            content["shipping_id"] = shipping_id
        if bonus != None:
            content["bonus"] = bonus
        if integral != None:
            content["integral"] = integral
        if inv_type != None:
            content["inv_type"] = inv_type
        if inv_content != None:
            content["inv_content"] = inv_content
        if inv_payee != None:
            content["inv_payee"] = inv_payee
        content = str(content)
        content = content.replace("\'", "\"")
        data = {
            "json": content
        }
        print("request_body: ")
        print(data)
        req = requests.post(url=self.orderUrl, data=data)
        jsondata = req.json()
        print("addToCart json start " + "=" * 80)
        print(jsondata)
        print("addToCart json end " + "=" * 80)
        self.status = jsondata["status"]["succeed"]
        if jsondata["status"]["succeed"] == 1:
            print("order_success")
        else:
            print("order_fail")

創(chuàng)建pytest類

class Test_ECMobile_Interface:

創(chuàng)建測試用函數(shù)并實現(xiàn)斷言

    def test_login_success(self):
        self.ec.login("ecshop", "ecshop")
        assert self.ec.isLogin

main函數(shù)調(diào)用

if __name__ == '__main__':
    pytest.main()

完整代碼

import pytest
from ecshop_request_FN.data.ecmobile import *

class Test_ECMobile_Interface:
    ec = None

    def setup_method(self):
        print("setup_method")
        self.ec = ECMobile()

    @pytest.mark.smoking
    def test_login_success(self):
        self.ec.login("ecshop", "ecshop")
        assert self.ec.isLogin

    def test_login_username_error(self):
        self.ec.login("errorname", "abc123")
        assert not self.ec.isLogin

    def test_login_without_password(self):
        self.ec.login("ecshop")
        assert not self.ec.isLogin

    @pytest.mark.smoking
    def test_add_cart_success(self):
        self.ec.login("ecshop", "ecshop")
        self.ec.addToCart(goods_id=9, spec=227, num=1)
        assert self.ec.status == 1

    def test_add_cart_without_login(self):
        self.ec.addToCart(goods_id=9, spec=227, num=1)
        assert self.ec.status != 1

    def test_add_cart_unsale_goods(self):
        self.ec.login("ecshop", "ecshop")
        self.ec.addToCart(goods_id=31, num=1)
        assert self.ec.status != 1

    @pytest.mark.smoking
    def test_order_goods(self):
        self.ec.login("ecshop", "ecshop")
        self.ec.addToCart(goods_id=9, spec=227, num=1)
        self.ec.order(pay_id=3, shipping_id=3)
        assert self.ec.status == 1

    def test_order_without_payid(self):
        self.ec.login("ecshop", "ecshop")
        self.ec.addToCart(goods_id=9, spec=227, num=1)
        self.ec.order(shipping_id=3)
        assert self.ec.status != 1

    def test_order_without_login(self):
        self.ec.addToCart(goods_id=9, spec=227, num=1)
        self.ec.order(pay_id=3, shipping_id=3)
        assert self.ec.status != 1

if __name__ == '__main__':
    pytest.main()

pytest修飾器

    @pytest.mark.smoking
    def test_login_success(self):
        self.ec.login("ecshop", "ecshop")
        assert self.ec.isLogin

為函數(shù)添加名為smoking的標(biāo)簽
可以通過pytest -m smoking調(diào)用所有帶smoking標(biāo)簽的函數(shù)

# 參數(shù)化
# @pytest.mark.parametrize("變量名逗號隔開",列表[(每個變量的值), ()])
# 測試方法需要帶參數(shù)
@pytest.mark.parametrize("datas, expect", [
    ((1, 2, 3), 6),  # passed
    ((1, 2, 3, 4), 0),  # fail
    ((5, 0, -5), 0)  # passed
])
def test_int_02(datas, expect):
    x = plus(*datas)  # plus(1, 2, 3)
    assert x == expect

通過@pytest.mark.parametrize實現(xiàn)參數(shù)化

命令行執(zhí)行
pytest [選項] [文件或目錄]

常用選項

選項 說明
-s 表示輸出調(diào)試信息,包括 print打印的信息
-v 顯示更詳細的信息, -vs:這兩個參數(shù)通常一起用
-n num 支持多線程或者分布式運行測試用例
--html=path 表示生成html測試報告
--reruns=count 表示失敗重跑
-p no:warnings 取消警告
--ff 先執(zhí)行上次失敗的用例
--lf 只執(zhí)行上次失敗的用例
-x 遇到測試用例fail,就結(jié)束測試
--maxfail=num 遇到num條測試用例fail, 就結(jié)束測試
-k 根據(jù)測試用例的部分字符串指定測試用例
-m markname 將運行用@pytest.mark.標(biāo)簽名 裝飾的所有測試
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • pytest使用 1、pytest簡介 官檔是最好的教程 pytest是一個非常成熟的全功能的Python測試框架...
    道無虛閱讀 4,437評論 1 5
  • 1. 概述 pytest是一個非常成熟的全功能的Python測試框架,主要特點有以下幾點: 1、簡單靈活,容易上手...
    紅薯愛帥閱讀 263,272評論 6 81
  • 前言 pytest 是 python 的第三方單元測試框架,比自帶 unittest 更簡潔和高效,支持315種以...
    梵音11閱讀 337評論 0 0
  • pytest是第三方開發(fā)的一個python測試模塊,可以輕松地編寫小型測試,而且可以擴展以支持應(yīng)用程序和庫的復(fù)雜功...
    何小有閱讀 9,834評論 0 3
  • 寫在前面 文檔中一部分摘抄了pytest中文文檔和百度的搜索結(jié)果,記錄下來方便自己以后查閱。 參數(shù)選項 -s 允許...
    Lacia閱讀 119評論 0 0

友情鏈接更多精彩內(nèi)容