2017-10-25 8 views
1

私は資格情報の治具を使用してPythonのテスト(ユーザーIDとパスワードの組)pytestフィクスチャを他のフィクスチャでパラメータ化できますか?

def test_something(credentials) 
    (userid, password) = credentials 
    print("Hello {0}, welcome to my test".format(userid)) 

を持っていると私は資格情報のpytest治具があります。それは素晴らしい

を作品

@pytest.fixture() 
def credentials(): 
    return ("my_userid", "my_password") 

を今私はテストを2回(ステージングとプロダクションのために1回)実行できるように、これを複数の資格(ステージングとプロダクション)で拡張したいと考えています。

私はパラメータ化が答えだと思っていましたが、什器でパラメータ化できないようです。

私はこのような何かをするのが大好きだ:staging_credentialsとproduction_credentialsは、すべての器具です

@pytest.fixture(params=[staging_credentials, production_credentials]) 
def credentials(request): 
    return request.param 

:フィクスチャに

@pytest.fixture() 
def staging_credentials(): 
    return ("staging_userid", "staging_password") 

@pytest.fixture() 
def production_credentials(): 
    return ("prod_userid", "prod_password") 

どうやらパラメータは、他の備品にすることはできません。

これをうまく処理する方法についてのご意見はありますか?私はhttps://docs.pytest.org/en/latest/proposals/parametrize_with_fixtures.htmlを見ましたが、それはあまりにも強引な力のようです。

ありがとうございます! スティーブ

答えて

1

間接パラメトリケーションが答えです。したがって、フィクスチャへのパラメータは他のフィクスチャ(名前/コード)である可能性があります。技術的には

import pytest 

all_credentials = { 
    'staging': ('user1', 'pass1'), 
    'prod': ('user2', 'pass2'), 
} 

@pytest.fixture 
def credentials(request): 
    return all_credentials[request.param] 

@pytest.mark.parametrize('credentials', ['staging', 'prod'], indirect=True) 
def test_me(credentials): 
    pass 

、あなたはそのキーでdictの値を得るが、request.paramに基づいてcredentials結果を生成し、このparamがテストの同じ-nameパラメータに渡された値になりますができないだけ。

(これはそうする唯一の理由であるとして、おそらくセットアップ/ティアダウンのステージで)あなたは、他の器具を使用したい場合:

ここ
import pytest 

@pytest.fixture 
def credentials(request): 
    return request.getfuncargvalue(request.param) 

@pytest.fixture() 
def staging_credentials(): 
    return ("staging_userid", "staging_password") 

@pytest.fixture() 
def production_credentials(): 
    return ("prod_userid", "prod_password") 

@pytest.mark.parametrize('credentials', ['staging_credentials', 'production_credentials'], indirect=True) 
def test_me(credentials): 
    pass 

request.getfuncargvalue(...)がでフィクスチャの値を返します。フィクスチャ名、動的に。

関連する問題