Python MongoDB测试随机失败

2024-10-16 20:47:14 发布

您现在位置:Python中文网/ 问答频道 /正文

对Python的unittest和PyMongo有一个奇怪的问题。测试随机成功或失败:

import unittest
from pymongo import Connection

from tractor import Tractor




class TestTractor(unittest.TestCase):
    def setUp(self):
        self.tractor = Tractor(1)

        self.mongo = Connection()
        self.db = self.mongo.tractor

        self.db.classes.remove({'name': {'$regex':'^test_'}})

        self.action_class_id = self.db.classes.insert({'name': 'test_action',
                                                       'metaclass': 'action'})
        self.object_class_id = self.db.classes.insert({'name': 'test_object',
                                                       'metaclass': 'object'})


    def tearDown(self):
        self.tractor = None



    def test_create_class(self):
        cid1 = self.tractor.create_action_class('test_create_action_class')
        cid2 = self.tractor.create_object_class('test_create_object_class')

        self.assertNotEqual(cid1, None)
        self.assertNotEqual(cid2, None)

        action_obj = self.db.classes.find_one({'_id': cid1})
        object_obj = self.db.classes.find_one({'_id': cid2})

        self.assertNotEqual(cid1, cid2)
        self.assertEqual(action_obj['_id'], cid1)
        self.assertEqual(object_obj['_id'], cid2)

        self.assertEqual(action_obj['name'], 'test_create_action_class')
        self.assertEqual(object_obj['name'], 'test_create_object_class')

正在测试的类:

^{pr2}$

随机行为:

silver@aregh-6930-lnx ~/projects/traction/tractor $ python -m unittest discover
......ssEssssssssss
======================================================================
ERROR: test_create_class (tests.test_tractor.TestTractor)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/silver/projects/traction/tractor/tests/test_tractor.py", line 64, in test_create_class
    self.assertEqual(action_obj['_id'], cid1)
TypeError: 'NoneType' object is not subscriptable

----------------------------------------------------------------------
Ran 19 tests in 0.023s

FAILED (errors=1, skipped=12)

。。。在

silver@aregh-6930-lnx ~/projects/traction/tractor $ python -m unittest discover
......ss.ssssssssss
----------------------------------------------------------------------
Ran 19 tests in 0.015s

OK (skipped=12)

这两个结果随机发生在同一个测试中,因为我在没有改变类和测试中任何东西的情况下重新运行测试。在

所有这些都在我的机器上运行,我确信在运行测试时,没有其他人修改MongoDB或代码。在

什么给予?在


Tags: nametestselfidobjdbobjectcreate
1条回答
网友
1楼 · 发布于 2024-10-16 20:47:14

我强烈怀疑这里的问题是你没有使用“安全”模式来写作。在

默认情况下,MongoDB使用“fire-and-forget”模式。这意味着insert命令被发送到服务器,但是驱动程序不检查任何服务器响应。在

当您切换到“安全”模式时,驱动程序将发送insert命令,然后它将发送第二个命令getLastError。第二个命令将在服务器实际提交写操作时返回。在

同样,默认情况下,您是在“fire and forget”模式下运行的,因此这里确实存在潜在的竞争条件。对于单元测试,您需要在“安全”模式下运行。在

insert的函数签名被定义为here。但是,您还应该能够在连接级别进行更改,以便每个到数据库的连接在默认情况下都使用“安全”模式。在

相关问题 更多 >