1

私は Learn Python the Hard Way 2nd Ed に取り組んできましたが、素晴らしいものでした。私の質問は、演習 49 (http://learnpythonthehardway.org/book/ex49.html) に関するものです。これは、本に記載されているコードをカバーするノーズ ユニット テストの作成に関するものです。この機能をカバーするテストを作成しようとしています:

def parse_subject(word_list, subj):
    verb = parse_verb(word_list)
    obj = parse_object(word_list)
    return Sentence(subj, verb, obj)

このテストを実行しようとしました:

from nose.tools import *
from ex48 import engine
def test_parse_subject():
  word_list = [('verb', 'verb'),
               ('direction', 'direction')]
  test_subj = ('noun', 'noun')
  test_verb = ('verb', 'verb')
  test_obj = ('direction', 'direction')
  assert_equal(engine.parse_subject(word_list, ('noun', 'noun')), 
               engine.Sentence(test_subj, test_verb, test_obj))

しかし、2 つの Sentence オブジェクトがまったく同じオブジェクトではないため、エラーが返されます

⚡ nosetests                
.....F..........
======================================================================
FAIL: tests.engine_tests.test_parse_subject
----------------------------------------------------------------------
Traceback (most recent call last):
 File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/nose/case.py", line 187, in runTest
    self.test(*self.arg)
 File "/Users/gregburek/code/LPTHW/projects/ex48/tests/engine_tests.py", line 59, in test_parse_subject
    engine.Sentence(test_subj, test_verb, test_obj))
AssertionError: <ex48.engine.Sentence object at 0x101471390> != <ex48.engine.Sentence object at 0x1014713d0>

----------------------------------------------------------------------
Ran 16 tests in 0.018s

FAILED (failures=1)

2 つのオブジェクトが同じであることを確認するには、nose をどのように使用すればよいですか?

4

5 に答える 5

2

私は今、まったく同じ演習#49に取り組んでいる初心者のようなもので、同じエラーに遭遇し、あなたと同じ質問があります. 誰も答えなかったので、文オブジェクトを 3 つの部分に分解し、それらが同等であることを確認するという、私が行ったことを入れたほうがよいと思いました。次のようになります。

def test_parse_subject():
word_list = [('verb','run'),
             ('noun','Bear'),
             ('verb','jump')]
subj = ('noun', 'me')
result = ex49.parse_subject(word_list,subj)
assert_equal(result.subject, 'me')
assert_equal(result.verb, 'run')
assert_equal(result.object, 'Bear')

ただし、nose.tools にオブジェクトの同等性を直接比較できる機能があるかどうかを知りたいです。

于 2011-11-22T02:32:37.060 に答える
0

github ユーザー (bitsai) によるこのチート シートでは、別の手法を使用しており、試してみることもできます。クラス属性をタプルに変換するメソッドを Sentence クラスに追加します。試すだけの価値があります。それを使用していて、さらに理にかなっています。

ここをクリックしてください

于 2014-03-07T10:31:05.317 に答える
0

あなたも試すことができます:

class Sentence(object):
    def __init__(self, subject, verb, obj):
        self.subject = subject[1]
        self.verb = verb[1]
        self.object = obj[1]

    def __eq__(self, other):
        if type(other) is type(self):
            return self.__dict__ == other.__dict__
        else:
            return False
于 2014-08-15T06:14:22.220 に答える