python单元测试指南

标签 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_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

最佳答案

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

一般来说,对于这种情况,我会提取 urllib 和文件写入代码以分离函数(不会进行单元测试),并在单元测试期间注入(inject)模拟函数。

即(为了更好的阅读而略微缩写):

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

并且,在测试文件上:

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

然后我同意丹尼尔的建议,你应该阅读一些关于单元测试的更深入的 Material 。

关于python单元测试指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2655697/

相关文章:

Python:使字典列表相对于一个键是唯一的

javascript - 为什么 Jasmine spy 不认为它被调用,即使它返回了 andReturn 值?

python - 跟踪唯一条目的内存有效方法

python - 修改 quart.request - 可以接受吗? (Python API)

android - 如何为单元测试期间流程中调用的静态方法返回不同的值?

ruby-on-rails - Ruby on Rails : how to find the slowest tests?

c# - 使用MVVM Light和PCL创建UWP应用程序

unit-testing - 将测试数据填充到 cassandra 单元的最快方法?

Python3 不可能将 @property 作为装饰器参数传递

python - 如何为所有 ctype 结构类设置 __str__ 方法?