我关注此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
Word Class
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文档的实例,以便我可以创建并保存记录。
答案 0 :(得分:1)
我认为您在测试中使用了错误的数据库实例。您应该使用用于注册模型的相同数据库实例。所以,我不知道你的代码是如何构建的,但是,乍一看,你应该从模型中导入数据库:
>>> from word.models import db
>>> db.Word.find()
或者
>>> from core import db