跳转到主要内容

带有本地文件系统挂载的Google Cloud Storage模拟库。

项目描述

cloud-storage-mocker

本地文件系统挂载的Google Cloud Storage Python客户端的模拟库。

安装

对于包用户

pip install cloud-storage-mocker

对于包开发者

git clone git@github.com:odashi/cloud-storage-mocker
cd cloud-storage-mocker
python -m venv venv
source venv/bin/activate
pip install -e '.[dev]'

包的工作原理

基本用法

此库提供patch上下文管理器,用于替换google-cloud-storage包中的以下类

  • 客户端
  • 对象

patch接受一个Mount对象列表,这些对象代表本地文件系统上的桶名称与目录之间的映射。每个Mount都有布尔配置readablewritable,用于控制挂载桶的读写权限。

此包的典型用例是编写单元测试以检查与Google Cloud Storage一起工作的代码的行为

import pathlib

import google.cloud.storage  # type: ignore[import]

from cloud_storage_mocker import BlobMetadata, Mount
from cloud_storage_mocker import patch as gcs_patch


def test_something(tmp_path: pathlib.Path) -> None:
    # Creates two temporary directories for readable/writable buckets.
    src_dir = tmp_path / "src"
    dest_dir = tmp_path / "dest"
    src_dir.mkdir()
    dest_dir.mkdir()

    # A sample file on the readable bucket.
    (src_dir / "hello.txt").write_text("Hello.")
    # Optionally, object metadata can also be specified by the file beside the
    # content, suffixed by ".__metadata__".
    (src_dir / "hello.txt.__metadata__").write_text(
        BlobMetadata(content_type="text/plain").dump_json()
    )

    # Mounts directories. Empty list is allowed if no actual access is required.
    with gcs_patch(
        [
            Mount("readable", src_dir, readable=True),
            Mount("writable", dest_dir, writable=True),
        ],
    ):
        client = google.cloud.storage.Client()

        # Reads a blob.
        blob = client.bucket("readable").blob("hello.txt")
        assert blob.download_as_text() == "Hello."
        # Metadata is available after downloading the content.
        assert blob.content_type == "text/plain"

        # Writes a blob.
        blob = client.bucket("writable").blob("world.txt")
        blob.upload_from_string("World.")

    # Checks if the file is written appropriately.
    assert (dest_dir / "world.txt").read_text() == "World."

修补的方法/属性

以下列出的方法具有挂载本地文件系统的特殊行为

其他方法映射到MagicMock

Client()

Client.bucket()

Bucket()

Bucket.blob()

Blob()

# Blob properties (download only)
Blob.cache_control
Blob.content_disposition
Blob.content_encoding
Blob.content_language
Blob.content_type

Blob.download_to_file()
Blob.download_to_filename()
Blob.download_as_bytes()
Blob.download_as_string()
Blob.download_as_text()
Blob.upload_from_file()
Blob.upload_from_filename()
Blob.upload_from_string()

注意

此库基本上是提供用于编写单元测试。不要在生产代码中使用此库。

项目详情


下载文件

下载您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

cloud_storage_mocker-0.3.4.tar.gz (6.9 kB 查看散列值)

上传时间

构建分发

cloud_storage_mocker-0.3.4-py3-none-any.whl (7.1 kB 查看散列值)

上传时间 Python 3

支持者