2016-09-12 7 views
1

私は、pytest yield-fixtureをデフォルトのスコープで1回のテストで複数回使用しようとしています。Python。 Pytest fixture collision

@pytest.fixture 
def create_temp_file(): 
    nonlocal_maker_data = {'path': None} # nonlocal for python2 

    def maker(path, data): 
     nonlocal_maker_data['path'] = path 
     with open(path, 'wb') as out: 
      out.write(data) 
    try: 
     yield maker 
    finally: 
     path = nonlocal_maker_data['path'] 
     if os.path.exists(path): 
      os.remove(path) 


def test_two_call_of_fixture(create_temp_file): 
    create_temp_file('temp_file_1', data='data1') 
    create_temp_file('temp_file_2', data='data2') 

    with open('temp_file_1') as f: 
     assert f.read() == 'data1' 

    with open('temp_file_2') as f: 
     assert f.read() == 'data2' 

    assert False 
    # temp_file_2 removed 
    # temp_file_1 doesn't removed 

私は衝突しています。最初のフィクスチャはクリーンではありません - temp_file_1は削除されませんが、2番目のファイルはうまく削除されません。 治具を何回も使用できますか?

PS:私は約tmpdirを知っています - スタンダードpytest fixture。これは単なる例です。

+0

もちろん、この例では、作成されたすべてのファイルを非ローカルリストに蓄積して削除することができます。しかし、私は最も一般的な方法を理解したい。 –

答えて

0

この例では、フィクスチャーが機能します。

@pytest.fixture 
def create_temp_file(): 
    nonlocal_maker_data = set() # nonlocal for python2 

    def maker(path, data): 
     with open(path, 'wb') as out: 
      out.write(data) 
     nonlocal_maker_data.add(path) 
    try: 
     yield maker 
    finally: 
     for path in nonlocal_maker_data: 
      if os.path.exists(path): 
       os.remove(path)