2015-03-19 69 views
1

我正在使用Pytest來測試可執行文件。這個exe在啓動時讀取一個配置文件。我在每次測試開始時都編寫了一個工具來生成這個exe文件,並在測試結束時關閉它。不過,我無法弄清楚如何告訴夾具使用哪個配置文件。我想要夾具在生成exe之前將指定的配置文件複製到目錄。如何將值傳遞給Pytest夾具

@pytest.fixture 
def session(request): 
    copy_config_file(specific_file) # how do I specify the file to use? 
    link = spawn_exe() 
    def fin(): 
     close_down_exe() 
    return link 

# needs to use config file foo.xml 
def test_1(session): 
    session.talk_to_exe() 

# needs to use config file bar.xml 
def test_2(session): 
    session.talk_to_exe() 

如何告訴夾具使用test_1的「foo.xml」和test_2的「bar.xml」?

感謝 約翰

回答

2

一種解決方案是使用pytest.mark爲:

@pytest.fixture 
def session(request): 
    m = request.node.get_marker('session_config') 
    if m is None: 
     pytest.fail('please use "session_config" marker') 
    specific_file = m.args[0] 
    copy_config_file(specific_file) 
    link = spawn_exe() 
    def fin(): 
     close_down_exe() 
    return link 

@pytest.mark.session_config("foo.xml") 
def test_1(session): 
    session.talk_to_exe() 

@pytest.mark.session_config("bar.xml") 
def test_2(session): 
    session.talk_to_exe() 

另一種方法是隻更改session夾具略微委派鏈接測試功能的創建:

@pytest.fixture 
def session_factory(request): 
    def make_link(specific_file): 
     copy_config_file(specific_file) 
     link = spawn_exe() 
     def fin(): 
      close_down_exe() 
     return link 
    return make_link 

def test_1(session_factory): 
    session = session_factory('foo.xml') 
    session.talk_to_exe() 

def test_2(session): 
    session = session_factory('bar.xml') 
    session.talk_to_exe() 

我更喜歡第二個,因爲它看起來更簡單,以後可以做更多的改進,例如,如果您需要在基於配置值的測試中使用@parametrize