Beispiel #1
0
    async def replace_one(
        self,
        document: "DocType",
        session: Optional[ClientSession] = None,
        bulk_writer: Optional[BulkWriter] = None,
    ) -> Optional[UpdateResult]:
        """
        Replace found document by provided
        :param document: Document - document, which will replace the found one
        :param session: Optional[ClientSession] - PyMongo session
        :param bulk_writer: Optional[BulkWriter] - Beanie bulk writer
        :return: UpdateResult
        """
        self.set_session(session=session)
        if bulk_writer is None:
            result: UpdateResult = (
                await self.document_model.get_motor_collection().replace_one(
                    self.get_filter_query(),
                    Encoder(by_alias=True, exclude={"_id"}).encode(document),
                    session=self.session,
                ))

            if not result.raw_result["updatedExisting"]:
                raise DocumentNotFound
            return result
        else:
            bulk_writer.add_operation(
                Operation(
                    operation=ReplaceOne,
                    first_query=self.get_filter_query(),
                    second_query=Encoder(by_alias=True,
                                         exclude={"_id"}).encode(document),
                    object_class=self.document_model,
                ))
            return None
Beispiel #2
0
async def test_encode_datetime():
    assert isinstance(Encoder().encode(datetime.now()), datetime)

    doc = DocumentForEncodingTest(datetime_field=datetime.now())
    await doc.insert()
    new_doc = await DocumentForEncodingTest.get(doc.id)
    assert isinstance(new_doc.datetime_field, datetime)
Beispiel #3
0
 def get_filter_query(self) -> Mapping[str, Any]:
     if self.find_expressions:
         return Encoder(custom_encoders=self.encoders).encode(
             And(*self.find_expressions).query
         )
     else:
         return {}
Beispiel #4
0
def get_dict(document: "Document", to_db: bool = False):
    exclude = set()
    if document.id is None:
        exclude.add("_id")
    if not document.get_settings().use_revision:
        exclude.add("revision_id")
    return Encoder(by_alias=True, exclude=exclude,
                   to_db=to_db).encode(document)
Beispiel #5
0
async def test_bytes():
    encoded_b = Encoder().encode(b"test")
    assert isinstance(encoded_b, Binary)
    assert encoded_b.subtype == 0

    doc = DocumentForEncodingTest(bytes_field=b"test")
    await doc.insert()
    new_doc = await DocumentForEncodingTest.get(doc.id)
    assert isinstance(new_doc.bytes_field, bytes)
Beispiel #6
0
async def test_custom_filed_types():
    custom1 = DocumentWithCustomFiledsTypes(
        color="#753c38",
        decimal=500,
        secret_bytes=b"secret_bytes",
        secret_string="super_secret_password",
        ipv4address="127.0.0.1",
        ipv4interface="192.0.2.5/24",
        ipv4network="192.0.2.0/24",
        ipv6address="::abc:7:def",
        ipv6interface="2001:db00::2/24",
        ipv6network="2001:db00::0/24",
        timedelta=4782453,
        set_type={"one", "two", "three"},
        tuple_type=tuple([3, "string"]),
        path="/etc/hosts",
    )
    custom2 = DocumentWithCustomFiledsTypes(
        color="magenta",
        decimal=500.213,
        secret_bytes=b"secret_bytes",
        secret_string="super_secret_password",
        ipv4address="127.0.0.1",
        ipv4interface="192.0.2.5/24",
        ipv4network="192.0.2.0/24",
        ipv6address="::abc:7:def",
        ipv6interface="2001:db00::2/24",
        ipv6network="2001:db00::0/24",
        timedelta=4782453,
        set_type=["one", "two", "three"],
        tuple_type=[3, "three"],
        path=Path("C:\\Windows"),
    )
    c1 = await custom1.insert()
    c2 = await custom2.insert()
    c1_fromdb = await DocumentWithCustomFiledsTypes.get(c1.id)
    c2_fromdb = await DocumentWithCustomFiledsTypes.get(c2.id)
    assert set(c1_fromdb.set_type) == set(c1.set_type)
    assert set(c2_fromdb.set_type) == set(c2.set_type)
    c1_fromdb.set_type = c2_fromdb.set_type = c1.set_type = c2.set_type = None
    c1_fromdb.revision_id = None
    c2_fromdb.revision_id = None
    assert Encoder().encode(c1_fromdb) == Encoder().encode(c1)
    assert Encoder().encode(c2_fromdb) == Encoder().encode(c2)
Beispiel #7
0
 def update_query(self) -> Dict[str, Any]:
     query: Dict[str, Any] = {}
     for expression in self.update_expressions:
         if isinstance(expression, BaseUpdateOperator):
             query.update(expression.query)
         elif isinstance(expression, dict):
             query.update(expression)
         else:
             raise TypeError("Wrong expression type")
     return Encoder(custom_encoders=self.encoders).encode(query)
Beispiel #8
0
async def test_bytes_already_binary():
    b = Binary(b"123", 3)
    encoded_b = Encoder().encode(b)
    assert isinstance(encoded_b, Binary)
    assert encoded_b.subtype == 3
Beispiel #9
0
def test_encode_with_custom_encoder():
    assert isinstance(
        Encoder(custom_encoders={
            datetime: str
        }).encode(datetime.now()), str)