gpt4 book ai didi

python单元测试指南

转载 作者:太空宇宙 更新时间:2023-11-03 12:42:51 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com