你如何得到一个python函数里面的值,它不返回任何单元测试?

时间:2015-09-03 14:29:47

标签: python unit-testing

我正在尝试为现有函数编写单元测试:

class InvFileTransferSpeed(Widget):
  'Widget for showing the transfer speed (useful for file transfers).'

  format = '%6.2f %ss/%s'
  prefixes = ' kMGTPEZY'
  __slots__ = ('unit', 'format')

  def __init__(self, unit='loop'):
    self.unit = unit

  def update(self, pbar):
    'Updates the widget with the current SI prefixed speed.'

    if pbar.seconds_elapsed < 2e-10 or pbar.currval < 2e-10: # =~ 0
      scaled = power = 0
    else:
      speed = pbar.seconds_elapsed / pbar.currval 
      power = int(math.log(speed, 1000))
      scaled = speed / 1000.**power

    return self.format % (scaled, self.prefixes[power], self.unit)

对于我的单元测试,如何使用模拟或其他方法获取传递给存储的最终值?

3 个答案:

答案 0 :(得分:2)

当您将 if($extension == 'xml'): $doc = new \DOMDocument(); $doc->load($filePath); $response->setContent($doc->saveXML()); else: $response->setContent(readfile($filePath)); endif; 传递给函数时,为什么不创建一个传递的空列表。该函数将附加到storage,然后您可以检查该列表中的内容以及是否为预期结果。

答案 1 :(得分:0)

我通常使用mock库(python3.x中的unittest.mock)。它看起来像是:

mock_storage = mock.Mock()
obj._fetch_law(some_task, mock_storage)
mock_storage.extend.assert_called_with(expected_value)

当然,在这个示例中,您可能也想模拟请求... mock.patch非常适合:

with mock.patch.object(requests, 'get') as mock_get:
    mock_get.return_value = ' ... '
    mock_storage = mock.Mock()
    obj._fetch_law(some_task, mock_storage)
    mock_storage.extend.assert_called_with(expected_value)

答案 2 :(得分:0)

劳伦斯是对的,只做一些简单的事情:

def test_fetch_law():
    store = []
    task = ...
    cls = ClassWithFetchLaw()
    cls._fetch_law(task, store)
    assert len(store) > 0

另一方面,如果你要关闭单元测试路由,为什么不让sys.exit抛出异常并为它编写另一个测试?除非你真的想要那里的sys.exit ......

def test_fetch_law_throws():
    store = []
    bad_task = ...
    cls = ClassWithFetchLaw()
    with pytest.raises(Exception):
        cls._fetch_law(bad_task, store)