0

我以这个http://pythonhosted.org/Flask-MongoKit/为例

我只是想获取一个 Document 实例来编写单元测试,但它不起作用。这是测试的代码:

import unittest
from tests import app, db, ctx
from word.models import Word

class ModelWordTestCase(unittest.TestCase):

    def setUp(self):
        pass

    def test_model_word(self):
        print db.Word

        word = db.Word()

        self.assertIsNotNone(word)

    def tearDown(self):
        pass

词类

from flask.ext.mongokit import Document
from core import db

@db.register
class Word(Document):
    __collection__ = 'words'
    use_dot_notation = True

    STATUS = {
        "approved" : 1,
        "pending" : 0,
        "rejected" : -1,
    }

    structure = {
        'lang': unicode,
        'local': unicode,
        'pronunciation' : unicode,
        'meaning': unicode,
        }

令人惊讶的是 db.Word 在打印时存在print db.Word语句,但不能像我上面提到的教程中那样调用它来创建新实例。这是测试的输出:

Collection(Database(MongoClient('localhost', 27017), u'words_test'), u'Word')

E
======================================================================
ERROR: test_model_word (tests.model_tests.ModelWordTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests/model_tests.py", line 14, in test_model_word
    word = db.Word()
  File "/usr/local/lib/python2.7/dist-packages/mongokit/collection.py", line 64, in __call__
    self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the 'Word' method on a 'Database' object it is failing because no such method exists.

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

如何解决此问题并获取 Word 文档的实例,以便创建和保存记录。

4

1 回答 1

1

我认为您在测试中使用了错误的数据库实例。您应该使用与注册模型相同的数据库实例。所以,我不知道你的代码是如何构造的,但乍一看,你应该从你的模型中导入数据库:

>>> from word.models import db
>>> db.Word.find()

或者可能

>>> from core import db
于 2013-10-19T17:02:09.043 回答