0

Let's put up this scenario

# This code lives in lolcat-web/lolapps/lolburger/burger.py
import os
from helper.lib import price

def i_haz_cheezeburger(Burger, user):

    kings_burgers = []
    queens_burgers = []
    address = os.path.join(user.hometown, burger_king_addr)
    burger_menu = Burger.menu()
    for burger in burger_menu:
       if burger == 'King':

            kings_burgers.append({
                    'name': burger, 
                    'price': price(burger)
                   })
       else:
            queens_burgers.append(...)

    return (kings_burgers, queens_burgers)

I want to test whether the function i_haz_cheezeburger will return a tuple, with correct values in it. It depends on a few things (simplification): os, helper.lib.price, Burger, and user (User class)

Since I am fairly new to mock by Michael Foord, here is my newbie attempt:

edit looks wrong because joiner and price doesn't seem to be used anywhere?

def test_01(unittest.TestCase):
   with patch('os.path.join') as joiner:
      with patch('lolcat-web.lolapps.lolburger.burger.price') as price: 
          mock_user = MagicMock(name='user', spec=client.auth.User)
          mock_user.hometown = 'New-York'
          mock_burger = MagicMock(name='burger', spec=lolcat-web.lolapps.lolburger.Burger)
          mock_burger.menu = [ '....sets up a list of samples .....' ]

          # now call the function
          response = i_get_cheezeburger(mock_burger, mock_user)
   # now we do some assertions.....

This is like writing fixtures. What if the method i_haz_cheezeburger has a few more dependencies. Of course I can refactor them out and create a few more wrapper / helper functions. But the problem is, or at least the confusion is: I want to test my output. I don't want to know "oh there is no mispell / unbound assignment because it passed with a per-defined return value" But setting up the fixtures (or return values for things like Burger.menu) doesn't sound right.

What's the proper way of dealing this kind of issue? Please correct my misunderstanding.

4

1 回答 1

3

不要模拟标准库——如果标准库有问题,你就有更大的问题(更不用说你几乎肯定没有对标准库进行集成测试,所以模拟它只是隐藏潜在的失败)。

如果函数的输出取决于 的返回值,那么如果要测试返回值Burger.menu(),则需要为的模拟版本设置返回值。Burger.menu()这是正确的做法。您提供的模拟输入是真实世界输入的受控版本,因此您期望在给定这些受控输入的情况下获得特定的输出。使用mock不会神奇地从方程式中删除所有实际的真实数据。

于 2012-04-10T20:41:34.620 回答