Python中pytest命令行實(shí)現(xiàn)環(huán)境切換
前言
在自動(dòng)化測(cè)試過程中經(jīng)常需要在不同的環(huán)境下進(jìn)行測(cè)試驗(yàn)證,所以寫自動(dòng)化測(cè)試代碼時(shí)需要考慮不同環(huán)境切換的情況。pytest鉤子函數(shù)pytest_addoption可以很好幫我們解決這個(gè)痛點(diǎn)。
pytest_addoption(parser, pluginmanager)
注冊(cè)argparse樣式選項(xiàng)和ini樣式配置值,在測(cè)試運(yùn)行開始時(shí)調(diào)用一次。
注意:
由于pytest在啟動(dòng)過程中如何發(fā)現(xiàn)插件,因此該函數(shù)只能在位于測(cè)試根目錄的插件或conftest.py文件中實(shí)現(xiàn)。
參數(shù)
parser(pytest.parser)–若要添加命令行選項(xiàng),請(qǐng)調(diào)用parser.addoption(…)。若要添加ini文件值,請(qǐng)調(diào)用解析器.addini(…)。
pluginmanager(pytest.PytestPluginManager)–pytest插件管理器,可用于安裝hookspec()或hookpimpl(),并允許一個(gè)插件調(diào)用另一個(gè)插件的鉤子來更改命令行選項(xiàng)的添加方式。
以后可以分別通過配置對(duì)象訪問選項(xiàng):
config.getoption(name)來檢索命令行選項(xiàng)的值。
config.getini(name)來檢索從ini樣式文件中讀取的值。
config對(duì)象通過.config屬性在許多內(nèi)部對(duì)象上傳遞,或者可以作為pytestconfig fixture檢索。
在conftest.py文件中定義命令行參數(shù)
def pytest_addoption(parser):
"""
添加命令行參數(shù)
parser.addoption為固定寫法
default 設(shè)置一個(gè)默認(rèn)值,此處設(shè)置默認(rèn)值為sit
choices 參數(shù)范圍,傳入其他值無效
help 幫助信息
"""
parser.addoption(
"--env", default="sit", choices=["dev", "sit", "uat"], help="環(huán)境參數(shù)"
)我們定義了不同環(huán)境下的命令參數(shù):dev、sit、uat,我們?cè)趺传@取運(yùn)行的命令行參數(shù)呢?
獲取命令行參數(shù)
@pytest.fixture(scope="session")
def get_env(request):
return request.config.getoption("--env")設(shè)置不同環(huán)境的全局變量
在不同的測(cè)試環(huán)境下,URL、用戶信息等數(shù)據(jù)都是不一樣的,建議在conftest中給全局變量賦值可以減少代碼冗余。
先定義一個(gè)數(shù)據(jù)文件,data_util.py分別獲取用戶信息和URL信息
def get_env():
env = {
'sit': 'www.baidu.com',
'uat': 'www.hao123.com'
}
return env
def get_user():
users = {
'sit': ['user1', 'pwd1'],
'uat': ['user2', 'pwd2']
}
return users然后在conftest中根據(jù)環(huán)境設(shè)置全局變量值
# 設(shè)置不同環(huán)境下的全局變量
@pytest.fixture(scope="session")
def set_env(get_env):
if get_env == 'sit':
env_url = data_util.get_env()['sit']
user = data_util.get_user()['sit']
if get_env == 'uat':
env_url = data_util.get_env()['uat']
user = data_util.get_user()['uat']
return {'env_url': env_url, 'user': user}注意fixture的使用范圍為整個(gè)測(cè)試會(huì)話。
以下是完整的conftest
import pytest
import data_util
def pytest_addoption(parser):
"""
添加命令行參數(shù)
parser.addoption為固定寫法
default 設(shè)置一個(gè)默認(rèn)值,此處設(shè)置默認(rèn)值為sit
choices 參數(shù)范圍,傳入其他值無效
help 幫助信息
"""
parser.addoption(
"--env", default="sit", choices=["dev", "sit", "uat"], help="環(huán)境參數(shù)"
)
@pytest.fixture(scope="session")
def get_env(request):
return request.config.getoption("--env")
# 設(shè)置不同環(huán)境下的全局變量
@pytest.fixture(scope="session")
def set_env(get_env):
if get_env == 'sit':
env_url = data_util.get_env()['sit']
user = data_util.get_user()['sit']
if get_env == 'uat':
env_url = data_util.get_env()['uat']
user = data_util.get_user()['uat']
return {'env_url': env_url, 'user': user}定義測(cè)試類及測(cè)試方法
注意fixture不能在x-unit風(fēng)格下的setup\teardown中引用,因此需要使用fixture定義setup、teardown方法才能引用到conftest里的fixture,一般我們?cè)趕etup方法中初始化環(huán)境變量具體如下:
@pytest.fixture()
def class_fixture(set_env):
print('setup_class')
url = set_env.get('env_url')
user = set_env.get('user')
print(url, user)
yield
print('teardown class')這樣我們就在測(cè)試前把環(huán)境信息設(shè)置OK了。
測(cè)試驗(yàn)證
以下是測(cè)試方法
import pytest
pytestmark = pytest.mark.usefixtures("module_fixture")
@pytest.fixture(scope="module", params=["test_fixture"])
def module_fixture(request):
param = request.param
print(" SETUP module", param)
yield param
print(" TEARDOWN module", param)
@pytest.fixture()
def class_fixture(set_env):
print('setup_class')
url = set_env.get('env_url')
user = set_env.get('user')
print(url, user)
yield
print('teardown class')
@pytest.fixture(scope="function", params=[1, 2])
def function_fixture(request):
param = request.param
print(" SETUP function", param)
yield param
print(" TEARDOWN function", param)
@pytest.mark.usefixtures('class_fixture')
class TestFixture:
def test_0(self, function_fixture):
print(" RUN test0 with function_fixture", function_fixture)
def test_1(self, module_fixture):
print(" RUN test1 with module_fixture", module_fixture)
def test_2(self, function_fixture, module_fixture):
print(f" RUN test2 with function_fixture {function_fixture} and module_fixture {module_fixture}")
def test_env(self, get_env):
print(f"The current environment is: get_env")
if __name__ == '__main__':
pytest.main(['-v', '-s','--env=uat', 'test_fixture.py::TestFixture::test_0'])我們首先填的uat命令運(yùn)行,查看輸出:

