python单元测试方法 [英] python unittest howto

查看:47
本文介绍了python单元测试方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I`d like to know how I could unit-test the following 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

推荐答案

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

Unit test propositioners will tell you that unit tests should be self contained, that is, they should not access the network or the filesystem (especially not in writing mode). Network and filesystem tests are beyond the scope of unit tests (though you might subject them to integration tests).

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

Speaking generally, for such a case, I'd extract the urllib and file-writing codes to separate functions (which would not be unit-tested), and inject mock-functions during unit testing.

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

I.e. (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

并且,在测试文件上:

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

然后我第二个丹尼尔的建议,你应该阅读一些关于单元测试的更深入的材料.

And then I second Daniel's suggestion, you should read some more in-depth material on unit testing.

这篇关于python单元测试方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