Python unittest howto

I would like to know how I can test the next module.

def download_distribution(url, tempdir):
    """ Method which downloads the distribution from PyPI """
    print "Attempting to download from %s" % (url,)

    try:
        url_handler = urllib2.urlopen(url)
        distribution_contents = url_handler.read()
        url_handler.close()

        filename = get_file_name(url)

        file_handler = open(os.path.join(tempdir, filename), "w")
        file_handler.write(distribution_contents)
        file_handler.close()
        return True

    except ValueError, IOError:
        return False
+3
source share
3 answers
suggestions

Unit 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):
    # Extracted code
    url_handler = urllib2.urlopen(url)
    content = url_handler.read()
    url_handler.close()
    return content

def write_to_file(content, filename, tmpdir):
    # Extracted code
    file_handler = open(os.path.join(tempdir, filename), "w")
    file_handler.write(content)
    file_handler.close()

def download_distribution(url, tempdir):
    # Original code, after extractions
    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):
    # In this case, do nothing, as we don't do filesystem meddling while unit testing
    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):
    # And so on...

, , .

+5

. Python, Mark Pilgrim "Dive Into Python", Python. , .

+5

urllopen, , unittests. , :

def urlopen(url):
    urlclean = url[:url.find('?')] # ignore GET parameters
    files = {
        'http://example.com/foo.xml': 'foo.xml',
        'http://example.com/bar.xml': 'bar.xml',
    }
    return file(files[urlclean])
yourmodule.urllib.urlopen = urlopen
0

Source: https://habr.com/ru/post/1741503/


All Articles