可以看出輸出是正確的,我們?cè)偾袚Q成sit試試:
if __name__ == '__main__':
pytest.main(['-v', '-s','--env=uat', 'test_fixture.py::TestFixture::test_0'])
可以看出在不同的命令下獲得的測(cè)試數(shù)據(jù)也不一樣,這樣我們就達(dá)到了環(huán)境切換的目的了~
到此這篇關(guān)于Python中pytest命令行實(shí)現(xiàn)環(huán)境切換的文章就介紹到這了,更多相關(guān)pytest 環(huán)境切換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
django 數(shù)據(jù)庫返回queryset實(shí)現(xiàn)封裝為字典
這篇文章主要介紹了django 數(shù)據(jù)庫返回queryset實(shí)現(xiàn)封裝為字典,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
python實(shí)現(xiàn)炫酷屏幕保護(hù)的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用python實(shí)現(xiàn)炫酷屏幕保護(hù)效果,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以跟隨小編一起了解一下2023-12-12
利用Python腳本實(shí)現(xiàn)ping百度和google的方法
最近在做SEO的時(shí)候,為了讓發(fā)的外鏈能夠快速的收錄,想到了利用ping的功能,google和百度都有相關(guān)的ping介紹,有興趣的朋友可以去看看相關(guān)的知識(shí)。下面這篇文章主要介紹了利用Python腳本實(shí)現(xiàn)ping百度和google的方法,需要的朋友可以參考借鑒,一起來看看吧。2017-01-01
使用Python自動(dòng)化生成PPT并結(jié)合LLM生成內(nèi)容的代碼解析
PowerPoint是常用的文檔工具,但手動(dòng)設(shè)計(jì)和排版耗時(shí)耗力,本文將展示如何通過 Python 自動(dòng)化提取 PPT 樣式并生成新 PPT,同時(shí)結(jié)合大語言模型(LLM)生成內(nèi)容(如自我介紹文本),實(shí)現(xiàn)高效、個(gè)性化的 PPT 制作,需要的朋友可以參考下2025-05-05
解決python3報(bào)錯(cuò)之takes?1?positional?argument?but?2?were?gi
這篇文章主要介紹了解決python3報(bào)錯(cuò)之takes?1?positional?argument?but?2?were?given問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
opencv調(diào)整圖像亮度對(duì)比度的示例代碼
本文通過實(shí)例代碼給大家介紹了opencv調(diào)整圖像亮度對(duì)比度,代碼簡單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
一文詳解Python中數(shù)據(jù)清洗與處理的常用方法
在數(shù)據(jù)處理與分析過程中,缺失值、重復(fù)值、異常值等問題是常見的挑戰(zhàn),本文總結(jié)了多種數(shù)據(jù)清洗與處理方法,文中的示例代碼簡潔易懂,有需要的小伙伴可以參考下2025-01-01
Python在for循環(huán)里處理大數(shù)據(jù)的推薦方法實(shí)例
這篇文章主要介紹了Python在for循環(huán)里處理大數(shù)據(jù)的推薦方法實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01

