2017-08-28 36 views
0

我有一個需要在我的測試套件中使用燈具的功能。這只是一個幫助生成完整URL的小幫助函數。在PyTest中將夾具傳遞給輔助函數?

def gen_url(endpoint): 
    return "{}/{}".format(api_url, endpoint) 

我在conftest.py夾具返回的網址:

@pytest.fixture(params=["http://www.example.com"]) 
def api_url(request): 
    return request.param 

@pytest.fixture(params=["MySecretKey"]) 
def api_key(request): 
    return request.param 

最後,在我的測試功能,我需要調用我的gen_url

def test_call_action_url(key_key): 
    url = gen_url("player") 
    # url should equal: 'http://www.example.com/player' 
    # Do rest of test here... 

當我這樣做但是,它會拋出一個錯誤,說明調用gen_urlapi_url未定義。如果我添加api_url作爲第二個參數,我需要將它作爲第二個參數傳遞。這不是我想要做的。

我可以將api_url作爲第二個參數添加到gen_url而不需要從測試中傳遞它嗎?爲什麼我不能像api_key那樣在我的test_*函數中使用它?

+3

爲什麼你不想把'api_url'傳遞給'gen_url'? –

回答

0

與您的代碼多重問題,夾具是不可見在您的測試代碼,直到除非你使用它作爲你的測試參數,你是不是通過這兩個固定裝置(api_urlapi_key)到您的測試功能,並隨後到您的幫手功能。 下面是修改後的代碼(未經測試)

def gen_url(api_url, endpoint): 
    return "{}/{}".format(api_url, endpoint) 

def test_call_action_url(api_url, api_key): 
    url = gen_url(api_url, "player") 
    # url should equal: 'http://www.example.com/player' 
    # Do rest of test here with api_key here... 
1

如果您gen_url夾具,它可以請求api_url沒有明確地傳遞:

@pytest.fixture 
def gen_url(api_url): 
    def gen_url(endpoint): 
     return '{}/{}'.format(api_url, endpoint) 
    return gen_url 


def test_call_action_url(api_key, gen_url): 
    url = gen_url('player') 
    # ... 

此外,如果api_key只用來發出請求, TestClient類 可以封裝它,所以測試方法只需要客戶端:

try: 
    from urllib.parse import urljoin # Python 3 
except ImportError: 
    from urlparse import urljoin # Python 2 

import requests 

@pytest.fixture 
def client(api_url, api_key): 
    class TestClient(requests.Session): 
     def request(self, method, url, *args, **kwargs): 
      url = urljoin(api_url, api_key) 
      return super(TestClient, self).request(method, url, *args, **kwargs) 

    # Presuming API key is passed as Authorization header 
    return TestClient(headers={'Authorization': api_key}) 


def test_call_action_url(client): 
    response = client.get('player') # requests <api_url>/player 
    # ...