mongoengine connect() in settings.py testing problem

后端 未结 4 605
忘掉有多难
忘掉有多难 2021-02-06 04:29

I want to be able to do conditional connect() based on either I started django in testing mode or not.

in my settings.py I use mongoengine connect() method to connect to

4条回答
  •  萌比男神i
    2021-02-06 05:06

    What I do is use register_connection, and then mock the connections on test.

    In the file that I define the Mongo Documents I have this:

    import mongoengine
    from django.conf import settings
    
    mongoengine.register_connection(
        'default', settings.MONGOENGINE_DB, **settings.MONGOENGINE_CONNECTION)
    

    Then in the tests I use the mock library to change the behave of connections (it would be possible too to mock one of the functions on the connection sub module like get_db) like this:

    connections = patch.dict(
        mongoengine.connection._connections, {'default': None})
    
    dbs = patch.dict(
        mongoengine.connection._dbs, {'default': {
            'your_collection': None,
            'another_collection': None,
            }})
    
    dbs.start()
    connections.start()
    
    insert = patch.object(mongoengine.queryset.QuerySet, 'insert')
    insert_mock = insert.start()
    
    ...
    
    insert_mock.assert_called_once(...)
    

提交回复
热议问题