2014-12-05 29 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