Exemplo n.º 1
0
def test_pymongo():
    response = b"%s%s%s%s%s" % (struct.pack("<i", 4), struct.pack(
        "<q", 1), struct.pack("<i", 1), struct.pack(
            "<i", 1), bson.BSON.encode({"hello": "world"}))
    assert asynmongo._unpack_response(response, 1) == {
        'starting_from': 1,
        'number_returned': 1,
        'cursor_id': 1,
        'data': [{
            'hello': 'world'
        }]
    }

    payload = bson.BSON.encode({"hello": "world"})
    response = b"%s%s%s" % (struct.pack(
        "<B", 0), struct.pack("<i", len(payload)), payload)
    assert asynmongo._unpack_response(response, 2013) == {
        'first_payload_type': 0,
        'data': [{
            'hello': 'world'
        }],
        'first_payload_size': 22
    }

    opts = CodecOptions(SON)
    assert auth._auth_key(1, "a", "b") == "90b38d5dbfabd0b883e17ae67847220a"
    assert message.query(0, "%s.$cmd" % "mydb", 0, 1, SON({
        'getnonce': 1
    }), SON({}), opts) == (
        1804289383,
        b'>\x00\x00\x00gE\x8bk\x00\x00\x00\x00\xd4\x07\x00\x00\x00\x00\x00\x00mydb.$cmd\x00\x00\x00\x00\x00\x01\x00\x00\x00\x13\x00\x00\x00\x10getnonce\x00\x01\x00\x00\x00\x00\x05\x00\x00\x00\x00',
        19)
    assert message.query(0, "col.a", 0, 1, {"_id": 1}, None, opts) == (
        846930886,
        b'0\x00\x00\x00\xc6#{2\x00\x00\x00\x00\xd4\x07\x00\x00\x00\x00\x00\x00col.a\x00\x00\x00\x00\x00\x01\x00\x00\x00\x0e\x00\x00\x00\x10_id\x00\x01\x00\x00\x00\x00',
        14)
    assert message.update("col.a", 0, 0, {"_id": 1}, {
        "a": 1
    }, 1, (), False, opts) == (
        1681692777,
        b'8\x00\x00\x00i\x98<d\x00\x00\x00\x00\xd1\x07\x00\x00\x00\x00\x00\x00col.a\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x10_id\x00\x01\x00\x00\x00\x00\x0c\x00\x00\x00\x10a\x00\x01\x00\x00\x00\x00<\x00\x00\x00i\x98<d\x00\x00\x00\x00\xd4\x07\x00\x00\x00\x00\x00\x00col.$cmd\x00\x00\x00\x00\x00\xff\xff\xff\xff\x17\x00\x00\x00\x10getlasterror\x00\x01\x00\x00\x00\x00',
        14)

    msg = message.delete("col.a", {"_id": 1}, 1, (), opts, 0)
    assert len(msg) == 3 and msg[0] == 1714636915 and msg[-1] == 14

    msg = message.insert("col.a", [{"a": 1}], False, 1, (), 0, opts)
    assert len(msg) == 3 and msg[0] == 1957747793 and msg[-1] == 12
Exemplo n.º 2
0
    def update(self, spec, document, upsert=False, manipulate=False,
               safe=False, multi=False, **kwargs):
        """Update a document(s) in this collection.

        Raises :class:`TypeError` if either `spec` or `document` is
        not an instance of ``dict`` or `upsert` is not an instance of
        ``bool``. If `safe` is ``True`` then the update will be
        checked for errors, raising
        :class:`~pymongo.errors.OperationFailure` if one
        occurred. Safe updates require a response from the database,
        while normal updates do not - thus, setting `safe` to ``True``
        will negatively impact performance.

        There are many useful `update modifiers`_ which can be used
        when performing updates. For example, here we use the
        ``"$set"`` modifier to modify some fields in a matching
        document:

        .. doctest::

          >>> db.test.insert({"x": "y", "a": "b"})
          ObjectId('...')
          >>> list(db.test.find())
          [{u'a': u'b', u'x': u'y', u'_id': ObjectId('...')}]
          >>> db.test.update({"x": "y"}, {"$set": {"a": "c"}})
          >>> list(db.test.find())
          [{u'a': u'c', u'x': u'y', u'_id': ObjectId('...')}]

        If `safe` is ``True`` returns the response to the *lastError*
        command. Otherwise, returns ``None``.

        Any additional keyword arguments imply ``safe=True``, and will
        be used as options for the resultant `getLastError`
        command. For example, to wait for replication to 3 nodes, pass
        ``w=3``.

        :Parameters:
          - `spec`: a ``dict`` or :class:`~pymongo.son.SON` instance
            specifying elements which must be present for a document
            to be updated
          - `document`: a ``dict`` or :class:`~pymongo.son.SON`
            instance specifying the document to be used for the update
            or (in the case of an upsert) insert - see docs on MongoDB
            `update modifiers`_
          - `upsert` (optional): perform an upsert if ``True``
          - `manipulate` (optional): manipulate the document before
            updating? If ``True`` all instances of
            :mod:`~pymongo.son_manipulator.SONManipulator` added to
            this :class:`~pymongo.database.Database` will be applied
            to the document before performing the update.
          - `safe` (optional): check that the update succeeded?
          - `multi` (optional): update all documents that match
            `spec`, rather than just the first matching document. The
            default value for `multi` is currently ``False``, but this
            might eventually change to ``True``. It is recommended
            that you specify this argument explicitly for all update
            operations in order to prepare your code for that change.
          - `**kwargs` (optional): any additional arguments imply
            ``safe=True``, and will be used as options for the
            `getLastError` command

        .. versionadded:: 1.8
           Support for passing `getLastError` options as keyword
           arguments.
        .. versionchanged:: 1.4
           Return the response to *lastError* if `safe` is ``True``.
        .. versionadded:: 1.1.1
           The `multi` parameter.

        .. _update modifiers: http://www.mongodb.org/display/DOCS/Updating

        .. mongodoc:: update
        """
        if not isinstance(spec, dict):
            raise TypeError("spec must be an instance of dict")
        if not isinstance(document, dict):
            raise TypeError("document must be an instance of dict")
        if not isinstance(upsert, bool):
            raise TypeError("upsert must be an instance of bool")

        if upsert and manipulate:
            document = self.__database._fix_incoming(document, self)

        if kwargs:
            safe = True

        return self.__database.connection._send_message(
            message.update(self.__full_name, upsert, multi,
                           spec, document, safe, kwargs), safe)
