【问题标题】:Python - what should and shouldn't be tested [closed]Python - 应该和不应该测试什么[关闭]
【发布时间】: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


【解决方案1】:

取决于测试方法,但我认为测试每一行代码对于需要维护的代码是一个好主意。这并不意味着每一行都需要自己的测试。您可以使用 coverage.py 之类的工具来查看您的测试覆盖了哪些行。

【讨论】:

    【解决方案2】:

    测试它的一部分似乎很愚蠢——即当这些部分只使用已经测试过的代码时。

    你怎么知道你正确地使用了这些部分?

    单元测试用于快速捕获编程错误 - 错误和接口更改。

    【讨论】:

    • 谢谢。这很有意义。自己很难完全学会这些东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2016-06-30
    • 2015-11-12
    相关资源
    最近更新 更多