2017-06-19 81 views
0

所以,我有兩個代碼主要部分:Pytest - tmpdir_factory在pytest_generate_tests

  1. 生成的配置文件,廣泛收集在一個目錄。
  2. 運行前一個生成的單個配置文件。

我想運行一個測試,首先執行code1並生成所有文件,然後爲每個配置文件運行code2並驗證結果是否正確。 到目前爲止,我的嘗試是:

@pytest.fixture(scope='session') 
def pytest_generate_tests(metafunc, tmpdir_factory): 
    path = os.path.join(tmpdir_factory, "configs") 
    gc.main(path, 
      gc.VARIANTS, gc.MODELS, 
      default_curvature_avg=0.0, 
      curvature_avg_variation=0.9, 
      default_gradient_avg=0.0, 
      gradient_avg_variation=0.9, 
      default_inversion="approximate", 
      vary_inversion=False, 
      vary_projections=True) 
    params = [] 
    for model in os.listdir(path): 
     model_path = os.path.join(path, model) 
     for dataset in os.listdir(model_path): 
      dataset_path = os.path.join(model_path, dataset) 
      for file_name in os.listdir(dataset_path): 
       config_file = os.path.join(dataset_path, file_name) 
       folder = os.path.join(dataset_path, file_name[:-5]) 
       tmpdir_factory.mktemp(folder) 
       params.append(dict(config_file=config_file, output_folder=folder)) 
       metafunc.addcall(funcargs=dict(config_file=config_file, output_folder=folder)) 

def test_compile_and_error(config_file, output_folder): 
    final_error = main(config_file, output_folder) 
    assert final_error < 0.9 

然而,tmpdir_factory夾具沒有爲pytest_generate_tests方法工作。我的問題是如何通過生成所有測試來實現我的目標?

回答

1

首先也是最重要的, pytest_generate_tests是爲了pytest鉤子而不是夾具功能的名稱。擺脫之前的@pytest.fixture,再看its docs。掛鉤應寫入conftest.py文件或插件文件中,並根據pytest_前綴自動收集。

現在你事: 只需使用手動使用的臨時目錄:

import tempfile 
import shutil 

dirpath = tempfile.mkdtemp() 

pytest_generate_tests。保存在全球dirpath在conftest, 使用

# ... do stuff with dirpath 
shutil.rmtree(dirpath) 

來源pytest_sessionfinish刪除:https://stackoverflow.com/a/3223615/3858507

請記住,如果你有一個以上的測試案例,pytest_generate_tests將要求每一個。所以你最好把所有的臨時工都保存在一個清單中,最後刪除所有的臨時工。相反,如果你只需要一個tempdir,而不是想用鉤子pytest_sesssionstart在那裏創建它並稍後使用它。

+0

非常感謝您的信息。 –