Exemplo n.º 3
0
    def update(self, spec, document, upsert=False, manipulate=False,
               safe=False, multi=False, **kwargs):
        """Update a document(s) in this collection.

        Raises :class:`TypeError` if either `spec` or `document` is
        not an instance of ``dict`` or `upsert` is not an instance of
        ``bool``. If `safe` is ``True`` then the update will be
        checked for errors, raising
        :class:`~pymongo.errors.OperationFailure` if one
        occurred. Safe updates require a response from the database,
        while normal updates do not - thus, setting `safe` to ``True``
        will negatively impact performance.

        There are many useful `update modifiers`_ which can be used
        when performing updates. For example, here we use the
        ``"$set"`` modifier to modify some fields in a matching
        document:

        .. doctest::

          >>> db.test.insert({"x": "y", "a": "b"})
          ObjectId('...')
          >>> list(db.test.find())
          [{u'a': u'b', u'x': u'y', u'_id': ObjectId('...')}]
          >>> db.test.update({"x": "y"}, {"$set": {"a": "c"}})
          >>> list(db.test.find())
          [{u'a': u'c', u'x': u'y', u'_id': ObjectId('...')}]

        If `safe` is ``True`` returns the response to the *lastError*
        command. Otherwise, returns ``None``.

        Any additional keyword arguments imply ``safe=True``, and will
        be used as options for the resultant `getLastError`
        command. For example, to wait for replication to 3 nodes, pass
        ``w=3``.

        :Parameters:
          - `spec`: a ``dict`` or :class:`~bson.son.SON` instance
            specifying elements which must be present for a document
            to be updated
          - `document`: a ``dict`` or :class:`~bson.son.SON`
            instance specifying the document to be used for the update
            or (in the case of an upsert) insert - see docs on MongoDB
            `update modifiers`_
          - `upsert` (optional): perform an upsert if ``True``
          - `manipulate` (optional): manipulate the document before
            updating? If ``True`` all instances of
            :mod:`~pymongo.son_manipulator.SONManipulator` added to
            this :class:`~pymongo.database.Database` will be applied
            to the document before performing the update.
          - `safe` (optional): check that the update succeeded?
          - `multi` (optional): update all documents that match
            `spec`, rather than just the first matching document. The
            default value for `multi` is currently ``False``, but this
            might eventually change to ``True``. It is recommended
            that you specify this argument explicitly for all update
            operations in order to prepare your code for that change.
          - `**kwargs` (optional): any additional arguments imply
            ``safe=True``, and will be used as options for the
            `getLastError` command

        .. versionadded:: 1.8
           Support for passing `getLastError` options as keyword
           arguments.
        .. versionchanged:: 1.4
           Return the response to *lastError* if `safe` is ``True``.
        .. versionadded:: 1.1.1
           The `multi` parameter.

        .. _update modifiers: http://www.mongodb.org/display/DOCS/Updating

        .. mongodoc:: update
        """
        if not isinstance(spec, dict):
            raise TypeError("spec must be an instance of dict")
        if not isinstance(document, dict):
            raise TypeError("document must be an instance of dict")
        if not isinstance(upsert, bool):
            raise TypeError("upsert must be an instance of bool")

        if manipulate:
            document = self.__database._fix_incoming(document, self)

        if self.safe or kwargs:
            safe = True
            if not kwargs:
                kwargs.update(self.get_lasterror_options())

        return self.__database.connection._send_message(
            message.update(self.__full_name, upsert, multi,
                           spec, document, safe, kwargs), safe)