2015-05-03 91 views
0

以下pytest-test使用httpretty來模擬請求。它提取的數據寫入文件:將httpretty與pytest結合tmpdir

import requests 
import httpretty 
import json 
from os import listdir 
from os.path import join 

@httpretty.activate 
def test_write_file_from_datasource(): 
    tmpdir = './mytestdir' 

    # mock the connection 
    concert_url = 'http://apis.is/concerts' 
    httpretty.register_uri(httpretty.GET, concert_url, 
          body = json.dumps({'results': []}), 
          content_type='application/json') 
    # fetch data 
    concerts = requests.get(concert_url).json() 

    # write data 
    with open(join(tmpdir, 'concerts.json'), 'w') as json_data: 
     json.dump(concerts, json_data, indent=2) 

    assert len(listdir(tmpdir)) == 1 

我想什麼現在要做的,是利用了pytest tmpdir功能。爲了達到這一點,我寫了這樣的測試(進口同上):

@httpretty.activate 
def test_write_file_from_datasource_failing(tmpdir): 
    tmpdir = str(tmpdir) 
    # mock the connection 
    concert_url = 'http://apis.is/concerts' 
    httpretty.register_uri(httpretty.GET, concert_url, 
          body = json.dumps({'results': []}), 
          content_type='application/json') 
    # fetch data 
    concerts = requests.get(concert_url).json() 

    # write data 
    with open(join(tmpdir, 'concerts.json'), 'w') as json_data: 
     json.dump(concerts, json_data, indent=2) 

    assert len(listdir(tmpdir)) == 1 

它失敗了,因爲httpretty裝飾似乎也與附加參數問題:

TypeError: test_write_file_from_datasource_failing() takes exactly 1 argument (0 given) 

任何想法,如何解決這個問題?

回答

1

看來這個裝飾器不能很好地與pytest的funcargs配合使用。

我看到的唯一解決方案是手動調用httprertty.enable()httpretty.disable()方法。

或者創建一個夾具:

@pytest.yield_fixture 
def http_pretty_mock(): 
    httpretty.enable() 
    yield 
    httpretty.disable() 


def test_write_file_from_datasource_failing(http_pretty_mock, tmpdir): 
    tmpdir = str(tmpdir) 
    # mock the connection