suggestionsUnit tests tell you that unit tests should be self-contained, that is, they should not access the network or file system (especially in write mode). Network and file system tests go beyond unit tests (although you can subject them to integration tests).
Generally speaking, for such a case, I would extract the urllib codes and the files to separate the functions (which would not be checked per unit), and introduce the mock functions during unit testing.
those. (slightly abbreviated for better reading):
def get_web_content(url):
url_handler = urllib2.urlopen(url)
content = url_handler.read()
url_handler.close()
return content
def write_to_file(content, filename, tmpdir):
file_handler = open(os.path.join(tempdir, filename), "w")
file_handler.write(content)
file_handler.close()
def download_distribution(url, tempdir):
distribution_contents = get_web_content(url)
filename = get_file_name(url)
write_to_file(distribution_contents, filename, tmpdir)
return True
And in the test file:
import module_I_want_to_test
def mock_web_content(url):
return """Some fake content, useful for testing"""
def mock_write_to_file(content, filename, tmpdir):
pass
module_I_want_to_test.get_web_content = mock_web_content
module_I_want_to_test.write_to_file = mock_write_to_file
class SomeTests(unittest.Testcase):
, , .