代理检查的单元测试

时间:2010-04-11 12:35:04

标签: python unit-testing proxy

可以使用

轻松获取计算机的代理配置
def check_proxy():    
     import urllib2
     http_proxy = urllib2.getproxies().get('http')

我需要为上面写的函数编写一个测试。为了做到这一点,我需要: -

  1. 将系统范围的代理设置为 测试期间无效的网址(声音 像一个坏主意)。
  2. 提供无效     http_proxy的URL。
  3. 我如何实现上述任何一种?

2 个答案:

答案 0 :(得分:2)

查看问题标签,我看到您要为该功能编写单元测试。那里你的单位在哪里? 您的业务逻辑在哪里? getproxiesget是标准Python库的函数。您不应该在单元测试中测试其他人的代码。此外,它足以仅测试Things That Could Possibly Break

如果我误解了你的问题,你的功能确实如此:

def check_proxy():    
     import urllib
     http_proxy = urllib.getproxies().get('http')
     # some “complex” code that uses http_proxy

并且由于依赖代理,你不知道如何测试“复杂”代码,我建议将函数分成两部分:

def check_proxy():    
     import urllib
     http_proxy = urllib.getproxies().get('http')
     _check_proxy(http_proxy)

def _check_proxy(http_proxy):
     # some “complex” code that uses http_proxy

现在,您可以使用您为_check_proxy角色专门准备的任何模拟/存根来单独测试http_proxy。为_check_proxy编写一些测试,并保留原始check_proxy未经测试(在单元 - 测试意义上)。没关系。

答案 1 :(得分:1)

getproxies的确切行为因您所使用的系统而异,但我相信在所有情况下它首先在环境中查找然后检查系统特定的代理设置位置(例如Windows上的注册表)。 / p>

所以试试:

os.environ['HTTP_PROXY'] = 'whatever invalid URL you want'