Ejemplo n.º 1
0
 async def test_create_reports_fail_correctly(self):
     """Test that failure is reported, when write not acknowledged."""
     self.collection.insert_one.return_value = InsertOneResult(None, False)
     success = await self.test_service.create("testcollection",
                                              self.data_stub)
     self.collection.insert_one.assert_called_once_with(self.data_stub)
     self.assertFalse(success)
Ejemplo n.º 2
0
 async def test_create_inserts_data(self):
     """Test that create method works and returns success."""
     self.collection.insert_one.return_value = futurized(
         InsertOneResult(ObjectId("0123456789ab0123456789ab"), True))
     success = await self.test_service.create("test", self.data_stub)
     self.collection.insert_one.assert_called_once_with(self.data_stub)
     self.assertTrue(success)
Ejemplo n.º 3
0
 async def test_create_folder_inserts_folder(self):
     """Test that create method works for folder and returns success."""
     self.collection.insert_one.return_value = InsertOneResult(
         ObjectId("0000000000aa1111111111bb"), True)
     folder = await self.test_service.create("folder", self.folder_stub)
     self.collection.insert_one.assert_called_once_with(self.folder_stub)
     self.assertTrue(folder)
Ejemplo n.º 4
0
def insert_one(co_or_ta, document=None, **kwargs):
    db = get_db()
    dbType = current_app.config['DBTYPE']

    if document is None or co_or_ta is None or db is None:
        return InsertOneResult()

    if dbType == "mongoDB":
        try:
            collection = db.get_collection(co_or_ta)
            result = collection.insert_one(document=document, **kwargs)
            if not result:
                return InsertOneResult()
            return result
        except Exception:
            traceback.print_exc()
            return InsertOneResult()
Ejemplo n.º 5
0
    def insert_one(self, document, **kwargs):
        """Insert a single document into collection

        :param document: Document to insert
        :returns:
            :class:`Deferred` that called back with
            :class:`pymongo.results.InsertOneResult`
        """
        inserted_ids, response = yield self._insert_one_or_many([document],
                                                                **kwargs)
        if response:
            _check_write_command_response([[0, response]])
        defer.returnValue(
            InsertOneResult(inserted_ids[0], self.write_concern.acknowledged))
Ejemplo n.º 6
0
    def test_failed_mongo_insert(self, mocked_insert_one):
            mocked_insert_one.return_value = InsertOneResult(None, False)

            response = self.app.post(
                '/%s/movies' % self.api,
                headers=self.headers,
                data=json.dumps({}),
                content_type='application/json'
            )
            self.assertEqual(response.status_code, 500)
            response_json = json.loads(response.data or '{}')
            self.assertDictContainsSubset(
                {'message': u'The resource can not be created'},
                response_json
            )
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
def cart_add(item: dict) -> InsertOneResult:
    """ Add an item to a shopping cart """
    LOGGER.debug('adding item to shopping cart: {}'.format(item['name']))
    db = connect_to_db() # pylint: disable=invalid-name
    result = InsertOneResult(None, False)
    try:
        # TODO: implement validation
        items = items_list()
        for each in items:
            if item.get('name') == each['name']:
                result_remove = items_remove(each['name'])
                if result_remove.acknowledged:
                    result = db.cart.insert_one(item)
                    break
    except Exception as exception:
        # TODO: use specifc exceptions. Create a custom error exception
        LOGGER.error(exception)
        raise Exception('There was a DB problem')
    return result
Ejemplo n.º 9
0
def test_create_http_exception(mocker):
    """Test: create(self, data: dict) -> int
    HTTPException: Creation error."""

    service = PhraseService(
        settings['db_name'],
        settings['cln_name']
    )
    insert_result = InsertOneResult(0, None)
    mock_insert_one = mocker.patch.object(Collection, 'insert_one')
    mock_insert_one.return_value = insert_result
    service.phrases.insert_one = mock_insert_one

    data = {
        'author': 'create-author',
        'text': 'created-text'
    }
    with pytest.raises(HTTPException) as ex:
        service.create(data)

    assert 400 == ex.value.status_code
    assert 'Creation error' == ex.value.detail
Ejemplo n.º 10
0
 def insert_one(self, document, **kwargs):
     inserted_ids = yield self._insert_one_or_many([document], **kwargs)
     defer.returnValue(InsertOneResult(inserted_ids[0], self.write_concern.acknowledged))
Ejemplo n.º 11
0
def mock_insert_workaround(collection, document):
    inserted_id = collection.insert(document)
    return InsertOneResult(inserted_id, True)
Ejemplo n.º 12
0
 def insert(self, document):
     self.inserted_items.append(document)
     return InsertOneResult(RawBSONDocument(BSON.encode(document)), True)
Ejemplo n.º 13
0
 def insert_one(self, document, session=None):
     result = self.__insert(document)
     if result:
         result = result[0]
     return InsertOneResult(result or None, True)
Ejemplo n.º 14
0
 def test_format_calledWithValidOperationResult_returnCorrectResult(self):
     expected = '{\n\t"acknowledged" : ' + 'true' + ',\n\t"insertedId" : ' + 'ObjectId("4d128b6ea794fc13a8000002")' + '\n}'
     actual = self.sut.format(InsertOneResult(ObjectId("4d128b6ea794fc13a8000002"), True))
     self.assertEqual(actual, expected)
Ejemplo n.º 15
0
 def insert_one(self, document, **kwargs):
     inserted_ids, response = yield self._insert_one_or_many([document], **kwargs)
     if response:
         _check_write_command_response([[0, response]])
     defer.returnValue(InsertOneResult(inserted_ids[0], self.write_concern.acknowledged))
Ejemplo n.º 16
0
 def mock_return(body):
     return InsertOneResult('5a80868574fdd6de0f4fa432', True)
Ejemplo n.º 17
0
def insert_mock(monkeypatch):
    with monkeypatch.context() as m:
        result = InsertOneResult(inserted_id=ObjectId(), acknowledged=True)
        m.setattr(Collection, "insert_one", MagicMock(return_value=result))
        yield result.inserted_id