Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python单元测试方法_Python_Unit Testing - Fatal编程技术网

python单元测试方法

python单元测试方法,python,unit-testing,Python,Unit Testing,我想知道如何对以下模块进行单元测试 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_con

我想知道如何对以下模块进行单元测试

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

模糊的问题。如果您只是在寻找一个使用Python斜面进行单元测试的入门,我推荐MarkPilgrim的《深入Python》一书。否则,您需要弄清楚您在测试代码时遇到的具体问题。

单元测试提议者会告诉您,单元测试应该是自包含的,也就是说,它们不应该访问网络或文件系统(特别是在编写模式下)。网络和文件系统测试超出了单元测试的范围(尽管您可能会对它们进行集成测试)

一般来说,对于这种情况,我会将urllib和文件编写代码提取到单独的函数中(不会进行单元测试),并在单元测试期间注入模拟函数

即(略为缩写以便于阅读):

并且,在测试文件上:

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...

然后我同意Daniel的建议,您应该阅读一些关于单元测试的更深入的材料。

要模拟urllopen,您可以预先获取一些示例,然后在单元测试中使用。下面是一个让您开始学习的示例:

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
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