예제 #1
0
def test__parse_batch_get_unknown_result_type():
    from google.cloud.firestore_v1.base_client import _parse_batch_get

    response_pb = mock.Mock()
    response_pb._pb.mock_add_spec(spec=["WhichOneof"])
    response_pb._pb.WhichOneof.return_value = "zoob_value"

    with pytest.raises(ValueError):
        _parse_batch_get(response_pb, {}, mock.sentinel.client)

    response_pb._pb.WhichOneof.assert_called_once_with("result")
예제 #2
0
def test__parse_batch_get_found():
    from google.cloud.firestore_v1.types import document
    from google.cloud._helpers import _datetime_to_pb_timestamp
    from google.cloud.firestore_v1.document import DocumentSnapshot
    from google.cloud.firestore_v1.base_client import _parse_batch_get

    now = datetime.datetime.utcnow()
    read_time = _datetime_to_pb_timestamp(now)
    delta = datetime.timedelta(seconds=100)
    update_time = _datetime_to_pb_timestamp(now - delta)
    create_time = _datetime_to_pb_timestamp(now - 2 * delta)

    ref_string = _dummy_ref_string()
    document_pb = document.Document(
        name=ref_string,
        fields={
            "foo": document.Value(double_value=1.5),
            "bar": document.Value(string_value=u"skillz"),
        },
        create_time=create_time,
        update_time=update_time,
    )
    response_pb = _make_batch_response(found=document_pb, read_time=read_time)

    reference_map = {ref_string: mock.sentinel.reference}
    snapshot = _parse_batch_get(response_pb, reference_map,
                                mock.sentinel.client)
    assert isinstance(snapshot, DocumentSnapshot)
    assert snapshot._reference is mock.sentinel.reference
    assert snapshot._data == {"foo": 1.5, "bar": u"skillz"}
    assert snapshot._exists
    assert snapshot.read_time.timestamp_pb() == read_time
    assert snapshot.create_time.timestamp_pb() == create_time
    assert snapshot.update_time.timestamp_pb() == update_time
예제 #3
0
    async def get_all(
        self,
        references: List[AsyncDocumentReference],
        field_paths: Iterable[str] = None,
        transaction=None,
        retry: retries.Retry = gapic_v1.method.DEFAULT,
        timeout: float = None,
    ) -> AsyncGenerator[DocumentSnapshot, Any]:
        """Retrieve a batch of documents.

        .. note::

           Documents returned by this method are not guaranteed to be
           returned in the same order that they are given in ``references``.

        .. note::

           If multiple ``references`` refer to the same document, the server
           will only return one result.

        See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
        more information on **field paths**.

        If a ``transaction`` is used and it already has write operations
        added, this method cannot be used (i.e. read-after-write is not
        allowed).

        Args:
            references (List[.AsyncDocumentReference, ...]): Iterable of document
                references to be retrieved.
            field_paths (Optional[Iterable[str, ...]]): An iterable of field
                paths (``.``-delimited list of field names) to use as a
                projection of document fields in the returned results. If
                no value is provided, all fields will be returned.
            transaction (Optional[:class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction`]):
                An existing transaction that these ``references`` will be
                retrieved in.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.  Defaults to a system-specified policy.
            timeout (float): The timeout for this request.  Defaults to a
                system-specified value.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        """
        request, reference_map, kwargs = self._prep_get_all(
            references, field_paths, transaction, retry, timeout)

        response_iterator = await self._firestore_api.batch_get_documents(
            request=request,
            metadata=self._rpc_metadata,
            **kwargs,
        )

        async for get_doc_response in response_iterator:
            yield _parse_batch_get(get_doc_response, reference_map, self)
