unittest中的奇怪对象实例行为

时间:2012-05-30 22:14:17

标签: python unit-testing

我正在尝试使用Python unittest测试一个类,但测试套件似乎在修改基类

这里有一些用于演示问题的伪代码:

班级

// module cards...
class deck():

    def __init__(self, cards):
        self.__cards = cards

    def __len__(self):
        return len(self.__cards)

    def draw(self, n = 1):
        '''
        remove and return n cards
        from internal card list

        n -- integer
        @return list removed
        '''
        removed      = self.__cards[0:n]
        remaining    = self.__cards[n:]
        self.__cards = remaining
        return removed

    def addOne(self, card):
        '''
        add single card to the deck
        '''
        self.__cards.append(card)

    def addMany(self, cards):
        '''
        add many cards to the deck
        '''
        self.__cards.extend(cards)

填充实例的fixture,可能是文件或数据库查询的输出

//source
src = [
{
    'id'          : 1,
    'name'        : 'one',
    'description' : 'this is one'
},
{
    'id'          : 2,
    'name'        : 'two',
    'description' : 'this is two'
},
{
    'id'          : 3,
    'name'        : 'three',
    'description' : 'this is three'
},
{
    'id'          : 4,
    'name'        : 'four',
    'description' : 'this is four'
},
{
    'id'          : 5,
    'name'        : 'five',
    'description' : 'this is five'
}
]

测试

from source import src
import cards 

def test_drawRemovesOne(self):
    deck = cards.deck(src)
    self.assertTrue(callable(deck.draw))

    # single card
    deckSize  = len(deck)
    drawnCard = deck.draw(1)
    self.assertEqual(drawnCard[0]['id'], 1)
    self.assertEqual(4, len(deck))
    self.assertEqual(len(drawnCard), 1)



def test_drawRemovesMany(self):
    deck = cards.deck(src)
    deckSize   = len(deck)
    drawnCards = deck.draw(3)
    self.assertEqual(drawnCards[0]['id'], 1)
    self.assertEqual(drawnCards[1]['id'], 2)
    self.assertEqual(drawnCards[2]['id'], 3)
    self.assertEqual(len(deck), 2)
    self.assertEqual(len(drawnCards), 3)


'''
INVALIDATES PREVIOUS TESTS...
def test_addOne(self):
    deck = cards.deck(src)
    card = {
        'id'          : 9,
        'name'        : 'nine',
        'description' : 'this is nine'
    }
    deckSize = len(deck)
    deck.addOne(card)
    newDeckSize = len(deck)
    self.assertTrue(newDeckSize == deckSize + 1)
'''

编辑:发布真实片段

第一次测试通过,但随后在第二次测试实施时失败。看起来似乎有一个对测试方法共享的类的引用,尽管看起来是新的实例。

我在Python中只做了一点名工作,这是我不知道的一些语言特性的结果吗?

1 个答案:

答案 0 :(得分:1)

请参阅此代码

>>> class Deck:
...     def __init__(self, cards):
...         self.cards = cards
>>> l0 = [1, 2, 3]
>>> d1 = Deck(l0)
>>> d2 = Deck(l0)
>>> d1.cards
0: [1, 2, 3]
>>> d2.cards
1: [1, 2, 3]
>>> d1.cards.append(4)
>>> d2.cards
2: [1, 2, 3, 4]    # d1 and d2 share the same list for cards

您可以使用deck = cards.deck(src)启动所有测试,但我不知道src的来源。如果它没有在setUp方法中创建为新对象,那么它可以在测试用例之间共享。