2014-12-05 37 views
1

凍結我有如下使用nose_parameterized一個Python代碼:多線程的urllib2鼻子框架

from nose_parameterized import parameterized 
from multiprocessing.pool import ThreadPool 
import urllib2 

def make_http_call(url, req_type): 
    opener = urllib2.build_opener() # <=== this line causes it to freeze 
    return 1 

pool = ThreadPool(processes=4) 
results = [] 
urls = ['a', 'b', 'c', 'd'] 
for url in urls: 
    results.append(pool.apply_async(make_http_call, (url, 'html'))) 
d = {'add': []} 
for ind, res in enumerate(results): 
    d['add'].append((res.get(), 2+ind, 3+ind)) 

@parameterized(d['add']) 
def test_add(a, b, c): 
    assert a+b == c 

這是代碼的虛擬版本。基本上,我需要使用http請求響應加載測試參數,並且由於有很多網址,我想多線程化它們。 只要我添加urllib2.build_opener,它使用鼻子凍結(但仍然可以與python很好地工作) 另外,我試過urllib2.urlopen;一樣的問題。 是否有'正確'(可調試)解決方法的任何想法?

+0

也許這會[幫助](http://stackoverflow.com/questions/2137187/python-process-blocked-by-urllib2) – 2014-12-05 20:48:32

+0

謝謝。我知道你關聯的那個問題,但是我不能將任何東西放在__main__中,因爲在參數收集之後執行安裝程序,所以不能在鼻子安裝中進行設置。鑑於限制,我希望有一個解決方法。 – max 2014-12-05 21:14:02

回答

1

你可以用鼻子multiprocess內置插件的是,像這樣:

from nose_parameterized import parameterized 
import urllib2 

urls = ['http://www.google.com', 'http://www.yahoo.com'] 

@parameterized(urls) 
def test_add(url): 
    a = urllib2.urlopen(url).read() 

    b = 2 + urls.index(url) 
    c = 3 + urls.index(url) 
    assert a+str(b) == str(c) 

nosetests --processes=2運行它。這使您能夠按照預期將測試運行分佈在一組並行運行測試的工作進程中。在幕後,使用了多處理模塊。

+0

Thanks.This回答了這個問題。如果我在測試方法中加載數據,我將被迫在那裏做所有的斷言,而不是在單獨的測試方法中。另一個問題是,我也有一些不能並行運行的測試,這意味着我需要單獨的鼻子運行......無論如何,瞭解這個功能都是非常好的。 – max 2014-12-11 01:45:55