前言
當我們自動化代碼寫完成之后,期望能在不同的環境測試,這時候應該把 base_url 單獨拿出來,能通過配置文件和支持命令行參數執行。
pytest-base-url 是 pytest 里面提供的一個管理 base-url 的一個非常實用的插件,參考文檔https://pypi.org/project/pytest-base-url/
環境准備
先安裝 pytest-base-url 插件
pip install pytest-base-url
使用案例
直接在用例里面使用 base_url參數 當成一個fixture使用
# test_demo.py
import requests
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
def test_example(base_url):
assert 200 == requests.get(base_url).status_code
命令行執行的時候加上 --base-url
參數
pytest --base-url http://www.example.com
D:\soft\web_base>pytest --base-url http://www.example.com
=========== test session starts ==============
platform win32 -- Python 3.6.0, pytest-4.5.0, py-1.5.4, pluggy-0.13.1
baseurl: http://www.example.com
rootdir: D:\soft\web_base
plugins: allure-pytest-2.8.6, base-url-1.4.2
collected 1 item
test_demo.py . [100%]
============= 1 passed in 0.73 seconds ============
pytest.ini 配置文件
也可以在 pytest.ini 配置文件中添加 base_url 地址
# pytest.ini文件內容
[pytest]
base_url = http://www.example.com
這樣在命令行執行時候就可以不用帶上 --base-url
參數
D:\soft\web_base>pytest
============== test session starts ================
platform win32 -- Python 3.6.0, pytest-4.5.0, py-1.5.4, pluggy-0.13.1
baseurl: http://www.example.com
rootdir: D:\soft\web_base, inifile: pytest.ini
plugins: allure-pytest-2.8.6, base-url-1.4.2
collected 1 item
test_demo.py . [100%]
============ 1 passed in 1.72 seconds ==========