<p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>

<p>What is the best way to control what urllib.urlopen returns?</p>

Probably the best way to handle this is to split up the code, so that logic that processes the page contents is split from the code that fetches the page.
Then pass an instance of the fetcher code into the processing logic, then you can easily replace it with a mock fetcher for the unit test.
e.g.
```
```
class Processor(oject):
    def __init__(self, fetcher):
        self.m_fetcher = fetcher

    def doProcessing(self):
        ## use self.m_fetcher to get page contents

class RealFetcher(object):
    def fetchPage(self, url):
        ## get real contents

class FakeFetcher(object):
    def fetchPage(self, url):
        ## Return whatever fake contents are required for this test
```
```