pytest文檔64-內置 pytestconfig 動態添加和獲取 pytest.ini 配置參數


前言

前面講 pytestconfig 的時候,可以獲取到 pytest.ini 里面的配置參數。
我們在寫項目自動化用例的時候,有一些配置參數希望能加到配置里面,如configid, productid,以及測試環境的base_url地址,和賬號相關信息。

addini的源碼閱讀

addini有四個參數:name, help, type=None, default=None

    def addini(self, name, help, type=None, default=None):
        """ register an ini-file option.

        :name: name of the ini-variable
        :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``
               or ``bool``.
        :default: default value if no ini-file option exists but is queried.

        The value of ini-variables can be retrieved via a call to
        :py:func:`config.getini(name) <_pytest.config.Config.getini>`.
        """
        assert type in (None, "pathlist", "args", "linelist", "bool")
        self._inidict[name] = (help, type, default)
        self._ininames.append(name)

動態添加配置信息

前面一篇講添加命令行參數,可以用 addoption 來添加命令行參數,這里我們是添加 pytest.ini 的配置信息
adddini里面參數說明

  • 第一個'url' 是參數的名稱
  • type 是類型,默認None,可以設置:None, "pathlist", "args", "linelist", "bool"
  • default 是設置的默認值
  • help 是設置幫助文檔,方便查閱
# conftest.py
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

def pytest_addoption(parser):
    parser.addoption(
        "--cmdopt", action="store", default="type1", help="my option: type1 or type2"
    )
    # 添加參數到pytest.ini
    parser.addini('url', type=None, default="http://49.235.92.12:8200/", help='添加 url 訪問地址參數')


# 獲取 pytest.ini 配置參數
@pytest.fixture(scope="session")
def home_url(pytestconfig):
    url = pytestconfig.getini('url')
    print("\n讀取到配置文件的url地址:%s" % url)
    return url

參數用例傳 home_url

# test_y.py

def test_h(home_url):
    print("用例:%s" % home_url)

運行結果

============================= test session starts =============================
platform win32 -- Python 3.6.6, pytest-4.5.0, py-1.9.0, pluggy-0.13.1
rootdir: D:\wangyiyun\web
collected 1 item

..\..\..\..\..\wangyiyun\web\test_y.py 
讀取到配置文件的url地址:http://49.235.92.12:8200/
用例:http://49.235.92.12:8200/
.

========================== 1 passed in 0.02 seconds ===========================

pytest.ini 配置 url地址

如果有一天我們的測試環境發生了改變,這時候不需要去改代碼,只需在 pytest.ini 配置一個環境地址

[pytest]


url = https://www.cnblogs.com/yoyoketang/

重新運行,我們得到的結果是

============================= test session starts =============================
platform win32 -- Python 3.6.6, pytest-4.5.0, py-1.9.0, pluggy-0.13.1
rootdir: D:\wangyiyun\web
collected 1 item

..\..\..\..\..\wangyiyun\test_y.py 
讀取到配置文件的url地址:https://www.cnblogs.com/yoyoketang/
用例:https://www.cnblogs.com/yoyoketang/
.

========================== 1 passed in 0.02 seconds ===========================

type參數的幾種類型

默認None,可以設置:None, "pathlist", "args", "linelist", "bool"

  • type=None 默認讀的是字符串
  • type="pathlist" 可以設置多個路徑,會自動拼接ini文件這一層目錄
  • type="args" 多個參數
  • type="linelist" 可以是多個命令行參數
  • type="bool" bool值,設置1或0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM