示例#1
0
    def replace_one(self, filter, replacement, upsert=False, **kwargs):
        """Replace a single document matching the filter.

        :raises ValueError:
            if `update` document is empty

        :raises ValueError:
            if `update` document has fields that starts with `$` sign.
            This method only allows *replacing* document completely. Use
            :meth:`update_one()` for modifying existing document.

        :param filter:
            A query that matches the document to replace.

        :param replacement:
            The new document to replace with.

        :param upsert:
            If ``True``, perform an insert if no documents match the filter.

        :returns:
            deferred instance of :class:`pymongo.results.UpdateResult`.
        """
        validate_ok_for_replace(replacement)

        raw_response = yield self._update(filter,
                                          replacement,
                                          upsert,
                                          multi=False,
                                          **kwargs)
        defer.returnValue(
            UpdateResult(raw_response, self.write_concern.acknowledged))
示例#2
0
    def update_many(self, filter, update, upsert=False, **kwargs):
        """Update one or more documents that match the filter.

        :raises ValueError:
            if `update` document is empty.

        :raises ValueError:
            if `update` document has fields that don't start with `$` sign.
            This method only allows *modification* of document (with `$set`,
            `$inc`, etc.), not *replacing* it. For replacing use
            :meth:`replace_one()` instead.

        :param filter:
            A query that matches the documents to update.

        :param update:
            update document to be used for updating or upserting. See `MongoDB
            Update docs <https://docs.mongodb.org/manual/tutorial/modify-documents/>`_
            for allowed operators.

        :param upsert:
            If ``True``, perform an insert if no documents match the `filter`.

        :returns:
            deferred instance of :class:`pymongo.results.UpdateResult`.
        """
        validate_ok_for_update(update)

        raw_response = yield self._update(filter,
                                          update,
                                          upsert,
                                          multi=True,
                                          **kwargs)
        defer.returnValue(
            UpdateResult(raw_response, self.write_concern.acknowledged))
示例#3
0
 def mock_return(obj_id, body):
     return UpdateResult(
         {
             'n': 1,
             'nModified': 1,
             'ok': 1.0,
             'updatedExisting': True
         }, True)
示例#4
0
def replace_one(co_or_ta, condition=None, replacement=None, **kwargs):
    db = get_db()
    dbType = current_app.config['DBTYPE']

    if co_or_ta is None or condition is None or replacement is None or db is None:
        return UpdateResult()

    if dbType == "mongoDB":
        try:
            collection = db.get_collection(co_or_ta)
            result = collection.replace_one(condition, replacement, **kwargs)
            if not result:
                return UpdateResult()
            return result
        except Exception:
            traceback.print_exc()
            return UpdateResult()
示例#5
0
    def __init__(self, collection_name, **kwargs):
        super().__init__()
        self.name = collection_name
        find_one_result = kwargs.get("find_one_result", {"_id": 1})
        inserted_id = kwargs.get("inserted_id", 1)
        create_indexes_result = kwargs.get("create_indexes_result", None)

        self.insert_one = AsyncMock(return_value=InsertOneResult(
            inserted_id=inserted_id, acknowledged=True))
        self.delete_many = AsyncMock(
            return_value=DeleteResult(raw_result={}, acknowledged=True))
        self.update_one = AsyncMock(
            return_value=UpdateResult(raw_result={}, acknowledged=True))
        self.update_many = AsyncMock(
            return_value=UpdateResult(raw_result={}, acknowledged=True))
        self.count_documents = AsyncMock(return_value=1)
        self.find_one = AsyncMock(return_value=find_one_result)
        self.create_indexes = AsyncMock(return_value=create_indexes_result)
示例#6
0
 def mock_return(obj_id, body):
     return UpdateResult(
         {
             'n': 1,
             'nModified': 0,
             'upserted': ObjectId('5a80868574fdd6de0f4fa430'),
             'ok': 1.0,
             'updatedExisting': False
         }, True)
 async def test_replace_replaces_data(self):
     """Test that replace method works and returns success."""
     self.collection.find_one.return_value = self.data_stub
     self.collection.replace_one.return_value = UpdateResult({}, True)
     success = await self.test_service.replace("testcollection",
                                               self.id_stub, self.data_stub)
     self.collection.replace_one.assert_called_once_with(
         {"accessionId": self.id_stub}, self.data_stub)
     self.assertTrue(success)
 async def test_update_updates_data(self):
     """Test that update method works and returns success."""
     self.collection.find_one.return_value = futurized(self.data_stub)
     self.collection.update_one.return_value = futurized(
         UpdateResult({}, True))
     success = await self.test_service.update("test", self.id_stub,
                                              self.data_stub)
     self.collection.update_one.assert_called_once_with(
         {"accessionId": self.id_stub}, {"$set": self.data_stub})
     self.assertTrue(success)
示例#9
0
    def test_load_unchanged_record(
        self, m_load_profiles, m_migrate, m_mongo_collection, m_taskManager, m_open
    ):
        m_mongo_collection.return_value = UpdateResult(
            {"n": 1, "nModified": 0, "upserted": None}, True
        )
        periodic_obj_mock = Mock()
        m_taskManager.return_value = periodic_obj_mock
        m_load_profiles.return_value = default_profiles
        self.assertEqual(False, load())

        periodic_obj_mock.manage_task.assert_not_called()
示例#10
0
    def test_inventory_errors(
        self,
        m_load_profiles,
        m_migrate,
        m_manage_task,
        m_mongo_collection,
        m_open,
        walk_task,
    ):
        walk_task.return_value = expected_managed_task
        m_mongo_collection.return_value = UpdateResult(
            {"n": 0, "nModified": 1, "upserted": 1}, True
        )
        m_manage_task.side_effect = Exception("Boom!")
        m_load_profiles.return_value = default_profiles

        self.assertEqual(True, load())
示例#11
0
def test_update_http_exception(mocker):
    """Test: update(self, id: int, data: dict) -> int
    HTTPException: Update error."""

    service = PhraseService(
        settings['db_name'],
        settings['cln_name']
    )
    update_result = UpdateResult(None, False)
    mock_update_one = mocker.patch.object(Collection, 'update_one')
    mock_update_one.return_value = update_result
    service.phrases.update_one = mock_update_one

    with pytest.raises(HTTPException) as ex:
        service.update(1, {'status': 1})

    assert 400 == ex.value.status_code
    assert 'Update error' == ex.value.detail
示例#12
0
    def test_load_new_record(
        self,
        m_load_profiles,
        m_migrate,
        m_mongo_collection,
        m_taskManager,
        m_open,
        walk_task,
    ):
        walk_task.return_value = expected_managed_task
        m_mongo_collection.return_value = UpdateResult(
            {"n": 0, "nModified": 1, "upserted": 1}, True
        )
        periodic_obj_mock = Mock()
        m_taskManager.return_value = periodic_obj_mock
        m_load_profiles.return_value = default_profiles
        self.assertEqual(False, load())

        periodic_obj_mock.manage_task.assert_called_with(**expected_managed_task)
 async def test_patch_data(self):
     """Test that patch method works and returns data."""
     json_patch = [
         {
             "op": "add",
             "path": "/metadataObjects/-",
             "value": {
                 "accessionId": self.id_stub,
                 "schema": "study"
             }
         },
     ]
     self.collection.bulk_write.return_value = futurized(
         UpdateResult({}, True))
     success = await self.test_service.patch("test", self.id_stub,
                                             json_patch)
     self.collection.bulk_write.assert_called_once_with(
         [
             UpdateOne(
                 {"testId": "EGA123456"},
                 {
                     "$addToSet": {
                         "metadataObjects": {
                             "$each": [{
                                 "accessionId": "EGA123456",
                                 "schema": "study"
                             }]
                         }
                     }
                 },
                 False,
                 None,
                 None,
                 None,
             )
         ],
         ordered=False,
     )
     self.assertTrue(success)
示例#14
0
    def test_load_new_record_small_walk(
        self,
        m_load_profiles,
        m_migrate,
        m_mongo_collection,
        m_taskManager,
        m_open,
    ):
        profiles = {
            "walk1": {
                "condition": {"type": "walk"},
                "varBinds": [
                    ["IF-MIB", "ifInDiscards", 1],
                    ["IF-MIB", "ifOutErrors"],
                    ["SNMPv2-MIB", "sysDescr", 0],
                ],
            },
            "walk2": {
                "condition": {"type": "walk"},
                "varBinds": [
                    ["IF-MIB", "ifInDiscards", 1],
                    ["IF-MIB", "ifOutErrors"],
                    ["SNMPv2-MIB", "sysDescr", 0],
                ],
            },
        }

        m_mongo_collection.return_value = UpdateResult(
            {"n": 0, "nModified": 1, "upserted": 1}, True
        )
        periodic_obj_mock = Mock()
        m_taskManager.return_value = periodic_obj_mock
        m_load_profiles.return_value = profiles
        self.assertEqual(False, load())
        self.assertEqual(
            {"address": "192.168.0.1", "profile": "walk2"},
            periodic_obj_mock.manage_task.call_args.kwargs["kwargs"],
        )
示例#15
0
 def __default_update_result(self, _id):
     """Return a default (empty) UpdateResult object."""
     return UpdateResult({'upserted': _id}, acknowledged=True)
示例#16
0
    def replace_one(self, filter, replacement, upsert=False, **kwargs):
        validate_ok_for_replace(replacement)

        raw_response = yield self._update(filter, replacement, upsert, multi=False, **kwargs)
        defer.returnValue(UpdateResult(raw_response, self.write_concern.acknowledged))
示例#17
0
    def update_many(self, filter, update, upsert=False, **kwargs):
        validate_ok_for_update(update)

        raw_response = yield self._update(filter, update, upsert, multi=True, **kwargs)
        defer.returnValue(UpdateResult(raw_response, self.write_concern.acknowledged))
示例#18
0
 def update_one(self, filter, update, upsert=False):
     result = self.__update(filter, update, upsert, multi=False)
     return UpdateResult(result, True)