【发布时间】:2014-05-19 16:48:43
【问题描述】:
我试图了解什么应该测试,什么不应该测试。即使在阅读了关于 S.O. 的其他问题/答案后,我仍然没有真正理解它。我工作的一位高级开发人员说我的所有代码都应该经过测试,但测试其中的一部分似乎很愚蠢——即当这些部分只使用已经测试过的代码时。
下面的例子有一个http请求函数和一个获取用户名函数。 获取用户名函数所做的只是调用http请求函数。因为我使用的是Testbed,所以没有发出HTTP请求,所以我们没有测试返回数据的正确性。那我还应该测试获取用户名功能吗?
正在测试的文件中的代码
def fetch_url(url, method=urlfetch.GET, data=''):
"""Send a HTTP request"""
result = urlfetch.fetch(url=url, method=method, payload=data,
headers={'Access-Control-Allow-Origin': '*'})
return result.content
def get_user_name():
"""Get the name of the current user"""
url = '{}/user?access_token={}'.format(GITHUB_API_URL, get_access_token())
result = json.loads(fetch_url(url))
return result['login']
这是测试:
class TestUrlFetch(unittest.TestCase):
"""Test if fetch_url sending legitimate requests"""
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
def test_fetch_url(self):
from console.auth import fetch_url
# Grab content via a URL fetch
content = fetch_url('https://google.com')
# Test that content is not empty
self.assertIsNotNone(content)
def tearDown(self):
self.testbed.deactivate()
所以如上所述,我是否应该编写另一个测试来测试get_user_name 函数?
【问题讨论】:
-
您可能会得到更好的答案:programmers.stackexchange.com
-
get_user_name() 似乎以特定方式格式化字符串并解析一些json。也许您可能会跳过测试 fetch_url() 而只测试 get_user_name().. 但是您将如何测试看起来不像
'{}/user?access_token={}'.format(GITHUB_API_URL, get_access_token())的 URL?一般规则是,测试任何可能被当前不存在的代码重用的东西。即:一切。
标签: python unit-testing nose python-unittest