2015-01-12 70 views
2

有沒有一種很好的方法來做到這一點。py.test針對不同結果的多個測試

@pytest.fixture(params=[ 
    "web01-east.domain.com", 
    "web01-master-east.domain.com", 
    "web01.domain.com", 
]) 
def patch_socket(request, monkeypatch): 
    def gethostname(): 
     return request.param 

    monkeypatch.setattr(socket, 'gethostname', gethostname) 


def test__get_pod(patch_socket): 
    assert __get_pod() == 'east' 

眼下這會工作,但我想有最後一次測試失敗,但沒事,因爲如果在__get_pod()函數返回未知的主機名不-east。

有沒有辦法告訴py.test,我想在一個什麼樣的PARAM列表,通過考試應該等於像

[ 
('web01-east.domain.com', 'web') 
('redis01-master-east.domain.com', 'redis-master') 
('web01.domain.com', 'Unknown') 
] 

回答

3

取而代之的猴子修補socket.gethostname,使__get_pod接受的參數。它將使代碼的可測試性:

下面是與pytest.mark.parametrize一個例子:

import re 

import pytest 


def __get_pod(hostname): # dummy impl. 
    hostname = hostname.split('.', 1)[0] 
    if '-' not in hostname: 
     return 'Unknown' 
    hostname = re.sub(r'\d+', '', hostname) 
    return hostname.rsplit('-', 1)[0] 


@pytest.mark.parametrize(['hostname', 'expected'], [ 
    ["web01-east.domain.com", 'web'], 
    ["redis01-master-east.domain.com", 'redis-master'], 
    ["web01.domain.com", 'Unknown'], 
]) 
def test__get_pod(hostname, expected): 
    assert __get_pod(hostname) == expected 

如果你想與mockey-補丁做(或者,你不能改變__get_pod簽名)

import re 
import socket 

import pytest 


def __get_pod(): 
    hostname = socket.gethostname() 
    hostname = hostname.split('.', 1)[0] 
    if '-' not in hostname: 
     return 'Unknown' 
    hostname = re.sub(r'\d+', '', hostname) 
    return hostname.rsplit('-', 1)[0] 


@pytest.mark.parametrize(['hostname', 'expected'], [ 
    ["web01-east.domain.com", 'web'], 
    ["redis01-master-east.domain.com", 'redis-master'], 
    ["web01.domain.com", 'Unknown'], 
]) 
def test__get_pod(monkeypatch, hostname, expected): 
    monkeypatch.setattr(socket, 'gethostname', lambda: hostname) 
    assert __get_pod() == expected 
1

替代falsetru的答案,更像是你開始喜歡的是使用燈具的返回值。鑑於__get_pod看起來類似(從falsetru的假人修改):

def __get_pod(): 
    hostname = socket.gethostname().split('.', 1)[0] 
    if '-' not in hostname: 
     return 'Unknown' 
    hostname = re.sub(r'\d+', '', hostname) 
    return hostname.rsplit('-', 1)[0] 

您可以測試它想:

@pytest.fixture(params=[ 
    ('web01-east.domain.com', 'web'), 
    ('redis01-master-east.domain.com', 'redis-master'), 
    ('web01.domain.com', 'Unknown') 
]) 
def patch_socket(request, monkeypatch): 
    def gethostname(): 
     return request.param[0] 

    monkeypatch.setattr(socket, 'gethostname', gethostname) 
    return request.param[1] 

def test__get_pod(patch_socket): 
    assert __get_pod() == patch_socket 

這需要從您的原始代碼的變化較小。

相關問題