예제 #4
0
    async def get_all(
        self,
        references: list,
        field_paths: Iterable[str] = None,
        transaction=None,
    ) -> AsyncGenerator[DocumentSnapshot, Any]:
        """Retrieve a batch of documents.

        .. note::

           Documents returned by this method are not guaranteed to be
           returned in the same order that they are given in ``references``.

        .. note::

           If multiple ``references`` refer to the same document, the server
           will only return one result.

        See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
        more information on **field paths**.

        If a ``transaction`` is used and it already has write operations
        added, this method cannot be used (i.e. read-after-write is not
        allowed).

        Args:
            references (List[.AsyncDocumentReference, ...]): Iterable of document
                references to be retrieved.
            field_paths (Optional[Iterable[str, ...]]): An iterable of field
                paths (``.``-delimited list of field names) to use as a
                projection of document fields in the returned results. If
                no value is provided, all fields will be returned.
            transaction (Optional[:class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction`]):
                An existing transaction that these ``references`` will be
                retrieved in.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        """
        document_paths, reference_map = _reference_info(references)
        mask = _get_doc_mask(field_paths)
        response_iterator = await self._firestore_api.batch_get_documents(
            request={
                "database": self._database_string,
                "documents": document_paths,
                "mask": mask,
                "transaction": _helpers.get_transaction_id(transaction),
            },
            metadata=self._rpc_metadata,
        )

        async for get_doc_response in response_iterator:
            yield _parse_batch_get(get_doc_response, reference_map, self)
예제 #5
0
def test__parse_batch_get_missing():
    from google.cloud.firestore_v1.document import DocumentReference
    from google.cloud.firestore_v1.base_client import _parse_batch_get

    ref_string = _dummy_ref_string()
    response_pb = _make_batch_response(missing=ref_string)
    document = DocumentReference("fizz", "bazz", client=mock.sentinel.client)
    reference_map = {ref_string: document}
    snapshot = _parse_batch_get(response_pb, reference_map,
                                mock.sentinel.client)
    assert not snapshot.exists
    assert snapshot.id == "bazz"
    assert snapshot._data is None
예제 #6
0
    async def get(
        self,
        field_paths: Iterable[str] = None,
        transaction=None,
        retry: retries.Retry = gapic_v1.method.DEFAULT,
        timeout: float = None,
    ) -> Union[DocumentSnapshot, Coroutine[Any, Any, DocumentSnapshot]]:
        """Retrieve a snapshot of the current document.

        See :meth:`~google.cloud.firestore_v1.base_client.BaseClient.field_path` for
        more information on **field paths**.

        If a ``transaction`` is used and it already has write operations
        added, this method cannot be used (i.e. read-after-write is not
        allowed).

        Args:
            field_paths (Optional[Iterable[str, ...]]): An iterable of field
                paths (``.``-delimited list of field names) to use as a
                projection of document fields in the returned results. If
                no value is provided, all fields will be returned.
            transaction (Optional[:class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction`]):
                An existing transaction that this reference
                will be retrieved in.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.  Defaults to a system-specified policy.
            timeout (float): The timeout for this request.  Defaults to a
                system-specified value.

        Returns:
            :class:`~google.cloud.firestore_v1.base_document.DocumentSnapshot`:
                A snapshot of the current document. If the document does not
                exist at the time of the snapshot is taken, the snapshot's
                :attr:`reference`, :attr:`data`, :attr:`update_time`, and
                :attr:`create_time` attributes will all be ``None`` and
                its :attr:`exists` attribute will be ``False``.
        """
        from google.cloud.firestore_v1.base_client import _parse_batch_get

        request, kwargs = self._prep_batch_get(field_paths, transaction, retry,
                                               timeout)

        response_iter = await self._client._firestore_api.batch_get_documents(
            request=request,
            metadata=self._client._rpc_metadata,
            **kwargs,
        )

        async for resp in response_iter:
            # Immediate return as the iterator should only ever have one item.
            return _parse_batch_get(
                get_doc_response=resp,
                reference_map={self._document_path: self},
                client=self._client,
            )

        logger.warning(
            "`batch_get_documents` unexpectedly returned empty "
            "stream. Expected one object.", )

        return DocumentSnapshot(
            self,
            None,
            exists=False,
            read_time=_datetime_to_pb_timestamp(datetime.datetime.now()),
            create_time=None,
            update_time=None,
        )
예제 #7
0
    def _call_fut(get_doc_response, reference_map, client=mock.sentinel.client):
        from google.cloud.firestore_v1.base_client import _parse_batch_get

        return _parse_batch_get(get_doc_response, reference_map, client)
예제 #8
0
def test__parse_batch_get_unset_result_type():
    from google.cloud.firestore_v1.base_client import _parse_batch_get

    response_pb = _make_batch_response()
    with pytest.raises(ValueError):
        _parse_batch_get(response_pb, {}, mock.sentinel.client)