views:

34

answers:

2

Proxy configuration of a machine can be easily fetched using

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

I need to write a test for the above written function. In order to do that I need to:-

  1. Set the system-wide proxy to an invalid URL during the test(sounds like a bad idea).
  2. Supply an invalid URL to http_proxy.

How can I achieve either of the above?

A: 

The exact behaviour of getproxies varies according the the system you're on, but I believe that in all cases it looks first in the environment then checks the system specific place for proxy settings (such as the registry on windows).

So try:

os.environ['HTTP_PROXY'] = 'whatever invalid URL you want'
Duncan
+2  A: 

Looking at the question tags I see you want to write unit-tests for the function. And where is your unit here? Where is your business logic? getproxies and get are functions of the standard Python library. You shouldn't test others' code in your unit-tests. Furthermore it enough to test only Things That Could Possibly Break.

If I've misunderstood your question and indeed your function looks like this:

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

and you don't know how to test the “complex” code due to dependency on proxy, I recommend to split the function in two:

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

Now you're able to test _check_proxy alone, using any mock/stub you specially prepared for the role of http_proxy. Write few tests for _check_proxy and leave original check_proxy untested (in sense of unit-tests). It is OK.

nailxx