在测试之间正确地重置MongoEngine

时间:2014-07-14 00:14:56

标签: python mongodb testing mongoengine nose

我想知道如何在测试或测试文件之间正确地重置MongoEngine状态。似乎放弃整个数据库是不够的。给出以下示例:

import unittest
from mypackage.models.domain.user import User                                                                        
from mongoengine import connect                                                                                  

class UsersTests(unittest.TestCase):                                                                             

    def setUp(self):                                                                                             
        self.conn = connect('test_database')                                                                     

    def tearDown(self):
        self.conn.drop_database('test_database')
        # User.drop_collection() # Uncomment to get expected results

    def test_something(self):                                                                                    
        print User._collection
        User(name='John H.', email='john@somedoamin.com').save()                                                 

    def test_something_else(self):                                                                               
        print User._collection                                                                                   
        User(name='John H.', email='john@somedoamin.com').save()                                                 

if __name__ == '__main__':                                                                                       
    unittest.main()

如果我用鼻子(或鼻子2)运行它

$ nosetests --notests/models/user_tests.py

None
.Collection(Database(MongoClient(None, None), u'test_database'), u'users')
.
----------------------------------------------------------------------
Ran 2 tests in 0.685s

OK

即使我多次运行,只有第一个User集合设置为None:

$ nosetests --nocapture tests/models/user_tests.py tests/models/user_tests.py
None
.Collection(Database(MongoClient(None, None), u'test_database'), u'users')
.Collection(Database(MongoClient(None, None), u'test_database'), u'users')
.Collection(Database(MongoClient(None, None), u'test_database'), u'users')
.
----------------------------------------------------------------------
Ran 4 tests in 1.382s

OK

此行为会导致一些难以发现的错误。在查看source后,看起来Document类的drop_collection()是我重置集合所需要的,但是为了重置MongoEngine状态而必须将它用于所有集合是很奇怪的。 。有点想知道推荐的方式是什么。任何想法都会非常感激!谢谢!

0 个答案:

没有答案