10

私は Learn Python the Hard Way をフォローしており、Exercise 47 - Automated Testing ( http://learnpythonthehardway.org/book/ex47.html )を行っています。

私は Python3 を使用しており (本では Python 2.x を使用しているのに対して)、assert_equals (本で使用されている) は非推奨であることに気付きました。assertEqual を使用しています。

テスト ケースを作成しようとしていますが、何らかの理由で cmd で NOSETEST を使用すると、次のエラーが発生します。NameError: global name 'assertEqual' is not defined

コードは次のとおりです。

from nose.tools import *
from ex47.game import Room



def test_room():
    gold = Room("GoldRoom",
        """ This room has gold in it you can grab. There's a
            door to the north. """)
    assertEqual(gold.name, "GoldRoom")
    assertEqual(gold.paths, {})

def test_room_paths():
    center = Room("Center", "Test room in the center.")
    north = Room("North", "Test room in the north.")
    south = Room("South", "Test room in the south.")

    center.add_paths({'north': north, 'south': south})
    assertEqual(center.go('north'), north)
    assertEqual(center.go('south'), south)

def test_map():
    start = Room("Start", "You can go west and down a hole")
    west = Room("Trees", "There are trees here. You can go east.")
    down = Room("Dungeon", "It's dark down here. You can go up.")

    start.add_paths({'west': west, 'down': down})
    west.add_paths({'east': start})
    down.add_paths({'up': start})

    assertEqual(start.go('west'), west)
    assertEqual(start.go('west').go('east'), start)
    assertEqual(start.go('down').go('up'), start)

GitHub で解決策を検索しようとしましたが、NameError が表示される理由と、それを修正する方法がわかりません。

4

4 に答える 4

5

assertEqual はunittest.TestCaseクラスのメソッドであるため、そのクラスを継承するオブジェクトでのみ使用できます。unittest のドキュメントを確認してください。

于 2013-07-22T15:09:32.377 に答える
1

なぜあるのですNameErrorか?

nose.tools方法がないからですassertEqual()。と混合nose.toolsしている可能性がありますunittest

あなたの場合、それを回避する方法は?

誰かが(コメントで) nose言ったようにassert_equal

from nose.tools import *
from ex47.game import Room

def test_room():
    gold = Room("GoldRoom",
        """ This room has gold in it you can grab. There's a
            door to the north. """)
    assert_equal(gold.name, "GoldRoom")
    assert_equal(gold.paths, {})

しかし、公式には非推奨です。それを使用すると、次のことが発生しDeprecationWarningます。

...
Asserts something ...
.../test.py:123:    
DeprecationWarning: Please use assertEqual instead.
  assert_equals(a, b)
ok
...

したがって、assertEqualfromを使用する必要がありunittestます。

import unittest
from ex47.game import Room

class TestGame(unittest.TestCase):
    def test_room(self):
        gold = Room("GoldRoom",
            """ This room has gold in it you can grab. There's a
                door to the north. """)
        self.assertEqual(gold.name, "GoldRoom")
        self.assertEqual(gold.paths, {})

ここでドキュメントを読む

于 2020-09-05T07:39:34.247 に答える