1

使用 mongomock 模拟 mongoengine 时,该connection.drop_database()方法无法正常工作:我第一次使用它,它按预期工作,但第二次根本不起作用。

下面的测试应该是一个全面的解释。

import mongoengine as me
try:
    import pytest
except:
    pass

class DummyDoc(me.Document):
    pass

def test_mongomock():
    db_conn = me.connect(db='mongotest', host='mongomock://localhost')
    db_conn.drop_database('mongotest')

    dd = DummyDoc()
    dd.save()
    assert len(DummyDoc.objects()) == 1

    dd = DummyDoc()
    dd.save()
    assert len(DummyDoc.objects()) == 2

    # First drop_database works as expected!
    db_conn.drop_database('mongotest')
    assert len(DummyDoc.objects()) == 0

    dd = DummyDoc()
    dd.save()
    assert len(DummyDoc.objects()) == 1

    dd = DummyDoc()
    dd.save()
    assert len(DummyDoc.objects()) == 2

    # Second drop_database does not work!!
    db_conn.drop_database('mongotest')
    assert len(DummyDoc.objects()) == 0

# Final part of Pytest output:
#         # Second drop_database does not work!!
#         db_conn.drop_database('mongotest')
# >       assert len(DummyDoc.objects()) == 0    # E       assert 2 == 0
#     E        +  where 2 = len([<DummyDoc: DummyDoc object>, <DummyDoc: DummyDoc object>])
#     E        +    where [<DummyDoc: DummyDoc object>, <DummyDoc: DummyDoc object>] = [<DummyDoc: DummyDoc object>, <DummyDoc: DummyDoc object>]()
#     E        +      where [<DummyDoc: DummyDoc object>, <DummyDoc: DummyDoc object>] = DummyDoc.objects


if __name__ == '__main__':
    test_mongomock()

该脚本可以作为简单的 python3 脚本或 pytest 运行。

4

0 回答 0