diff --git a/.agents/verifying-drive-api-params.md b/.agents/verifying-drive-api-params.md new file mode 100644 index 0000000..e3305f0 --- /dev/null +++ b/.agents/verifying-drive-api-params.md @@ -0,0 +1,66 @@ +# Verifying Google Drive API parameters + +When adding or changing a Drive API call, **verify each parameter against the +live discovery document** before trusting it. Do not rely on: + +- **Type stubs** (`googleapiclient-stubs`). Most methods are typed + `def method(self, *, fileId, ..., **kwargs)`. The `**kwargs` swallows *any* + keyword, so the stub accepting `supportsAllDrives=True` proves only that + Python won't raise β€” not that the API supports the parameter. +- **Human docs / blog posts / memory.** They lag, omit per-method differences, + and frequently copy a parameter (like `supportsAllDrives`) onto methods that + don't actually take it. + +The discovery document is the source of truth: the Python client is generated +from it, and it lists the exact parameters each method accepts. + +## How to check + +```bash +# Fetch once +curl -s "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest" -o drive_v3.json + +# List the accepted parameters for a given method, e.g. files.export +uv run python -c " +import json +d = json.load(open('drive_v3.json')) +m = d['resources']['files']['methods']['export'] # .methods. +print(sorted(m.get('parameters', {}).keys())) +" +``` + +Swap `'files'` / `'export'` for the resource and method you care about +(`files.get`, `files.list`, `files.create`, `drives.list`, ...). + +To see a parameter's type / required-ness / description: + +```bash +uv run python -c " +import json +d = json.load(open('drive_v3.json')) +import pprint; pprint.pprint(d['resources']['files']['methods']['export']['parameters']) +" +``` + +## Worked example (the bug this guide came from) + +``` +files.export -> ['fileId', 'mimeType'] # NO supportsAllDrives +files.get -> ['acknowledgeAbuse', 'fileId', 'includeLabels', + 'includePermissionsForView', 'supportsAllDrives', + 'supportsTeamDrives'] # has it +``` + +`files.export`/`export_media` accept **only** `fileId` and `mimeType`. Passing +`supportsAllDrives=True` was silently serialized as an ignored query param β€” +no error, mocked tests still passed β€” but it was wrong. `files.get` *does* +take it, which is why it's correct elsewhere in the code. Per-method +differences like this are exactly what the discovery doc catches and stubs hide. + +## Checklist when touching a Drive call + +1. Find the method: `resources..methods.` in the discovery doc. +2. Confirm **every** kwarg you pass is in that method's `parameters`. +3. If a kwarg isn't listed, remove it (it does nothing) or find the right method. +4. Remember mocked unit tests won't catch an unsupported-but-ignored param β€” + the discovery doc is the only cheap pre-flight check. diff --git a/.github/ISSUE_TEMPLATE/bug-report.yaml b/.github/ISSUE_TEMPLATE/bug-report.yaml new file mode 100644 index 0000000..3b2e373 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.yaml @@ -0,0 +1,57 @@ +name: πŸ› Bug report +description: Report a bug or unexpected behavior in gdrive_fsspec +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thank you for contributing to gdrive_fsspec! ✊ + Please provide as much information as possible to help us reproduce and fix your issue quickly. + - type: checkboxes + id: checks + attributes: + label: Initial Checks + description: Just making sure we're on the same page. + options: + - label: I'm using the [latest version](https://github.com/marimo-team/gdrive-fsspec/releases/latest) of gdrive_fsspec + required: true + - label: I've searched for my issue in [the issue tracker](https://github.com/marimo-team/gdrive-fsspec/issues) before opening this issue + required: true + - type: textarea + id: description + attributes: + label: Description + description: | + Please explain what you're seeing and what you would expect to see. + - **A line of code is worth a thousand words**: you can include a minimal, reproducible example below. + validations: + required: true + - type: textarea + id: example + attributes: + label: Minimal, Reproducible Example + description: > + If at all possible, please add a self-contained, + [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) + that demonstrates the bug. + (This will be automatically formatted as code, so no need for backticks.) + placeholder: | + from gdrive_fsspec import GoogleDriveFileSystem + + fs = GoogleDriveFileSystem( + token="browser", + skip_instance_cache=True + ) + ... + render: Python + - type: textarea + id: version + attributes: + label: Python, gdrive_fsspec & fsspec version + description: | + Which version of Python, gdrive_fsspec, and fsspec are you using? + value: | + - Python: + - gdrive_fsspec: + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yaml b/.github/ISSUE_TEMPLATE/config.yaml new file mode 100644 index 0000000..f41da5a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yaml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: πŸ’¬ Questions & Discussions + url: https://github.com/marimo-team/gdrive-fsspec/discussions + about: Have a question or want to discuss an idea? Start a discussion here instead of opening an issue. diff --git a/.github/ISSUE_TEMPLATE/feature-request.yaml b/.github/ISSUE_TEMPLATE/feature-request.yaml new file mode 100644 index 0000000..61455fd --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.yaml @@ -0,0 +1,25 @@ +name: πŸš€ Feature Request +description: "Suggest a new feature for gdrive_fsspec" +labels: ["feature"] +body: + - type: markdown + attributes: + value: Thank you for contributing to gdrive_fsspec! ✊ + - type: textarea + id: description + attributes: + label: Description + description: | + Please give as much detail as possible about the feature you would like to suggest. πŸ™ + You might like to add: + * A demo of how code might look when using the feature + * Your use case(s) for the feature + * Reference to other projects that have a similar feature + validations: + required: true + - type: textarea + id: references + attributes: + label: References + description: | + Please add any links or references that might help us understand your feature request better. πŸ“š diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..f5cbf94 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,8 @@ +## Summary + +Fixes # + +## Checklist + +- [ ] Tests added/updated for new behavior +- [ ] Docstrings use RST double backticks for inline code (e.g. ``drive``, not `drive`) diff --git a/.github/workflows/tests.yaml b/.github/workflows/ci.yaml similarity index 58% rename from .github/workflows/tests.yaml rename to .github/workflows/ci.yaml index 96592d9..4a8ba0c 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/ci.yaml @@ -2,7 +2,7 @@ name: CI on: push: - branches: [master] + branches: [main] pull_request: workflow_dispatch: @@ -25,8 +25,25 @@ jobs: - uses: ./.github/actions/setup + # pyrefly-check uses language: system and expects pyrefly on PATH. - name: Run pre-commit - run: uvx pre-commit run --all-files + run: PATH="$PWD/.venv/bin:$PATH" uvx pre-commit run --all-files + + typecheck: + name: Typecheck + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: ./.github/actions/setup + with: + python-version: "3.13" + + - name: Run pyrefly + run: uv run pyrefly check --output-format=github test: name: Test (Python ${{ matrix.python-version }}) @@ -49,14 +66,34 @@ jobs: - name: Run unit tests run: uv run pytest -v + coverage: + name: Coverage + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: ./.github/actions/setup + with: + python-version: "3.13" + + - name: Run tests with coverage + run: | + uv run pytest \ + --cov=gdrive_fsspec \ + --cov-report=term-missing \ + --cov-report=xml \ + --cov-fail-under=95 + integration: name: Integration tests runs-on: ubuntu-latest # Run only when Drive credentials are available: manual dispatch, pushes to - # master, or PRs from this repo (fork PRs are skipped β€” they cannot use secrets). + # main, or PRs from this repo (fork PRs are skipped β€” they cannot use secrets). if: >- github.event_name == 'workflow_dispatch' || - (github.event_name == 'push' && github.ref == 'refs/heads/master') || + (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) timeout-minutes: 15 @@ -75,6 +112,8 @@ jobs: - name: Run integration tests env: - GDRIVE_FSSPEC_DRIVE: gdrivefs-testing GDRIVE_FSSPEC_CREDENTIALS_PATH: ${{ secrets.GDRIVE_FSSPEC_CREDENTIALS_PATH }} + GDRIVE_FSSPEC_DRIVE_FULL_ACCESS: drive-full-access + GDRIVE_FSSPEC_DRIVE_CONTENT_MANAGER: drive-test + GDRIVE_FSSPEC_DRIVE_READONLY: drive-readonly run: uv run pytest -v -m integration diff --git a/.gitignore b/.gitignore index caa9a83..e948db7 100644 --- a/.gitignore +++ b/.gitignore @@ -108,3 +108,4 @@ uv.lock /src/gdrive_fsspec/_version.py /tmp/* +.DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4545198..6a35942 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,6 +19,13 @@ repos: args: [--fix, --show-fixes] - id: ruff-format types_or: [python] + - repo: https://github.com/facebook/pyrefly-pre-commit + rev: 1.1.1 # Note: this is the version of the pre-commit hook, NOT the pyrefly version used for type checking + hooks: + - id: pyrefly-check + name: Pyrefly (type checking) + pass_filenames: false # Recommended to do full repo checks. However, you can change this to `true` to only check changed files + language: system # Use system-installed pyrefly - repo: https://github.com/codespell-project/codespell rev: v2.4.2 hooks: diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ff01de7 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,3 @@ +Set up the environment as described in [CONTRIBUTING.md](CONTRIBUTING.md). + +To verify Google Drive APIs, refer to [verifying-drive-api-params.md](.agents/verifying-drive-api-params.md). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..4090931 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,112 @@ +# Contributing to gdrive-fsspec + +Thanks for your interest in contributing! This guide covers local setup, running tests, and the checks CI runs on pull requests. + +## Prerequisites + +Install `uv` and `pre-commit`: + +- [`uv` install docs](https://docs.astral.sh/uv/getting-started/installation/) +- [`pre-commit` install docs](https://pre-commit.com/#install) + +## Setup + +1. Fork the repository on GitHub, then clone your fork: + + ```sh + git clone git@github.com:/gdrive-fsspec.git + cd gdrive-fsspec + ``` + +2. Create the virtual environment and install dependencies: + + ```sh + uv sync --all-groups + ``` + +3. Install pre-commit hooks: + + ```sh + pre-commit install + ``` + +## Running checks locally + +CI runs the same checks you can run before pushing: + +**Lint** (ruff, codespell, formatting, and more via pre-commit): + +```sh +pre-commit run --all-files +``` + +**Type checking** (pyrefly): + +```sh +uv run pyrefly check +``` + +**Unit tests** (default; no Google Drive credentials needed): + +```sh +uv run pytest -v +``` + +**Coverage** (same unit tests; reports missing lines; CI requires at least 95%): + +```sh +uv run pytest --cov=gdrive_fsspec --cov-report=term-missing +``` + +## Docstrings + +Use reStructuredText (RST) double backticks for inline code in docstringsβ€”for example, ``drive`` rather than `drive`. This matches the existing codebase and renders correctly with Sphinx-style tooling. + +## Integration tests + +Integration tests use a real Google Drive account and a directory named `gdrive_fsspec_testdir` on Drive. + +```sh +uv run pytest -v -m integration +``` + +By default, the tests trigger a browser login to authenticate. However, you can also use service-account credentials. + +Hence, we dedicate a **profile** to each method of testing. Each profile targets a different drive and has different roles. Any profile whose variables are unset is skipped, so you can run a subset locally. + +| Profile | Auth | Target | Access | Exercises | +| --- | --- | --- | --- | --- | +| `full_access` | service account | shared drive | Manager | Full CRUD (the default `fs` fixture when a key is set) | +| `content_manager` | service account | shared drive | Content manager | Trash allowed; permanent delete denied | +| `readonly` | service account | shared drive | Viewer | Reads allowed; all mutations denied | +| `sa_my_drive` | service account | _none_ (SA My Drive) | β€” | No quota; uploads must fail | +| `user` | user OAuth | My Drive | user | Full CRUD as a real user (the default `fs` fixture when no key is set) | + +Set these environment variables before running them: + +- `GDRIVE_FSSPEC_CREDENTIALS_PATH` β€” path to a service-account JSON, or the JSON string (starting with `{`). Shared by every service-account profile. **Its presence also picks the default `fs`/`make_fs` identity:** set β†’ full-access service account; unset β†’ OAuth user. +- `GDRIVE_FSSPEC_DRIVE_FULL_ACCESS` β€” **Shared Drive** (name or ID) where the service account has **Manager** access. +- `GDRIVE_FSSPEC_DRIVE_CONTENT_MANAGER` β€” _optional_. Shared Drive where the service account has **Content manager** access. +- `GDRIVE_FSSPEC_DRIVE_READONLY` β€” _optional_. Shared Drive where the service account has **Viewer** access. Add a file to it manually to exercise the trash-denied path. + +

+ Configuring shared drives in Google Drive UI +

+ +The `sa_my_drive` profile needs no extra variables (it reuses the key with no shared drive). + +To run tests with browser authentication, run `GDRIVE_FSSPEC_FORCE_BROWSER=1 uv run pytest -v -m integration`. + +Service accounts cannot own files in Google Drive and have no storage quota. Uploads must target a [Shared Drive](https://developers.google.com/workspace/drive/api/guides/about-shareddrives) where the service account is a member with at least **Contributor** access. See [Google's storage-limit errors](https://developers.google.com/workspace/drive/api/guides/handle-errors#storage-limit). + +> **Note:** Integration tests do not run on PRs from forks, because those workflows cannot use repository secrets. They run on pushes to `main` and same-repo PRs. Google Drive has no good emulator; see [this discussion](https://github.com/fsspec/gdrive-fsspec/issues/23#issuecomment-2030367587). + +### Creating a service account + +1. Enable Google Drive API for the project in the Google Cloud Console. +2. Create a new service account. +3. Grant the service account permissions (likely Editor role, as there is no fine-grained Drive permissions). +4. Create a new key and download the JSON file. + +5. To add a shared drive to the service account, get the service account email. +6. From the shared drive, add the service account email as a member with at least Contributor access. diff --git a/README.md b/README.md index 30d5f7d..4de1a0d 100644 --- a/README.md +++ b/README.md @@ -1,141 +1,108 @@ -# Google Drive fsspec implementation +# gdrive-fsspec -This is an implementation of the fsspec interface for Google Drive. +

+ Google Drive +

-This software is in beta stage and should not be relied upon in production settings. +

+ CI + + + license +

-## Installation +

+ fsspec docs Β· + contributing +

+ +--- + +**gdrive-fsspec** implements the [fsspec](https://filesystem-spec.readthedocs.io/) interface for Google Drive. List directories, read and write files, and plug into any library that speaks fsspec. -You can install it with pip from pypi or directly from source: +## Quickstart ```sh -pip install gdrive_fsspec -pip install git+https://github.com/fsspec/gdrive-fsspec +# Currently, you need to install from the GitHub repository, there is no PyPI package yet. +pip install git+https://github.com/marimo-team/gdrive-fsspec ``` -## Usage +```python +from gdrive_fsspec import GoogleDriveFileSystem -As gdrivefs implements the fsspec interface, most documentation can be found at https://filesystem-spec.readthedocs.io/en/latest/usage.html. +# First run: token="browser". Later: token="cache" +fs = GoogleDriveFileSystem(token="cache") -### Authentication +for entry in fs.ls(""): + print(entry["name"], entry["type"]) -There are several methods to authenticate gdrivefs against Google Drive. +with fs.open("my-folder/data.csv", "rb") as f: + print(f.read()) +``` -#### 1. Service account credentials +Most filesystem operations follow the [fsspec usage guide](https://filesystem-spec.readthedocs.io/en/latest/usage.html). -In this method, you provide a dict containing the service account credentials obtained -in the GCP console. The dict content is the same as the JSON file downloaded from the GCP console. -More details can be found here: . -This credential can be useful -when integrating with other GCP services, and when you don't want the user to -be prompted to authenticate. +## Why use gdrive-fsspec -```python -from gdrive_fsspec import GoogleDriveFileSystem -fs = GoogleDriveFileSystem(creds=service_account_credentials, - token="service_account") -``` +1. **fsspec-native** β€” same API as S3, GCS, and local filesystems; works with ecosystem tools that accept an `AbstractFileSystem`. +2. **Flexible auth** β€” user OAuth, service accounts, or anonymous read-only access to public files. +3. **Shared Drives** β€” target a Shared Drive by name via the `drive=` argument (required for service-account uploads). +4. **Scoped access** β€” `read_only` or `full_control` OAuth scopes. -#### 2. OAuth with user credentials +## Authentication -A browser will be opened to complete the OAuth authentication flow. Afterwards, the access -token will be stored locally, and you can reuse it in subsequent sessions. +### User OAuth (personal Drive) + +A browser opens on first use; the token is cached for later sessions. ```python -# use this the first time you run -token = 'browser' -# use this on subsequent attempts -# token = 'cache' -fs = GoogleDriveFileSystem(token=token) +fs = GoogleDriveFileSystem(token="browser") # first time +fs = GoogleDriveFileSystem(token="cache") # reuse cached token ``` -On headless or remote machines (SSH sessions, containers, CI, and similar environments), -you may not be able to bind a local callback server or open a browser on the same host. -In that case, pass `use_local_webserver: False` in `auth_kwargs` to request a token via -the console. +On headless or remote machines (SSH, containers, CI), pass `use_local_webserver=False` in `auth_kwargs` to authenticate via the console: ```python fs = GoogleDriveFileSystem( - token=token, - auth_kwargs={'use_local_webserver': False}, + token="browser", + auth_kwargs={"use_local_webserver": False}, ) ``` -#### 3. Anonymous (read-only) access +### Service account -If you want to interact with files that are shared publicly ("anyone with the link"), -then you do not need to authenticate to Google Drive. +Provide a dict with the service account credentials from the GCP console (same content as the downloaded JSON). See [Google's service account key docs](https://cloud.google.com/iam/docs/service-account-creds#key-types). ```python -token = 'anon' -fs = GoogleDriveFileSystem(token=token) +fs = GoogleDriveFileSystem( + creds=service_account_credentials, + token="service_account", + drive="My Shared Drive", # required for uploads +) ``` -See ``GoogleDriveFileSystem`` docstring for more details. - -## Development +Service accounts have no personal storage quota. Uploads must target a [Shared Drive](https://developers.google.com/workspace/drive/api/guides/about-shareddrives) where the account is at least a **Contributor**. See [Google's storage-limit errors](https://developers.google.com/workspace/drive/api/guides/handle-errors#storage-limit). -### Setup +### Anonymous (public files) -1. Install `uv` and `pre-commit`: +For files shared publicly ("anyone with the link"), no authentication is needed: -- [uv install docs](https://docs.astral.sh/uv/getting-started/installation/) -- [pre-commit install docs](https://pre-commit.com/#install) - -2. Clone your fork and `cd` into the repo: - -```sh -git clone git@github.com:/gdrive-fsspec.git -cd gdrive-fsspec -``` - -3. Set up the environment: -```sh -uv sync -pre-commit install +```python +fs = GoogleDriveFileSystem(token="anon") ``` -### Running tests - -There are unit tests and integration tests. Integration tests use a directory -named `gdrive_fsspec_testdir` on Google Drive. - -**Unit tests** mock the Google Drive API and need no credentials. By default, -`pytest` runs unit tests only: - -```sh -uv run pytest -v -``` +See the ``GoogleDriveFileSystem`` docstring for `root_file_id`, `access`, `spaces`, and other options. -**Integration tests** hit a real Google Drive account: +## Installation ```sh -uv run pytest -v -m integration +pip install git+https://github.com/marimo-team/gdrive-fsspec ``` -Set these environment variables before running them: - -- `GDRIVE_FSSPEC_CREDENTIALS_PATH` β€” path to a service-account JSON, or the JSON string (starting with `{`). Required when using `service_account` (the default). -- `GDRIVE_FSSPEC_CREDENTIALS_TYPE` β€” token type (`service_account` default; use `cache` or `browser` for user OAuth). -- `GDRIVE_FSSPEC_DRIVE` β€” **Shared Drive name**. Required for service-account upload tests. - -Service accounts cannot own files in Google Drive and have no storage quota. -Uploads must target a [Shared Drive](https://developers.google.com/workspace/drive/api/guides/about-shareddrives) where the service account is a member with at least **Contributor** access. -See [Google’s storage-limit errors](https://developers.google.com/workspace/drive/api/guides/handle-errors#storage-limit). - -For a personal Drive (no Shared Drive), use user OAuth instead: -`GDRIVE_FSSPEC_CREDENTIALS_TYPE=cache` after a one-time `browser` login. - -To run all tests, override the default marker filter: - -```sh -uv run pytest -v -m "" -``` +## Contributing -> **Note:** Integration tests do not run on PRs from forks, because those -> workflows cannot use repository secrets. They run on pushes to `master` and same repo PRs. -> Google Drive has no good emulator; see [link](https://github.com/fsspec/gdrive-fsspec/issues/23#issuecomment-2030367587). +Contributions welcome β€” see [CONTRIBUTING.md](CONTRIBUTING.md) for setup, tests, and CI. -## Other implementations +## Related projects -- [PyDrive2](https://github.com/iterative/PyDrive2?tab=readme-ov-file#fsspec-filesystem) also provides an fsspec-compatible Google Drive API. +- [PyDrive2](https://github.com/iterative/PyDrive2?tab=readme-ov-file#fsspec-filesystem) β€” another fsspec-compatible Google Drive implementation diff --git a/assets/google-drive-icon.svg b/assets/google-drive-icon.svg new file mode 100644 index 0000000..97fcf5b --- /dev/null +++ b/assets/google-drive-icon.svg @@ -0,0 +1 @@ + diff --git a/assets/shared-drives.png b/assets/shared-drives.png new file mode 100644 index 0000000..0080cb5 Binary files /dev/null and b/assets/shared-drives.png differ diff --git a/pyproject.toml b/pyproject.toml index 4d7533d..d9d5326 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,17 +28,22 @@ dependencies = [ "google-api-python-client", "google-auth-httplib2", "google-auth-oauthlib", - "pydata_google_auth" + "pydata_google_auth", + "typing-extensions>=4.15.0", ] [dependency-groups] dev = [ + "google-api-python-client-stubs>=1.37.0", + "pyrefly>=1.1.1", "pytest>=9.0.3", + "pytest-cov>=7.1.0", "ruff>=0.15.16", ] [project.urls] -Source = "http://github.com/fsspec/gdrive-fsspec" +Source = "https://github.com/marimo-team/gdrive-fsspec" +Contributing = "https://github.com/marimo-team/gdrive-fsspec/blob/main/CONTRIBUTING.md" [tool.setuptools_scm] version_file = "src/gdrive_fsspec/_version.py" @@ -52,3 +57,23 @@ addopts = """\ markers = [ "integration: marks test as integration test consuming external resources (select with '-m integration')", ] + +[tool.ruff.lint] +extend-select = ["I", "B"] + +[tool.pyrefly] +preset = "strict" +project-includes = ["**/*.py*"] +search-path = ["tests"] + +[tool.pyrefly.errors] +unannotated-return = "error" +unannotated-parameter = "error" + +[tool.coverage.run] +source_pkgs = ["gdrive_fsspec"] +omit = ["*/_version.py"] + +[tool.coverage.report] +show_missing = true +fail_under = 95 diff --git a/src/gdrive_fsspec/core.py b/src/gdrive_fsspec/core.py index 234dd54..aa110bf 100644 --- a/src/gdrive_fsspec/core.py +++ b/src/gdrive_fsspec/core.py @@ -1,132 +1,297 @@ -from functools import cached_property +from __future__ import annotations + +import io import json import logging import os -import re +import pathlib +import warnings +from functools import cached_property +from typing import TYPE_CHECKING, Any, Literal, Mapping, TypeAlias, cast, overload +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit -from fsspec.spec import AbstractFileSystem, AbstractBufferedFile +import httplib2 +from fsspec.spec import AbstractBufferedFile, AbstractFileSystem +from google.auth.credentials import AnonymousCredentials, Credentials +from google.oauth2 import service_account +from google_auth_httplib2 import AuthorizedHttp from googleapiclient.discovery import build from googleapiclient.errors import HttpError -from google.auth.credentials import AnonymousCredentials -from google.oauth2 import service_account +from googleapiclient.http import MediaIoBaseDownload, build_http + +from .types import FileInfo +from .typing_utils import override +from .utils import merge_fields + +if TYPE_CHECKING: + from googleapiclient._apis.drive.v3.resources import DriveResource + from googleapiclient._apis.drive.v3.schemas import Drive, File + from .types import FilesResource -logger = logging.getLogger("gdrive_fsspec") -scope_dict = { +DEFAULT_BLOCK_SIZE = 5 * 2**20 +LOGGER = logging.getLogger("gdrive_fsspec") + +# https://developers.google.com/workspace/drive/api/guides/api-specific-auth +SCOPE_DICT = { "full_control": "https://www.googleapis.com/auth/drive", "read_only": "https://www.googleapis.com/auth/drive.readonly", } +# https://developers.google.com/workspace/drive/api/guides/mime-types DIR_MIME_TYPE = "application/vnd.google-apps.folder" -fields = ",".join( - [ - "name", - "id", - "size", - "trashed", - "mimeType", - "version", - "createdTime", - "modifiedTime", - ] + +# Base URL for resumable uploads. +UPLOAD_URL = "https://www.googleapis.com/upload/drive/v3/files" + +# File resource fields; partial-response mask for files.list / files.get: +# https://developers.google.com/workspace/drive/api/reference/rest/v3/files#resource +# https://developers.google.com/workspace/drive/api/guides/performance#partial +_BASE_FIELDS = [ + "name", + "id", + "size", + "trashed", + "mimeType", + "version", + "createdTime", + "modifiedTime", +] +INFO_FIELDS = ",".join(_BASE_FIELDS) + +# Shared-drive role docs, surfaced in permission errors on delete/trash. +_SHARED_DRIVE_ROLES_URL = "https://support.google.com/a/answer/7337554" +# https://developers.google.com/workspace/drive/api/guides/delete#permissions for more info. + +_TRASH_PERMISSION_MSG = "Insufficient permissions to move the file into Trash." +_TRASH_PERMISSION_SHARED_DRIVE_MSG = ( + "Insufficient permissions to move the file into Trash. Shared drives require " + f"Content manager or Manager access. See {_SHARED_DRIVE_ROLES_URL}" ) +_DELETE_PERMISSION_SHARED_DRIVE_MSG = ( + "Insufficient permissions to permanently delete the file. Shared drives require " + f"Manager access. See {_SHARED_DRIVE_ROLES_URL}" +) +_DELETE_PERMISSION_MSG = "Insufficient permissions to permanently delete the file." + +_NUM_RETRIES = 5 -def _normalize_path(prefix, name): +def _normalize_path(prefix: str, name: str) -> str: raw_prefix = prefix.strip("/") return "/" + "/".join([raw_prefix, name]) -def _finfo_from_response(f, path_prefix=None): +def _with_supports_all_drives(url: str) -> str: + """Return ``url`` with ``supportsAllDrives=true`` set, overriding any value. + + The resumable session URI is opaque and may already carry query parameters + (``upload_id``, ``session_crd``). Setting the parameter via the query parser + forces ``true`` even if the URL somehow already had ``supportsAllDrives=false``. + """ + parts = urlsplit(url) + query = dict(parse_qsl(parts.query, keep_blank_values=True)) + query["supportsAllDrives"] = "true" + return urlunsplit(parts._replace(query=urlencode(query))) + + +def _parse_range_end(range_header: str | None) -> int | None: + """Last stored byte index from a resumable ``Range`` header. + + Resumable uploads report stored bytes as ``bytes=0-`` (the optional + ``bytes=`` unit is tolerated). Only ranges starting at ``0`` are accepted β€” + anything else (a non-zero start, missing dash, or non-integer end) returns + ``None``, since ``_consume_accepted`` assumes the range covers from the + start of the object and a malformed value would miscount accepted bytes. + """ + if not range_header: + return None + spec = range_header.strip().removeprefix("bytes=") + start, sep, end = spec.partition("-") + if not sep or start != "0": + return None + try: + return int(end) + except ValueError: + return None + + +def _finfo_from_response( + file: File | Mapping[str, Any], path_prefix: str | None = None +) -> FileInfo: # strictly speaking, other types might be capable of having children, # such as packages # TODO: check specifically for links - ftype = "directory" if f.get("mimeType") == DIR_MIME_TYPE else "file" + file_type = "directory" if file.get("mimeType") == DIR_MIME_TYPE else "file" if path_prefix: - name = _normalize_path(path_prefix, f["name"]) + name = _normalize_path(path_prefix, file["name"]) else: - name = f["name"] - info = {"name": name.lstrip("/"), "size": int(f.get("size", 0)), "type": ftype} - f.update(info) - return f + name = file["name"] + info: FileInfo = { + "name": name.lstrip("/"), + "size": int(file.get("size", 0)), + "type": file_type, + } + return cast(FileInfo, {**file, **info}) class MultipleFilesError(FileNotFoundError): pass +AuthMethod = Literal["anon", "browser", "cache", "service_account"] +ROOT_ID = "root" + +# One path element β€” matches fsspec.stringify_path +PathLike: TypeAlias = str | os.PathLike[str] | pathlib.Path + + class GoogleDriveFileSystem(AbstractFileSystem): - """ - Access to google-drive as a file-system + """Access Google Drive as a file system. + + In the Google Drive API, everything is a file resource. Folders are files + with a special MIME type. - Limitations: - - we assume that each path identifies a unique file. In gdrive, it is - possible to have multiple identically named files, and this will - result in errors in this implementation. + Note: + We assume that each path identifies a unique file. In Google Drive, it + is possible to have multiple identically named files, and this will + result in errors in this implementation. """ protocol = "gdrive" root_marker = "" + if TYPE_CHECKING: + service: DriveResource + files: FilesResource + authed_http: AuthorizedHttp + def __init__( self, - root_file_id=None, - token="cache", - access="full_control", - spaces="drive", - creds=None, - drive=None, - auth_kwargs=None, - **kwargs, - ): - """ - :param root_file_id: str or None - If you have a share, drive or folder ID to treat as the FS root, enter - it here. Otherwise, you will get your default drive - :param token: str - One of "anon", "browser", "cache", "service_account". Using "browser" will prompt a URL to - be put in a browser, and cache the response for future use with token="cache". - "browser" will remove any previously cached token file, if it exists. - :param access: str - One of "full_control", "read_only" - :param spaces: - Category of files to search; can be 'drive', 'appDataFolder' and 'photos'. - Of these, only the first is general - :param creds: None or dict - Required just for "service_account" token, a dict containing the service account - credentials obtained in GCP console. The dict content is the same as the json file - downloaded from GCP console. More details can be found here: - https://cloud.google.com/iam/docs/service-account-creds#key-types - This credential can be useful when integrating with other GCP services, and when you - don't want the user to be prompted to authenticate. - The files need to be shared with the service account email address, that can be found - in the json file. - :param auth_kwargs: dict - Additional keyword arguments passed to the authentication backend - (``pydata_google_auth.get_user_credentials`` for user OAuth, or - ``service_account.Credentials.from_service_account_info`` for service - accounts). For headless or remote environments where a local callback - server is unavailable, pass ``use_local_webserver=False`` to request a - token via the console. - :param kwargs: - Passed to parent + root_file_id: str | None = None, + token: AuthMethod = "cache", + access: Literal["full_control", "read_only"] = "full_control", + spaces: str = "drive", + creds: dict[str, Any] | str | None = None, + drive: str | None = None, + auth_kwargs: dict[str, Any] | None = None, + **kwargs: Any, + ) -> None: + """Initialize a Google Drive file system. + + Args: + root_file_id: Folder file ID to use as the filesystem root (the empty + path ``""``). Obtain it from a folder URL such as + ``https://drive.google.com/drive/folders/``. If omitted, + defaults to the shared-drive root when ``drive`` is set, otherwise + ``"root"`` (the authenticated user's My Drive). A shared-drive ID + is also accepted here for backwards compatibility (when it cannot + be resolved as a file, it is treated as a shared drive and + ``drive`` is set from it), but this is a legacy path; prefer + passing ``drive`` to target a shared drive. + token: One of ``"anon"``, ``"browser"``, ``"cache"``, + ``"service_account"``. Using ``"browser"`` will prompt a URL to + be opened in a browser and cache the response for future use with + ``token="cache"``. ``"browser"`` removes any previously cached + token file, if it exists. + access: One of ``"full_control"``, ``"read_only"``. + spaces: Category of files to search; can be ``"drive"``, + ``"appDataFolder"``, and ``"photos"``. Of these, only the first + is general. + creds: Required for ``"service_account"`` token. A dict with the + service account credentials from the GCP console (same content + as the downloaded JSON). See + https://cloud.google.com/iam/docs/service-account-creds#key-types. + Files must be shared with the service account email from that JSON. + drive: A shared drive to scope API calls to, given as either its ID + or its name. Resolved against the drives accessible to the current + credentials (via ``drives.list``). Required for service-account + uploads. If omitted, operations use the user's My Drive (or + anonymous public files when ``token="anon"``). Combine with + ``root_file_id`` to start below the shared-drive root, e.g. a + subfolder ID inside that drive. + auth_kwargs: Additional keyword arguments passed to the authentication + backend (``pydata_google_auth.get_user_credentials`` for user + OAuth, or + ``service_account.Credentials.from_service_account_info`` for + service accounts). For headless or remote environments where a + local callback server is unavailable, pass + ``use_local_webserver=False`` to request a token via the console. + **kwargs: Passed to the parent class. """ + # Ideally, these should be keyword-arguments, but to maintain backwards compatibility, we keep the existing API. + super().__init__(**kwargs) self.access = access - self.scopes = [scope_dict[access]] + self.scopes = [SCOPE_DICT[access]] self.spaces = spaces self.creds = creds + self.drive = drive self.auth_kwargs = auth_kwargs or {} self.connect(method=token) if token == "anon": self.drive = None elif drive: - self.drive = self._drive_id_from_name(drive) - else: - self.drive = drive - self.root_file_id = root_file_id or self.drive or "root" + self.drive = self._resolve_drive_id(drive) + + if root_file_id and root_file_id != ROOT_ID: + self._validate_root_file_id(root_file_id) + + self.root_file_id = root_file_id or self.drive or ROOT_ID + + def _validate_root_file_id(self, root_file_id: str) -> None: + try: + meta = self.files.get( + fileId=root_file_id, + fields="id,trashed,mimeType,driveId", + supportsAllDrives=True, + ).execute(num_retries=_NUM_RETRIES) + except HttpError as err: + if err.status_code != 404: + raise + self._confirm_shared_drive_root(root_file_id) + return - def connect(self, method=None): + if meta.get("trashed"): + raise FileNotFoundError(f"root_file_id {root_file_id!r} is trashed") + if meta.get("mimeType") != DIR_MIME_TYPE: + raise NotADirectoryError(f"root_file_id {root_file_id!r} is not a folder") + # Check if the root file is in the correct drive. + if self.drive is not None and meta.get("driveId") != self.drive: + raise ValueError( + f"root_file_id {root_file_id!r} is not in drive {self.drive!r}" + ) + + def _confirm_shared_drive_root(self, drive_id: str) -> None: + """Accept a shared-drive ID passed as ``root_file_id`` (legacy). + + Older versions documented ``root_file_id`` as accepting a "share, drive or + folder ID", so a shared-drive ID may be passed here. When the ID does not + resolve as a file, fall back to treating it as a shared drive and set + ``self.drive`` from it so directory listings are scoped correctly. + + Args: + drive_id: Shared-drive ID to validate. + + Note: + Prefer passing ``drive`` instead of using this legacy path. + """ + try: + self.service.drives().get(driveId=drive_id).execute( + num_retries=_NUM_RETRIES + ) + except HttpError as err: + if err.status_code == 404: + raise FileNotFoundError(f"root_file_id {drive_id!r} not found") from err + raise + if self.drive is None: + self.drive = drive_id + elif self.drive != drive_id: + raise ValueError( + f"root_file_id {drive_id!r} conflicts with drive {self.drive!r}" + ) + + def connect(self, method: AuthMethod | None = None) -> None: if method == "browser": cred = self._connect_browser() elif method == "cache": @@ -137,30 +302,49 @@ def connect(self, method=None): cred = self._connect_service_account() else: raise ValueError(f"Invalid connection method `{method}`.") - srv = build("drive", "v3", credentials=cred) - self.srv = srv - self.files = srv.files() + + # Own the authenticated transport explicitly. Sharing the transport + # keeps credential refresh and connection state in one place. + self.authed_http = AuthorizedHttp( + cred, http=build_http() + ) # TODO: should we make this private? + + # AuthorizedHttp duck-types as httplib2.Http (this is exactly what + # googleapiclient passes internally), but the stubs only accept Http. + # pyrefly: ignore [no-matching-overload] + self.service = build("drive", "v3", http=self.authed_http) + self.files = self.service.files() @property - def _user_credentials_cache_path(self): - import pydata_google_auth + def srv(self) -> DriveResource: + """Deprecated alias for :attr:`service`.""" + warnings.warn( + "`srv` is deprecated; use `service` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.service + + @property + def _user_credentials_cache_path(self) -> str: + import pydata_google_auth.cache return pydata_google_auth.cache.READ_WRITE._path - def _connect_browser(self): + def _connect_browser(self) -> Credentials: try: os.remove(self._user_credentials_cache_path) except OSError: pass return self._connect_cache() - def _connect_cache(self): + def _connect_cache(self) -> Credentials: import pydata_google_auth kwargs = {"use_local_webserver": True, **self.auth_kwargs} return pydata_google_auth.get_user_credentials(self.scopes, **kwargs) - def _connect_service_account(self): + def _connect_service_account(self) -> Credentials: if isinstance(self.creds, str): if not self.creds.strip(): raise ValueError("Empty credentials are not allowed") @@ -175,39 +359,122 @@ def _connect_service_account(self): ) @cached_property - def drives(self): - """Drives accessible to the current user""" - out = [] - page_token = None + def drives(self) -> list[Drive]: + """Shared drives accessible to the current user. + + drives.list only returns shared drives + https://developers.google.com/workspace/drive/api/reference/rest/v3/drives/list + + Returns: + List of drive resource dicts from the Drive API. + """ + drives: list[Drive] = [] + page_token: str | None = None while True: - ret = self.srv.drives().list(pageToken=page_token).execute() - out.extend(ret["drives"]) - page_token = ret.get("nextPageToken") + if page_token is None: + response = ( + self.service.drives().list().execute(num_retries=_NUM_RETRIES) + ) + else: + response = ( + self.service.drives() + .list(pageToken=page_token) + .execute(num_retries=_NUM_RETRIES) + ) + drives.extend(response["drives"]) + page_token = response.get("nextPageToken") if page_token is None: break - return out + return drives + + @cached_property + def export_formats(self) -> dict[str, list[str]]: + """Supported export conversions, keyed by source MIME type. - def mkdir(self, path, create_parents=True, **kwargs): - if create_parents and self._parent(path): - self.makedirs(self._parent(path), exist_ok=True) - par = self._parent(path) - parent_id = self.info(par)["id"] + Maps each Google-native MIME type (e.g. + ``application/vnd.google-apps.document``) to the list of target MIME + types it can be exported to. Fetched once from the Drive ``about`` + resource and cached for the lifetime of the filesystem. + + Returns: + Mapping of source MIME type to its list of valid export targets. + """ + about = ( + self.service.about() + .get(fields="exportFormats") + .execute(num_retries=_NUM_RETRIES) + ) + return about.get("exportFormats", {}) + + def _path_str(self, path: PathLike) -> str: + """Strip the protocol and normalize a path-like input to a single string. + + Args: + path: A ``str``, ``os.PathLike``, or ``pathlib.Path``. + + Returns: + The protocol-stripped path as a string. + + Raises: + TypeError: If ``path`` resolves to a sequence of paths. + """ + stripped = self._strip_protocol(path) + if isinstance(stripped, list): + raise TypeError("expected a single path, not a sequence of paths") + return stripped + + # Return type is Any (not drive.v3 File) to match fsspec AbstractFileSystem.mkdir. + @override + def mkdir(self, path: PathLike, create_parents: bool = True, **kwargs: Any) -> Any: + """Create a directory at the given path. + + Args: + path: Directory path to create. + create_parents: If True, create any missing parent directories first. + **kwargs: Ignored; accepted for fsspec compatibility. + + Returns: + The created folder's file resource dict from the Drive API (drive.v3 + ``File`` at runtime). + + Raises: + FileExistsError: If a file or folder already exists at ``path``. + """ + parent = self._parent(path) + if create_parents and parent: + self.makedirs(parent, exist_ok=True) + + stripped_path = self._path_str(path) + if self.exists(stripped_path): + raise FileExistsError(stripped_path) + + parent_id = self._path_to_id(parent) meta = { - "name": path.rstrip("/").rsplit("/", 1)[-1], + "name": stripped_path.rstrip("/").rsplit("/", 1)[-1], "mimeType": DIR_MIME_TYPE, "parents": [parent_id], } - if self.exists(path): - raise FileExistsError(path) - logger.debug(f"Creating {path}, child of {parent_id}") - out = self.files.create(body=meta, supportsAllDrives=True).execute() - if par in self.dircache: - self.dircache[par].append(_finfo_from_response(out, path_prefix=par)) - self.dircache[path] = [] + LOGGER.debug(f"Creating {stripped_path}, child of {parent_id}") + out: File = self.files.create(body=meta, supportsAllDrives=True).execute( + num_retries=_NUM_RETRIES + ) + if parent in self.dircache: + self.dircache[parent].append(_finfo_from_response(out, path_prefix=parent)) + self.dircache[stripped_path] = [] return out - def makedirs(self, path, exist_ok=True): - parts = path.split("/") + @override + def makedirs(self, path: PathLike, exist_ok: bool = True) -> None: + """Create a directory and any missing parent directories. + + Args: + path: Directory path to create (may include nested components). + exist_ok: If False, raise when the final path component already exists. + + Raises: + FileExistsError: If ``exist_ok`` is False and the directory already exists. + """ + parts = self._path_str(path).split("/") path = "" for i, part in enumerate(parts): path = path + "/" + part if path else part @@ -216,107 +483,391 @@ def makedirs(self, path, exist_ok=True): elif i == len(parts) - 1 and not exist_ok: raise FileExistsError(path) - def rm_file(self, path, file_id=None): - file_id = file_id or self.info(path)["id"] - logger.debug(f"Removing {path}, file_id={file_id}") - self.files.delete(fileId=file_id, supportsAllDrives=True).execute() - par = self._parent(path) - if par in self.dircache: - listing = self.dircache[par] - i = [i for i, li in enumerate(listing) if li["name"] == path][0] - listing.pop(i) - self.dircache.pop(path, None) - - def rm(self, path, recursive=True, maxdepth=None): + # fsspec's base rm_file delegates to _rm; we implement delete here so both + # rm_file and rm share the same Drive trash/permanent behavior. + @override + def _rm(self, path: PathLike, permanent: bool = False) -> None: + """Delete a single file or directory by path. + + Args: + path: Path of the file or folder to delete. + permanent: If True, permanently delete the file instead of moving to trash. + """ + stripped_path = self._path_str(path) + if stripped_path == "": + raise ValueError("Cannot delete the filesystem root") + file_info = self.info( + stripped_path, fields="driveId,capabilities/canDelete,capabilities/canTrash" + ) + file_id = file_info["id"] + LOGGER.debug(f"Removing {stripped_path}, file_id={file_id}") + + on_shared_drive = bool(file_info.get("driveId")) + + # Sometimes, the file exists but delete reports a 404 error. + # This is due to a permission issue rather than a file not found error. + # https://github.com/marimo-team/gdrive-fsspec/issues/19 + # So we check whether we can delete it first. + if permanent: + can_delete = file_info.get("capabilities", {}).get("canDelete", False) + if not can_delete and on_shared_drive: + raise PermissionError(_DELETE_PERMISSION_SHARED_DRIVE_MSG) + elif not can_delete: + raise PermissionError(_DELETE_PERMISSION_MSG) + self.files.delete(fileId=file_id, supportsAllDrives=True).execute( + num_retries=_NUM_RETRIES + ) + else: + can_trash = file_info.get("capabilities", {}).get("canTrash", False) + if not can_trash and on_shared_drive: + raise PermissionError(_TRASH_PERMISSION_SHARED_DRIVE_MSG) + elif not can_trash: + raise PermissionError(_TRASH_PERMISSION_MSG) + self._trash_file(file_id) + + parent = self._parent(stripped_path) + if parent in self.dircache: + listing = self.dircache[parent] + self.dircache[parent] = [ + li for li in listing if li["name"] != stripped_path + ] + + # Drop any cached listing rooted at the deleted path (it was a directory). + self.dircache.pop(stripped_path, None) + + @override + def rm( + self, + path: PathLike, + recursive: bool = True, + maxdepth: int | None = None, + permanent: bool = False, + ) -> None: + """Delete a file or directory. + + By default the file is moved to the trash, matching the Google Drive UI + (and recoverable from there). Pass ``permanent=True`` to hard-delete. + + Args: + path: Path of the file or folder to delete. + recursive: If False, refuse to delete a non-empty directory. + maxdepth: Ignored; accepted for fsspec compatibility. + permanent: If True, permanently delete instead of moving to trash. + This is irreversible, refer to https://developers.google.com/workspace/drive/api/guides/delete#permissions for permissions. + + Raises: + ValueError: If ``recursive`` is False and the directory is not empty. + """ if recursive is False and self.isdir(path) and self.ls(path): raise ValueError("Attempt to delete non-empty folder") - self.rm_file(path) + self._rm(path, permanent=permanent) + + @override + def rmdir(self, path: PathLike, permanent: bool = False) -> None: + """Remove an empty directory. - def rmdir(self, path): + Args: + path: Path of the directory to remove. + permanent: If True, permanently delete instead of moving to trash. + + Raises: + ValueError: If ``path`` is not a directory or is not empty. + """ if not self.isdir(path): raise ValueError("Path is not a directory") - self.rm(path, recursive=False) + self.rm(path, recursive=False, permanent=permanent) - def invalidate_cache(self, path=None): + @override + def invalidate_cache(self, path: PathLike | None = None) -> None: if path is None: self.dircache.clear() else: self.dircache.pop(self._strip_protocol(path), None) super().invalidate_cache(path) - def export(self, path, mime_type): - """Convert a google-native file to another format and download + def export(self, path: PathLike, mime_type: str) -> bytes: + """Export a Google-native file to another format and download it. + + Use this for Docs, Sheets, Slides, and other Google Workspace files that + cannot be downloaded directly with ``open(..., "rb")``. - mime_type is something like "text/plain" + Args: + path: Path of the Google-native file to export. + mime_type: Target MIME type for the export (e.g. ``"text/plain"``). + Must be one of the conversions Drive supports for this file's + type; see :attr:`export_formats`. + + Returns: + Exported file content as bytes. + + Raises: + ValueError: If ``mime_type`` is not a supported export target for + this file's source type. """ - file_id = self.path_to_file_id(path) - return self.files.export( - fileId=file_id, mimeType=mime_type, supportsAllDrives=True - ).execute() - - def _drive_id_from_name(self, name): - drive = [_["id"] for _ in self.drives if _["name"] == name] - if len(drive) == 0: - raise ValueError(f"Drive name {drive} not found") - elif len(drive) == 1: - return drive[0] - else: - raise ValueError(f"Drive name {drive} refers to multiple shared drives") - - def ls(self, path, detail=False, trashed=False): - path = self._strip_protocol(path) - files = self._ls_from_cache(path) - - if files is None: - # get parent ID - if "/" in path: - pref = path.rsplit("/", 1)[0] - inf = self.info(pref, trashed=trashed) - file_id = inf["id"] - else: - pref = "" - file_id = self.root_file_id + info = self.info(path) + file_id = info["id"] + source_mime = info.get("mimeType", "") + targets = self.export_formats.get(source_mime, []) + if mime_type not in targets: + valid = ", ".join(targets) if targets else "none" + raise ValueError( + f"Cannot export {path!r} (type {source_mime!r}) to {mime_type!r}. Supported export types: {valid}." + ) - # list parent - files = self._list_directory_by_id( - file_id, trashed=trashed, path_prefix=pref + request = self.files.export_media(fileId=file_id, mimeType=mime_type) + buffer = io.BytesIO() + downloader = MediaIoBaseDownload(buffer, request) + done = False + while not done: + _, done = downloader.next_chunk(num_retries=_NUM_RETRIES) + return buffer.getvalue() + + def _resolve_drive_id(self, drive: str) -> str: + """Resolve a shared-drive ID or name to its drive ID. + + Args: + drive: Shared-drive ID or human-readable name. + + Returns: + The matching shared-drive ID. + + Raises: + ValueError: If no drive matches, or the name matches multiple drives. + """ + if any(d["id"] == drive for d in self.drives): + return drive + matches = [d["id"] for d in self.drives if d["name"] == drive] + if len(matches) == 1: + return matches[0] + if len(matches) == 0: + raise ValueError(f"Drive {drive!r} not found by id or name") + raise ValueError(f"Drive name {drive!r} refers to multiple shared drives") + + @overload + # pyrefly: ignore [bad-override] # overloads diverge from base ls signature + def ls( + self, + path: PathLike, + detail: Literal[False] = False, + trashed: bool = False, + **kwargs: Any, + ) -> list[str]: ... + + @overload + def ls( + self, + path: PathLike, + detail: Literal[True], + trashed: bool = False, + fields: str | None = None, + **kwargs: Any, + ) -> list[FileInfo]: ... + + @override + def ls( + self, + path: PathLike, + detail: bool = False, + trashed: bool = False, + fields: str | None = None, + **kwargs: Any, + ) -> list[str] | list[FileInfo]: + """List files and directories under ``path``. + + Args: + path: Directory path to list. Use ``""`` for the filesystem root. + detail: If True, return full file-info dicts; otherwise return paths only. + trashed: If True, include trashed items in the listing. + fields: Extra Drive fields to request on top of the defaults, as a + comma-separated string (e.g. ``"driveId,capabilities/canDelete"``). + See https://developers.google.com/workspace/drive/api/reference/rest/v3/files#resource. + kwargs: Not used; accepted for fsspec compatibility. + + Returns: + Sorted list of child paths, or list of file-info dicts when ``detail`` + is True. + + Raises: + ValueError: If ``fields`` is given while ``detail`` is False, since the + names-only result would discard the requested fields. + FileNotFoundError: If ``path`` does not exist. + MultipleFilesError: If multiple files share the same path name. + """ + # A blank mask means "no extra fields". + fields = (fields or "").strip() or None + if fields is not None and not detail: + raise ValueError( + "fields requires detail=True; names-only output discards the requested fields" + ) + + stripped_path: str = self._path_str(path) + + # We only check the cache for typical API calls, we avoid caching if user passes extra fields or trashed files. + use_cache = fields is None and not trashed + + if use_cache and (cached := self.dircache.get(stripped_path)) is not None: + files: list[FileInfo] = cached + else: + files = self._ls_uncached( + stripped_path, trashed=trashed, fields=fields, cache_results=use_cache ) - if files: - self.dircache[pref] = files - else: - raise FileNotFoundError(path) - - if path: - # else we listed the top-level and are done - this_file = [f for f in files if f["name"] == path] - if len(this_file) == 0: - raise FileNotFoundError(path) - elif len(this_file) > 1: - raise MultipleFilesError(path) - if this_file[0]["type"] == "directory": - files = self._list_directory_by_id( - this_file[0]["id"], trashed=trashed, path_prefix=path - ) - self.dircache[path] = files if detail: return files else: - return sorted([f["name"] for f in files]) + return sorted([file["name"] for file in files]) + + def _ls_uncached( + self, + stripped_path: str, + *, + trashed: bool = False, + fields: str | None = None, + cache_results: bool = True, + ) -> list[FileInfo]: + """List a path's contents from the API, populating the dircache. + + Args: + stripped_path: The path to list. + trashed: If True, include trashed items in the listing. + fields: Extra Drive fields to request on top of the defaults. + cache_results: If True, set the cache for the listing. + """ + if stripped_path == "": + # Empty path is the root directory. + files = self._list_directory_by_id( + self.root_file_id, trashed=trashed, path_prefix="", fields=fields + ) + if cache_results: + self.dircache[stripped_path] = files + return files + + parent = self._parent(stripped_path) + siblings = self.ls(parent, detail=True, trashed=trashed, fields=fields) + matches = [file for file in siblings if file["name"] == stripped_path] + + if len(matches) == 0: + raise FileNotFoundError(stripped_path) + if len(matches) > 1: + raise MultipleFilesError(stripped_path) + + entry = matches[0] + if entry["type"] != "directory": + # `ls` on a file returns the file's own info, and is not a directory + # so we don't cache it under the file path + return [entry] + + files = self._list_directory_by_id( + entry["id"], trashed=trashed, path_prefix=stripped_path, fields=fields + ) + if cache_results: + self.dircache[stripped_path] = files + return files - def info(self, path, trashed=False): - path = self._strip_protocol(path) - if path == "": - return { - "name": path, + @override + def info( + self, + path: PathLike, + trashed: bool = False, + fields: str | None = None, + **kwargs: Any, + ) -> dict[str, Any]: + """Return metadata for a file or directory. + + Args: + path: Path to inspect. Use ``""`` for the filesystem root. + trashed: If True, allow resolving trashed files. + fields: Extra Drive fields to request on top of the defaults, as a + comma-separated string (e.g. ``"driveId,capabilities/canDelete"``). + See https://developers.google.com/workspace/drive/api/reference/rest/v3/files#resource. + kwargs: Additional arguments to pass to the ``files.get`` request. + + Returns: + File-info dict including ``name``, ``type``, ``size``, and Drive API fields. + """ + stripped_path = self._path_str(path) + if stripped_path == "": + info: FileInfo = { + "name": stripped_path, "mimeType": DIR_MIME_TYPE, "type": "directory", "size": 0, "id": self.root_file_id, } - return super().info(path, trashed=trashed) + return cast(dict[str, Any], info) + + # A blank mask means "no extra fields". + fields = (fields or "").strip() or None + + # info_by_id fetches fresh data, but involves an extra API call. + # resolve_entry uses the cache, but doesn't fetch extra fields. + if fields is None: + file_info = self._resolve_entry(stripped_path, trashed=trashed) + else: + file_info = self._info_by_id( + stripped_path, fields, trashed=trashed, **kwargs + ) + return cast(dict[str, Any], file_info) + + def _info_by_id( + self, stripped_path: str, fields: str, *, trashed: bool = False, **kwargs: Any + ) -> FileInfo: + """Return a path's info via ``files.get`` by id, with extra ``fields``. + + ``files.get`` is O(1) in directory size and bypasses the listing cache, + so the extra fields are always fresh β€” unlike enriching the whole parent + listing, which scales with the number of siblings. + """ + entry = self._resolve_entry(stripped_path, trashed=trashed) + for reserved in ("fileId", "fields", "supportsAllDrives"): + kwargs.pop(reserved, None) + + meta = self.files.get( + fileId=entry["id"], + fields=merge_fields(INFO_FIELDS, fields), + supportsAllDrives=True, + **kwargs, + ).execute(num_retries=_NUM_RETRIES) + parent = self._parent(stripped_path) + return _finfo_from_response(meta, path_prefix=parent) - def _drive_kw(self): + def _resolve_entry(self, path: PathLike, *, trashed: bool = False) -> FileInfo: + """Resolve a path to its own FileInfo by matching it in its parent listing. + + Args: + path: Path to resolve. + trashed: If True, allow resolving trashed files. + + Returns: + The FileInfo for the resolved path. + + Raises: + ValueError: If called with the root path, which has no parent to + list β€” callers must handle the root themselves. + FileNotFoundError: If ``path`` does not exist. + MultipleFilesError: If multiple files share the same path name. + """ + stripped_path = self._path_str(path) + if stripped_path == "": + raise ValueError("_resolve_entry is not defined for the root path") + parent = self._parent(stripped_path) + matches = [ + file + for file in self.ls(parent, detail=True, trashed=trashed) + if file["name"] == stripped_path + ] + if len(matches) == 0: + raise FileNotFoundError(stripped_path) + if len(matches) > 1: + raise MultipleFilesError(stripped_path) + return matches[0] + + def _path_to_id(self, path: PathLike, trashed: bool = False) -> str: + if self._path_str(path) == "": + return self.root_file_id + return self._resolve_entry(path, trashed=trashed)["id"] + + def _drive_kw(self) -> dict[str, Any]: if self.drive is not None: return dict( includeItemsFromAllDrives=True, @@ -325,13 +876,23 @@ def _drive_kw(self): driveId=self.drive, ) else: - return {} + empty: dict[str, Any] = {} + return empty - def _list_directory_by_id(self, file_id, trashed=False, path_prefix=None): - all_files = [] - page_token = None - afields = "nextPageToken, files(%s)" % fields - if file_id == "root" and self.drive is not None: + def _list_directory_by_id( + self, + file_id: str, + trashed: bool = False, + path_prefix: str | None = None, + fields: str | None = None, + ) -> list[FileInfo]: + all_files: list[FileInfo] = [] + page_token: str | None = None + + file_fields = merge_fields(INFO_FIELDS, fields) + all_fields = f"nextPageToken, files({file_fields})" + + if file_id == ROOT_ID and self.drive is not None: query = f"'{self.drive}' in parents " else: query = f"'{file_id}' in parents " @@ -339,64 +900,143 @@ def _list_directory_by_id(self, file_id, trashed=False, path_prefix=None): query += "and trashed = false " kwargs = self._drive_kw() while True: - logger.debug("%s ; prefix %s", query, path_prefix) - response = self.files.list( - q=query, - spaces=self.spaces, - fields=afields, - pageToken=page_token, - orderBy="name", - pageSize=1000, - **kwargs, - ).execute() - for f in response.get("files", []): - all_files.append(_finfo_from_response(f, path_prefix)) + LOGGER.debug("%s ; prefix %s", query, path_prefix) + if page_token is None: + response = self.files.list( + q=query, + spaces=self.spaces, + fields=all_fields, + orderBy="name", + pageSize=1000, + **kwargs, + ).execute(num_retries=_NUM_RETRIES) + else: + response = self.files.list( + q=query, + spaces=self.spaces, + fields=all_fields, + pageToken=page_token, + orderBy="name", + pageSize=1000, + **kwargs, + ).execute(num_retries=_NUM_RETRIES) + for file in response.get("files", []): + all_files.append(_finfo_from_response(file, path_prefix)) page_token = response.get("nextPageToken", None) if page_token is None: break return all_files - def _open(self, path, mode="rb", **kwargs): - return GoogleDriveFile(self, path, mode=mode, **kwargs) + def _trash_file(self, file_id: str, untrash: bool = False) -> File: + """Trash or untrash a file. + Args: + file_id: The ID of the file to trash or untrash. + untrash: If True, untrash the file. + """ + response = self.files.update( + fileId=file_id, + body={"trashed": not untrash}, + supportsAllDrives=True, + ).execute(num_retries=_NUM_RETRIES) + return response -DEFAULT_BLOCK_SIZE = 5 * 2**20 + @override + def _open( + self, + path: PathLike, + mode: str = "rb", + block_size: int | None = None, + autocommit: bool = True, + cache_options: dict[str, Any] | None = None, + **kwargs: Any, + ) -> AbstractBufferedFile: + """Open a file on Google Drive, returning a buffered file object. + + Args: + path: Path of the file to open. + mode: File mode; only ``"rb"`` and ``"wb"`` are supported. + block_size: Buffer size in bytes; defaults to ``DEFAULT_BLOCK_SIZE``. + autocommit: If True, commit the upload when the file is closed. + cache_options: Options forwarded to the read-ahead cache. + **kwargs: Passed to :class:`GoogleDriveFile`. + + Returns: + A :class:`GoogleDriveFile` open in the requested mode. + """ + return GoogleDriveFile( + self, + path, + mode=mode, + block_size=block_size if block_size is not None else DEFAULT_BLOCK_SIZE, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) class GoogleDriveFile(AbstractBufferedFile): def __init__( self, - fs, - path, - mode="rb", - block_size=DEFAULT_BLOCK_SIZE, - autocommit=True, - **kwargs, - ): - """ - Open a file. - - Parameters - ---------- - fs: instance of GoogleDriveFileSystem - mode: str - Normal file modes. Currently only 'wb' amd 'rb'. - block_size: int - Buffer size for reading or writing (default 5MB) + fs: GoogleDriveFileSystem, + path: PathLike, + mode: str = "rb", + block_size: int = DEFAULT_BLOCK_SIZE, + autocommit: bool = True, + **kwargs: Any, + ) -> None: + """Open a file on Google Drive for reading or writing. + + Args: + fs: GoogleDriveFileSystem instance. + path: File path to open. + mode: File mode; currently only ``"rb"`` and ``"wb"`` are supported. + block_size: Buffer size for reading or writing (default 5 MiB). + autocommit: If True, commit the upload when the file is closed. + **kwargs: Passed to :class:`AbstractBufferedFile`. + + Raises: + IsADirectoryError: If ``mode`` is ``"wb"`` and ``path`` is an + existing directory. + MultipleFilesError: If ``path`` already resolves to multiple files. """ + path = fs._path_str(path) + + existing_id: str | None = None + if mode == "wb": + # If the path already exists, remember its id so the upload PATCHes + # the existing file instead of creating an identically-named + # duplicate. + try: + existing: FileInfo = cast(FileInfo, fs.info(path)) + except MultipleFilesError: + raise + except FileNotFoundError: + pass + else: + if existing["type"] == "directory": + raise IsADirectoryError(path) + existing_id = existing["id"] + super().__init__(fs, path, mode, block_size, autocommit=autocommit, **kwargs) if mode == "wb": self.location = None + self.file_id: str | None = existing_id else: - self.file_id = fs.info(path)["id"] - self._media_object = None + self.file_id = fs._path_to_id(path) + self._media_object: Any | None = None + + @override + def _fetch_range(self, start: int | None = None, end: int | None = None) -> bytes: + """Fetch bytes from Google Drive for the open file. - def _fetch_range(self, start=None, end=None): - """Get data from Google Drive + Args: + start: Start byte offset, or None to fetch from the beginning. + end: End byte offset (exclusive), or None to fetch through the end. - start, end : None or integers - if not both None, fetch only given range + Returns: + Requested byte range, or empty bytes if the range is not satisfiable. """ if self._media_object is None: @@ -410,7 +1050,7 @@ def _fetch_range(self, start=None, end=None): else: self._media_object.headers.pop("Range", None) try: - data = self._media_object.execute() + data = self._media_object.execute(num_retries=_NUM_RETRIES) return data except HttpError as e: # TODO : doc says server might send everything if range is outside @@ -418,13 +1058,37 @@ def _fetch_range(self, start=None, end=None): return b"" raise - def _upload_chunk(self, final=False): - """Write one part of a multi-block file upload + def _authed_request( + self, + uri: str, + method: str, + *, + body: bytes | None = None, + headers: dict[str, str] | None = None, + ) -> tuple[httplib2.Response, bytes]: + """ + Make an authenticated raw request via the owned transport. + Wraps ``fs.authed_http.request`` to make it typed. + """ + response, content = self.fs.authed_http.request( + uri, method=method, body=body, headers=headers + ) + return response, content + + @override + # pyrefly: ignore [bad-override] # fsspec leaves the base method unannotated + def _upload_chunk(self, final: bool = False) -> bool: + """Upload one chunk of a resumable multi-part upload. + + Returns ``False`` (fsspec's "buffer not fully consumed" signal) when the + server accepted only part of the buffer; ``True`` once it accepted all of + it. See :meth:`_consume_accepted` for the partial-acceptance handling. + + Args: + final: If True, finalize and commit the upload. - Parameters - ---------- - final: bool - Complete and commit upload + Raises: + IOError: If the upload server returns an unexpected response. """ self.buffer.seek(0) data = self.buffer.getvalue() @@ -432,7 +1096,9 @@ def _upload_chunk(self, final=False): length = len(data) if final and self.autocommit: if length: + # pyrefly: ignore [unsupported-operation] part = "%i-%i" % (self.offset, self.offset + length - 1) + # pyrefly: ignore [unsupported-operation] head["Content-Range"] = "bytes %s/%i" % (part, self.offset + length) else: # closing when buffer is empty @@ -441,74 +1107,152 @@ def _upload_chunk(self, final=False): else: head["Content-Range"] = "bytes %i-%i/*" % ( self.offset, + # pyrefly: ignore [unsupported-operation] self.offset + length - 1, ) head.update( {"Content-Type": "application/octet-stream", "Content-Length": str(length)} ) - req = self.fs.files._http.request - head, body = req( + response, body = self._authed_request( + # pyrefly: ignore [unsupported-operation] self.location + "&supportsAllDrives=true", - method="PUT", + "PUT", body=data, headers=head, ) - status = int(head["status"]) - assert status < 400, "Init upload failed" + status = int(response["status"]) + if status >= 400: + error_message = body.decode("utf-8", errors="replace") + raise IOError(f"Chunk upload failed (HTTP {status}): {error_message}") if status in [200, 201]: # server thinks we are finished - this should happen # only when closing blob = json.loads(body.decode()) self.file_id = blob["id"] - par = self.fs._parent(self.path) - # duplicate should not happen here, and parent should already exist - info = _finfo_from_response(blob, path_prefix=par) + parent = self.fs._parent(self.path) + info = _finfo_from_response(blob, path_prefix=parent) info["size"] = self.tell() - if par in self.fs.dircache: - self.fs.dircache[par].append(info) - elif "range" in head: - assert status == 308 - else: - raise IOError - return True + if parent in self.fs.dircache: + listing = self.fs.dircache[parent] + # Update the existing entry in place when overwriting, so the + # parent listing keeps exactly one entry per path. + for i, existing in enumerate(listing): + if existing["name"] == info["name"]: + listing[i] = info + break + else: + listing.append(info) + return True + if status != 308: + raise IOError(f"Unexpected resumable status {status}") + # A 308 on a finalizing PUT means the server did not commit the object. + # This path sends a concrete total and expects 200/201; treating the + # 308 as a partial-consumption signal would silently leave the upload + # unfinalized, since commit()/close() flush only once and ignore the + # re-buffer. Fail loudly instead. + if final and self.autocommit: + raise IOError( + f"Resumable upload not finalized: server returned 308 " + f"(range {response.get('range')!r}) on the final chunk" + ) + return self._consume_accepted(data, response.get("range")) - def commit(self): - """If not auto-committing, finalize file""" + def _consume_accepted(self, data: bytes | None, range_header: str | None) -> bool: + """Reconcile a 308 response with what the server actually stored. + + Google accepts intermediate data only up to a 256 KiB-aligned boundary + and reports the last stored byte in ``Range: bytes=0-``. Any bytes + past that boundary were dropped, so re-buffer them for the next chunk. + + Returns True if the whole buffer was accepted (fsspec then advances + ``offset`` and clears the buffer), or False if a tail was re-buffered + here (so fsspec must not advance ``offset`` past it). + """ + if data is None: + # Empty finalizing PUT; nothing to reconcile. + return True + offset = self.offset or 0 + stored_end = _parse_range_end(range_header) + # A 308 with no/garbled Range means the server persisted nothing yet, so + # the whole buffer must be re-sent. ``accepted`` is bytes stored from + # this buffer; the server should never report an end behind our offset. + accepted = 0 if stored_end is None else stored_end + 1 - offset + if accepted < 0 or accepted > len(data): + raise IOError( + f"Server reported {accepted} accepted bytes outside the {len(data)}-byte chunk at offset {offset}" + ) + if accepted == len(data): + return True + self.buffer = io.BytesIO(data[accepted:]) + self.buffer.seek(0, 2) # position at end for further writes + self.offset = offset + accepted + return False + + @override + def commit(self) -> None: + """Finalize the upload when ``autocommit`` is False.""" self.autocommit = True self._upload_chunk(final=True) - def _initiate_upload(self): - """Create multi-upload""" - parent_id = self.fs.info(self.fs._parent(self.path))["id"] - head = {"Content-Type": "application/json; charset=UTF-8"} + @override + def _initiate_upload(self) -> None: + """Start a resumable upload session. + + If the path already exists, the existing file is updated in place via + PATCH. Otherwise, a new file is created via POST. + + The discovery client's files.create/update + can only drive resumable uploads from a fully seekable source (MediaFileUpload); + fsspec streams blocks of unknown total size, so we manage the resumable session + manually instead. https://developers.google.com/workspace/drive/api/guides/manage-uploads#resumable + """ + headers = {"Content-Type": "application/json; charset=UTF-8"} + query = "?uploadType=resumable&supportsAllDrives=true" # also allows description, MIME type, version, thumbnail... - body = json.dumps( - {"name": self.path.rsplit("/", 1)[-1], "parents": [parent_id]} - ).encode() - req = self.fs.files._http.request # partial with correct creds - # TODO : this creates a new file. If the file exists, you should - # update it by getting the ID and using PATCH, or delete and recreate, - # else you get two identically-named files - r = req( - "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true", - method="POST", - headers=head, - body=body, - ) - head = r[0] - assert int(head["status"]) < 400, "Init upload failed" - self.location = r[0]["location"] + if self.file_id is not None: + # Update the existing file in place. ``name``/``parents`` are + # already set on the resource, so an empty body suffices. + response, _ = self._authed_request( + f"{UPLOAD_URL}/{self.file_id}{query}", + "PATCH", + headers=headers, + body=json.dumps({}).encode(), + ) + else: + parent_id = self.fs._path_to_id(self.fs._parent(self.path)) + response, _ = self._authed_request( + f"{UPLOAD_URL}{query}", + "POST", + headers=headers, + body=json.dumps( + {"name": self.path.rsplit("/", 1)[-1], "parents": [parent_id]} + ).encode(), + ) + status = int(response["status"]) + if status >= 400: + raise IOError(f"Init upload failed with status {status}") + self.location = response["location"] + + @override + def discard(self) -> None: + """Cancel an in-progress resumable upload. - def discard(self): - """Cancel in-progress multi-upload""" + Issues a ``DELETE`` against the session URI returned by + :meth:`_initiate_upload`, mirroring the other resumable-upload calls + rather than reconstructing the endpoint. Google replies ``499`` to a + successful cancellation, so that status is accepted alongside ``<400``. + See https://developers.google.com/workspace/drive/api/guides/manage-uploads#cancel-upload + """ if self.location is None: - logger.debug("Abort file creation %s", self.path) + LOGGER.debug("Abort file creation %s", self.path) return - logger.debug("Cancel file creation %s", self.path) - uid = re.findall("upload_id=([^&=?]+)", self.location) - head, _ = self.fs._call( + LOGGER.debug("Cancel file creation %s", self.path) + response, _ = self._authed_request( + _with_supports_all_drives(self.location), "DELETE", - "https://www.googleapis.com/upload/drive/v3/files", - params={"uploadType": "resumable", "upload_id": uid}, + headers={"Content-Length": "0"}, ) - assert int(head["status"]) < 400, "Cancel upload failed" + status = int(response["status"]) + if not (status < 400 or status == 499): + raise IOError(f"Cancel upload failed with status {status}") + self.location = None diff --git a/src/gdrive_fsspec/types.py b/src/gdrive_fsspec/types.py new file mode 100644 index 0000000..d2d3386 --- /dev/null +++ b/src/gdrive_fsspec/types.py @@ -0,0 +1,39 @@ +"""Static types for Google Drive fsspec integration.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from typing_extensions import TypedDict + +if TYPE_CHECKING: + from googleapiclient._apis.drive.v3.resources import DriveResource + from googleapiclient._apis.drive.v3.schemas import Drive, File + + FilesResource = DriveResource.FilesResource + + +class _FsspecRequired(TypedDict): + """Fields fsspec requires on every file-info dict.""" + + name: str + size: int + type: Literal["file", "directory"] + + +class _DrivePartialFields(TypedDict, total=False): + """Subset of Drive v3 ``File`` fields requested via ``FIELDS``.""" + + id: str + mimeType: str + trashed: bool + version: str + createdTime: str + modifiedTime: str + + +class FileInfo(_FsspecRequired, _DrivePartialFields, extra_items=Any): + """fsspec file-info dict: normalized path fields plus Drive API metadata.""" + + +__all__ = ["Drive", "DriveResource", "File", "FileInfo", "FilesResource"] diff --git a/src/gdrive_fsspec/typing_utils.py b/src/gdrive_fsspec/typing_utils.py new file mode 100644 index 0000000..275a252 --- /dev/null +++ b/src/gdrive_fsspec/typing_utils.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +import sys + +if sys.version_info >= (3, 12): + from typing import override as _override +else: + from typing_extensions import override as _override + +override = _override diff --git a/src/gdrive_fsspec/utils.py b/src/gdrive_fsspec/utils.py new file mode 100644 index 0000000..f0cb324 --- /dev/null +++ b/src/gdrive_fsspec/utils.py @@ -0,0 +1,16 @@ +def merge_fields(base: str, extra: str | None) -> str: + """Merge two comma-separated Drive field masks, dropping duplicate tokens. + + Args: + base: Base fields string, always retained. + extra: Additional fields to append; ``None`` or empty returns ``base`` + unchanged. + + Returns: + The merged field mask, order-preserving with duplicate tokens removed. + """ + if not extra: + return base + fields = [f.strip() for f in base.split(",") if f.strip()] + fields.extend(f.strip() for f in extra.split(",") if f.strip()) + return ",".join(dict.fromkeys(fields)) diff --git a/tests/conftest.py b/tests/conftest.py index 48c54ec..c168b53 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,10 +1,356 @@ +import os +from dataclasses import dataclass +from typing import Any, Callable, Generator, NamedTuple +from unittest import mock + import pytest from gdrive_fsspec import GoogleDriveFileSystem +from gdrive_fsspec.core import AuthMethod + +TESTDIR = "gdrive_fsspec_testdir" + +FsFactory = Callable[..., GoogleDriveFileSystem] + + +def empty_headers() -> dict[str, str]: + return {} + + +def empty_listing() -> list[dict[str, Any]]: + return [] + + +def empty_files_list_response() -> dict[str, Any]: + files: list[Any] = [] + return {"files": files} + + +class MockedDriveFS(NamedTuple): + fs: GoogleDriveFileSystem + files: mock.Mock + service: mock.Mock + authed_http: mock.Mock @pytest.fixture() -def anon_fs(): +def mocked_fs(anon_fs: GoogleDriveFileSystem) -> MockedDriveFS: + files = mock.Mock() + service = mock.Mock() + authed_http = mock.Mock() + # Raw resumable-upload calls go through fs.authed_http.request; the + # discovery client's files()._http points at the same transport so tests + # can assert on either handle interchangeably. + files._http = authed_http + anon_fs.files = files + anon_fs.service = service + anon_fs.authed_http = authed_http + return MockedDriveFS(anon_fs, files, service, authed_http) + + +@pytest.fixture() +def anon_fs() -> GoogleDriveFileSystem: # skip_instance_cache keeps each test's dircache isolated; fsspec otherwise # returns the same cached instance for identical constructor arguments. return GoogleDriveFileSystem(token="anon", skip_instance_cache=True) + + +# --------------------------------------------------------------------------- +# Integration-test drive profiles +# +# A single service-account key backs every ``service_account`` profile; each +# profile just points at a different target (a shared drive with a specific +# role, or the account's own My Drive). +# +# Whether a service-account key is configured picks the identity for the default +# ``fs``/``make_fs`` suite: when ``GDRIVE_FSSPEC_CREDENTIALS_PATH`` is set the +# suite runs as the full-access service account; when it is unset the suite runs +# as a user via OAuth (the ``user`` profile), logging in through the browser once +# per session and reusing the cached token thereafter. See the header of +# ``tests/test_integration.py`` for the full environment-variable reference. +# --------------------------------------------------------------------------- + +# Profile identifiers. +CONTENT_MANAGER = "content_manager" +READONLY = "readonly" +FULL_ACCESS = "full_access" +SA_MY_DRIVE = "sa_my_drive" +USER = "user" + +# Shared service-account key (path to JSON or the JSON string itself). +_CREDS_ENV = "GDRIVE_FSSPEC_CREDENTIALS_PATH" + + +@dataclass(frozen=True) +class DriveProfile: + """A named credential/target combination for live integration tests. + + The ``writable``/``can_trash``/``can_permanent_delete`` flags are + informational: they document the access level each profile is expected to + have (and mirror the permission boundaries asserted by the profile-specific + tests). They are not consumed programmatically yet; teardown removes + ``TESTDIR`` with a permanent-then-trash fallback that works for any role. + """ + + id: str + token: AuthMethod + creds_env: str | None + drive_env: str | None + writable: bool + can_trash: bool + can_permanent_delete: bool + description: str + + +PROFILES: dict[str, DriveProfile] = { + CONTENT_MANAGER: DriveProfile( + id=CONTENT_MANAGER, + token="service_account", + creds_env=_CREDS_ENV, + drive_env="GDRIVE_FSSPEC_DRIVE_CONTENT_MANAGER", + writable=True, + can_trash=True, + can_permanent_delete=False, + description="Service account with Content manager access on a shared drive.", + ), + READONLY: DriveProfile( + id=READONLY, + token="service_account", + creds_env=_CREDS_ENV, + drive_env="GDRIVE_FSSPEC_DRIVE_READONLY", + writable=False, + can_trash=False, + can_permanent_delete=False, + description="Service account with Viewer access on a shared drive.", + ), + FULL_ACCESS: DriveProfile( + id=FULL_ACCESS, + token="service_account", + creds_env=_CREDS_ENV, + drive_env="GDRIVE_FSSPEC_DRIVE_FULL_ACCESS", + writable=True, + can_trash=True, + can_permanent_delete=True, + description="Service account with full (Manager) access on a shared drive.", + ), + SA_MY_DRIVE: DriveProfile( + id=SA_MY_DRIVE, + token="service_account", + creds_env=_CREDS_ENV, + drive_env=None, + writable=False, + can_trash=False, + can_permanent_delete=False, + description="Service account without a shared drive (its own quota-less My Drive).", + ), + USER: DriveProfile( + id=USER, + token="cache", + creds_env=None, + drive_env=None, + writable=True, + can_trash=True, + can_permanent_delete=True, + description=( + "User OAuth identity (My Drive). Uses a cached token; a one-time " + "browser login populates the cache when it is missing." + ), + ), +} + + +def _creds_value(profile: DriveProfile) -> str | None: + return os.getenv(profile.creds_env) if profile.creds_env else None + + +def _drive_value(profile: DriveProfile) -> str | None: + if profile.drive_env is None: + return None + return os.getenv(profile.drive_env) + + +def _service_account_configured() -> bool: + return bool((os.getenv(_CREDS_ENV) or "").strip()) + + +def _default_profile_id() -> str: + """Pick the identity for the default ``fs``/``make_fs`` suite. + + A configured service-account key selects full access; otherwise the suite + runs as a user via OAuth so the same CRUD tests can be exercised locally + without a service account. + """ + return FULL_ACCESS if _service_account_configured() else USER + + +def _oauth_cache_available() -> bool: + """True when a cached user OAuth token exists (so no browser prompt fires).""" + try: + import pydata_google_auth.cache + + path = pydata_google_auth.cache.READ_WRITE._path + except Exception: + return False + return bool(path) and os.path.exists(path) + + +# Guard so the interactive browser login runs at most once per test session. +_user_login_done = False + + +def _force_browser_login() -> bool: + """True when the user asked to re-run the browser login (ignoring any cache).""" + return bool((os.getenv("GDRIVE_FSSPEC_FORCE_BROWSER") or "").strip()) + + +def _ensure_user_login() -> None: + """Make sure a cached user token exists, logging in via browser once. + + ``token="cache"`` would itself launch the browser flow on a cache miss, but + it would do so for *every* filesystem the suite builds. Instead we perform a + single ``token="browser"`` login up front and let every later instance reuse + the cache. Never triggers in CI (guarded by the caller). + + Set ``GDRIVE_FSSPEC_FORCE_BROWSER=1`` to force a fresh browser login even + when a cached token already exists (``token="browser"`` clears the cache and + re-authenticates). It still happens at most once per session. + """ + global _user_login_done + if _user_login_done: + return + if _oauth_cache_available() and not _force_browser_login(): + _user_login_done = True + return + # Populate the cache with one interactive login for the whole session. + GoogleDriveFileSystem(token="browser", skip_instance_cache=True) + _user_login_done = True + + +def _require_profile(profile_id: str) -> DriveProfile: + """Return the profile, skipping the test when it is not configured.""" + profile = PROFILES[profile_id] + if profile.creds_env is not None: + creds = _creds_value(profile) + if not creds or not creds.strip(): + pytest.skip(f"{profile.creds_env} not set (profile {profile_id!r})") + if profile.drive_env is not None: + drive = _drive_value(profile) + if not drive or not drive.strip(): + pytest.skip(f"{profile.drive_env} not set (profile {profile_id!r})") + if profile.token in ("cache", "browser"): + # The browser login is interactive; never attempt it in CI. + if os.getenv("CI"): + pytest.skip(f"cannot run interactive OAuth profile {profile_id!r} in CI") + _ensure_user_login() + return profile + + +def _build_fs(profile: DriveProfile, **overrides: Any) -> GoogleDriveFileSystem: + return GoogleDriveFileSystem( + skip_instance_cache=True, + token=profile.token, + creds=_creds_value(profile), + drive=_drive_value(profile), + **overrides, + ) + + +def _remove_testdir(instance: GoogleDriveFileSystem) -> None: + """Best-effort delete of ``TESTDIR``, falling back to trash when needed. + + Managers can permanently delete; content managers can only trash. Try the + stronger operation first and fall back so cleanup works for either role. + """ + try: + if not instance.exists(TESTDIR): + return + except (OSError, PermissionError): + return + for permanent in (True, False): + try: + instance.rm(TESTDIR, recursive=True, permanent=permanent) + return + except (OSError, PermissionError): + continue + + +def _reset_testdir(instance: GoogleDriveFileSystem) -> None: + """Give ``instance`` a fresh, empty ``TESTDIR``.""" + _remove_testdir(instance) + instance.mkdir(TESTDIR, create_parents=True) + + +ProfiledFactory = Callable[[str], FsFactory] + + +@pytest.fixture() +def fs_factory() -> Generator[ProfiledFactory, None, None]: + """Build live filesystems for any profile, cleaning up ``TESTDIR`` afterwards. + + ``fs_factory(profile_id)`` returns a factory that constructs as many + instances of that profile as a test needs (e.g. a second one rooted at a + different ``root_file_id``). Every instance created through this fixture has + its ``TESTDIR`` removed during teardown. + """ + created: list[GoogleDriveFileSystem] = [] + + def _for(profile_id: str) -> FsFactory: + profile = _require_profile(profile_id) + + def _make(**overrides: Any) -> GoogleDriveFileSystem: + instance = _build_fs(profile, **overrides) + created.append(instance) + return instance + + return _make + + yield _for + + for instance in created: + _remove_testdir(instance) + + +@pytest.fixture() +def make_fs(fs_factory: ProfiledFactory) -> FsFactory: + """Factory for the default identity's filesystems. + + Full-access service account when ``GDRIVE_FSSPEC_CREDENTIALS_PATH`` is set, + otherwise the OAuth user identity, so the same CRUD suite runs either way. + """ + return fs_factory(_default_profile_id()) + + +@pytest.fixture() +def fs(make_fs: FsFactory) -> GoogleDriveFileSystem: + """A single default-identity filesystem with a fresh ``TESTDIR`` already created.""" + instance = make_fs() + _reset_testdir(instance) + return instance + + +@pytest.fixture() +def content_manager_fs(fs_factory: ProfiledFactory) -> GoogleDriveFileSystem: + """A content-manager filesystem with a fresh ``TESTDIR`` (can trash, not delete).""" + instance = fs_factory(CONTENT_MANAGER)() + _reset_testdir(instance) + return instance + + +@pytest.fixture() +def readonly_fs(fs_factory: ProfiledFactory) -> GoogleDriveFileSystem: + """A viewer-only filesystem (list/read succeed; every mutation is denied).""" + return fs_factory(READONLY)() + + +@pytest.fixture() +def sa_my_drive_fs(fs_factory: ProfiledFactory) -> GoogleDriveFileSystem: + """A service-account filesystem with no shared drive (quota-less My Drive).""" + return fs_factory(SA_MY_DRIVE)() + + +@pytest.fixture() +def requires_shared_drive() -> None: + """Skip when no full-access shared drive is configured.""" + drive = _drive_value(PROFILES[FULL_ACCESS]) + if not drive or not drive.strip(): + pytest.skip("full-access shared drive not configured") diff --git a/tests/test_core.py b/tests/test_core.py index 19c42eb..fedf7a8 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1,122 +1,43 @@ import json -import os +from typing import Any, Literal, cast from unittest import mock import pytest +from conftest import MockedDriveFS +from googleapiclient.errors import HttpError -from gdrive_fsspec.core import ( - DIR_MIME_TYPE, - GoogleDriveFile, - GoogleDriveFileSystem, - _finfo_from_response, - _normalize_path, -) - - -TESTDIR = "gdrive_fsspec_testdir" - - -def _credentials_configured(): - token = os.getenv("GDRIVE_FSSPEC_CREDENTIALS_TYPE", "service_account") - if token == "service_account": - path = os.getenv("GDRIVE_FSSPEC_CREDENTIALS_PATH") - return bool(path and path.strip()) - return True - - -@pytest.fixture() -def fs(): - if not _credentials_configured(): - pytest.skip("GDRIVE_FSSPEC_CREDENTIALS_PATH not set") - kwargs = { - "creds": os.getenv("GDRIVE_FSSPEC_CREDENTIALS_PATH"), - "token": os.getenv("GDRIVE_FSSPEC_CREDENTIALS_TYPE", "service_account"), - "drive": os.getenv("GDRIVE_FSSPEC_DRIVE"), - } - fs = GoogleDriveFileSystem(skip_instance_cache=True, **kwargs) - if fs.exists(TESTDIR): - fs.rm(TESTDIR, recursive=True) - fs.mkdir(TESTDIR, create_parents=True) - try: - yield fs - finally: - try: - fs.rm(TESTDIR, recursive=True) - except IOError: - pass - - -# --------------------------------------------------------------------------- -# Pure helpers -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "prefix, name, expected", - [ - ("/a/b/", "c", "/a/b/c"), - ("a/b", "c", "/a/b/c"), - ], -) -def test_normalize_path(prefix, name, expected): - assert _normalize_path(prefix, name) == expected - - -@pytest.mark.parametrize( - "mime_type, expected_type", - [ - ("text/plain", "file"), - (DIR_MIME_TYPE, "directory"), - ], -) -def test_finfo_from_response_type(mime_type, expected_type): - info = _finfo_from_response( - {"name": "child", "mimeType": mime_type}, path_prefix="parent" - ) - assert info["type"] == expected_type - assert info["name"] == "parent/child" - - -def test_finfo_from_response_casts_size(): - assert _finfo_from_response({"name": "x", "size": "12"})["size"] == 12 - +from gdrive_fsspec.core import DIR_MIME_TYPE, GoogleDriveFile, GoogleDriveFileSystem -def test_finfo_from_response_defaults_missing_size(): - assert _finfo_from_response({"name": "x"})["size"] == 0 +def test_create_anon(anon_fs: GoogleDriveFileSystem) -> None: + assert anon_fs.service is not None -def test_finfo_from_response_strips_leading_slash(): - info = _finfo_from_response({"name": "f"}, path_prefix="/top") - assert info["name"] == "top/f" +def test_srv_is_deprecated_alias(anon_fs: GoogleDriveFileSystem) -> None: + with pytest.warns(DeprecationWarning): + assert anon_fs.srv is anon_fs.service -# --------------------------------------------------------------------------- -# Construction and connection (no network) -# --------------------------------------------------------------------------- - -def test_create_anon(anon_fs): - assert anon_fs.srv is not None - - -def test_auth_kwargs(): +def test_auth_kwargs() -> None: fs = GoogleDriveFileSystem( token="anon", auth_kwargs={"user_email": "test@example.com"}, skip_instance_cache=True, ) - assert fs.srv is not None + assert fs.service is not None assert fs.auth_kwargs == {"user_email": "test@example.com"} -def test_connect_invalid_method(): +def test_connect_invalid_method() -> None: with pytest.raises(ValueError): - GoogleDriveFileSystem(token="bogus", skip_instance_cache=True) + GoogleDriveFileSystem(token=cast(Any, "bogus"), skip_instance_cache=True) -def test_invalid_access_raises(): +def test_invalid_access_raises() -> None: with pytest.raises(KeyError): - GoogleDriveFileSystem(token="anon", access="nope", skip_instance_cache=True) + GoogleDriveFileSystem( + token="anon", access=cast(Any, "nope"), skip_instance_cache=True + ) @pytest.mark.parametrize( @@ -126,17 +47,23 @@ def test_invalid_access_raises(): ("read_only", ["https://www.googleapis.com/auth/drive.readonly"]), ], ) -def test_access_scopes_mapping(access, expected_scopes): +def test_access_scopes_mapping( + access: Literal["full_control", "read_only"], + expected_scopes: list[str], +) -> None: fs = GoogleDriveFileSystem(token="anon", access=access, skip_instance_cache=True) assert fs.scopes == expected_scopes -def test_upload_chunk_without_parent_dircache(): +def test_upload_chunk_without_parent_dircache() -> None: fs = GoogleDriveFileSystem( token="anon", skip_instance_cache=True, use_listings_cache=False ) fs.files = mock.Mock() - fs.files._http.request.return_value = ( + fs.authed_http = mock.Mock() + # New file: the path does not exist yet. + fs.info = mock.Mock(side_effect=FileNotFoundError("parent/file.txt")) + fs.authed_http.request.return_value = ( {"status": "200"}, json.dumps({"id": "file-id", "name": "file.txt", "size": "4"}).encode(), ) @@ -146,6 +73,7 @@ def test_upload_chunk_without_parent_dircache(): file.offset = 0 try: + # A fully-accepted final chunk (HTTP 200) reports completion as True. assert file._upload_chunk(final=True) is True finally: file.closed = True @@ -154,24 +82,230 @@ def test_upload_chunk_without_parent_dircache(): assert file.file_id == "file-id" -def test_drive_kw_without_drive(anon_fs): +def test_drive_kw_without_drive(anon_fs: GoogleDriveFileSystem) -> None: assert anon_fs._drive_kw() == {} -def test_drive_kw_with_drive(anon_fs): +def test_drive_kw_with_drive(anon_fs: GoogleDriveFileSystem) -> None: anon_fs.drive = "drive-123" kw = anon_fs._drive_kw() assert kw["driveId"] == "drive-123" assert kw["supportsAllDrives"] is True -def test_root_info(anon_fs): +def test_root_info(anon_fs: GoogleDriveFileSystem) -> None: info = anon_fs.info("") - assert info["type"] == "directory" - assert info["id"] == anon_fs.root_file_id + assert info == { + "name": "", + "mimeType": DIR_MIME_TYPE, + "type": "directory", + "size": 0, + "id": anon_fs.root_file_id, + } + + +def _http_error(status: int) -> HttpError: + resp = mock.Mock(status=status, reason="Error") + return HttpError(resp, b'{"error": {"message": "x"}}') + + +def test_validate_root_file_id_accepts_folder(mocked_fs: MockedDriveFS) -> None: + mocked_fs.files.get.return_value.execute.return_value = { + "id": "folder-id", + "trashed": False, + "mimeType": DIR_MIME_TYPE, + } + + mocked_fs.fs._validate_root_file_id("folder-id") + + mocked_fs.files.get.assert_called_once_with( + fileId="folder-id", + fields="id,trashed,mimeType,driveId", + supportsAllDrives=True, + ) -def test_invalidate_cache_path(anon_fs): +def test_validate_root_file_id_accepts_folder_in_scoped_drive( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.fs.drive = "drive-id" + mocked_fs.files.get.return_value.execute.return_value = { + "id": "folder-id", + "trashed": False, + "mimeType": DIR_MIME_TYPE, + "driveId": "drive-id", + } + + mocked_fs.fs._validate_root_file_id("folder-id") + + +def test_validate_root_file_id_rejects_folder_in_other_drive( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.fs.drive = "drive-id" + mocked_fs.files.get.return_value.execute.return_value = { + "id": "folder-id", + "trashed": False, + "mimeType": DIR_MIME_TYPE, + "driveId": "other-drive", + } + + with pytest.raises(ValueError, match="not in drive"): + mocked_fs.fs._validate_root_file_id("folder-id") + + +def test_validate_root_file_id_rejects_my_drive_folder_when_scoped( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.fs.drive = "drive-id" + mocked_fs.files.get.return_value.execute.return_value = { + "id": "folder-id", + "trashed": False, + "mimeType": DIR_MIME_TYPE, + } + + with pytest.raises(ValueError, match="not in drive"): + mocked_fs.fs._validate_root_file_id("folder-id") + + +def test_validate_root_file_id_rejects_non_folder( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.files.get.return_value.execute.return_value = { + "id": "file-id", + "trashed": False, + "mimeType": "text/plain", + } + + with pytest.raises(NotADirectoryError, match="not a folder"): + mocked_fs.fs._validate_root_file_id("file-id") + + +def test_validate_root_file_id_rejects_trashed_folder( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.files.get.return_value.execute.return_value = { + "id": "folder-id", + "trashed": True, + "mimeType": DIR_MIME_TYPE, + } + + with pytest.raises(FileNotFoundError, match="trashed"): + mocked_fs.fs._validate_root_file_id("folder-id") + + +def test_validate_root_file_id_accepts_drive_id_and_sets_drive( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.fs.drive = None + mocked_fs.files.get.return_value.execute.side_effect = _http_error(404) + mocked_fs.service.drives.return_value.get.return_value.execute.return_value = { + "id": "drive-id", + } + + mocked_fs.fs._validate_root_file_id("drive-id") + + assert mocked_fs.fs.drive == "drive-id" + mocked_fs.service.drives.return_value.get.assert_called_once_with( + driveId="drive-id" + ) + + +def test_validate_root_file_id_accepts_matching_drive_id( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.fs.drive = "drive-id" + mocked_fs.files.get.return_value.execute.side_effect = _http_error(404) + mocked_fs.service.drives.return_value.get.return_value.execute.return_value = { + "id": "drive-id", + } + + mocked_fs.fs._validate_root_file_id("drive-id") + + assert mocked_fs.fs.drive == "drive-id" + + +def test_validate_root_file_id_conflicting_drive_id_raises( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.fs.drive = "existing-drive" + mocked_fs.files.get.return_value.execute.side_effect = _http_error(404) + mocked_fs.service.drives.return_value.get.return_value.execute.return_value = { + "id": "drive-id", + } + + with pytest.raises(ValueError, match="conflicts with drive"): + mocked_fs.fs._validate_root_file_id("drive-id") + + +def test_validate_root_file_id_missing(mocked_fs: MockedDriveFS) -> None: + mocked_fs.files.get.return_value.execute.side_effect = _http_error(404) + mocked_fs.service.drives.return_value.get.return_value.execute.side_effect = ( + _http_error(404) + ) + + with pytest.raises(FileNotFoundError, match="not found"): + mocked_fs.fs._validate_root_file_id("missing-id") + + +def test_validate_root_file_id_propagates_drive_permission_error( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.files.get.return_value.execute.side_effect = _http_error(404) + mocked_fs.service.drives.return_value.get.return_value.execute.side_effect = ( + _http_error(403) + ) + + with pytest.raises(HttpError) as exc_info: + mocked_fs.fs._validate_root_file_id("drive-id") + assert exc_info.value.status_code == 403 + + +def test_validate_root_file_id_propagates_non_404_from_files_get( + mocked_fs: MockedDriveFS, +) -> None: + mocked_fs.files.get.return_value.execute.side_effect = _http_error(403) + + with pytest.raises(HttpError) as exc_info: + mocked_fs.fs._validate_root_file_id("folder-id") + assert exc_info.value.status_code == 403 + + +def test_ls_empty_root_returns_empty(anon_fs: GoogleDriveFileSystem) -> None: + anon_fs._list_directory_by_id = mock.Mock(return_value=[]) + + assert anon_fs.ls("") == [] + assert anon_fs.dircache[""] == [] + + +def test_ls_missing_child_in_populated_parent_raises( + anon_fs: GoogleDriveFileSystem, +) -> None: + anon_fs._list_directory_by_id = mock.Mock( + return_value=[ + { + "name": "other", + "id": "other-id", + "type": "file", + "mimeType": "text/plain", + } + ] + ) + + with pytest.raises(FileNotFoundError): + anon_fs.ls("missing") + + +def test_ls_missing_path_on_empty_root_raises( + anon_fs: GoogleDriveFileSystem, +) -> None: + anon_fs._list_directory_by_id = mock.Mock(return_value=[]) + + with pytest.raises(FileNotFoundError): + anon_fs.ls("missing") + + +def test_invalidate_cache_path(anon_fs: GoogleDriveFileSystem) -> None: anon_fs.dircache["parent"] = [{"name": "parent/file"}] anon_fs.dircache["other"] = [{"name": "other/file"}] @@ -181,7 +315,7 @@ def test_invalidate_cache_path(anon_fs): assert anon_fs.dircache["other"] == [{"name": "other/file"}] -def test_invalidate_cache_all(anon_fs): +def test_invalidate_cache_all(anon_fs: GoogleDriveFileSystem) -> None: anon_fs.dircache["parent"] = [{"name": "parent/file"}] anon_fs.dircache["other"] = [{"name": "other/file"}] @@ -190,21 +324,26 @@ def test_invalidate_cache_all(anon_fs): assert anon_fs.dircache == {} -def test_drive_id_from_name_single_match(anon_fs): +def test_resolve_drive_id_by_name(anon_fs: GoogleDriveFileSystem) -> None: anon_fs.drives = [{"id": "1", "name": "foo"}, {"id": "2", "name": "bar"}] - assert anon_fs._drive_id_from_name("foo") == "1" + assert anon_fs._resolve_drive_id("foo") == "1" -def test_drive_id_from_name_missing(anon_fs): +def test_resolve_drive_id_by_id(anon_fs: GoogleDriveFileSystem) -> None: + anon_fs.drives = [{"id": "1", "name": "foo"}, {"id": "2", "name": "bar"}] + assert anon_fs._resolve_drive_id("2") == "2" + + +def test_resolve_drive_id_missing(anon_fs: GoogleDriveFileSystem) -> None: anon_fs.drives = [{"id": "1", "name": "foo"}] - with pytest.raises(ValueError): - anon_fs._drive_id_from_name("missing") + with pytest.raises(ValueError, match="not found by id or name"): + anon_fs._resolve_drive_id("missing") -def test_drive_id_from_name_duplicate(anon_fs): +def test_resolve_drive_id_duplicate_name(anon_fs: GoogleDriveFileSystem) -> None: anon_fs.drives = [{"id": "1", "name": "dup"}, {"id": "2", "name": "dup"}] - with pytest.raises(ValueError): - anon_fs._drive_id_from_name("dup") + with pytest.raises(ValueError, match="multiple shared drives"): + anon_fs._resolve_drive_id("dup") @pytest.mark.parametrize( @@ -214,49 +353,23 @@ def test_drive_id_from_name_duplicate(anon_fs): '{"type": "service_account"}', ], ) -def test_service_account_creds_parsing(creds): +def test_service_account_creds_parsing(creds: dict[str, Any] | str) -> None: target = "gdrive_fsspec.core.service_account.Credentials.from_service_account_info" with mock.patch(target) as from_info: GoogleDriveFileSystem( - token="service_account", creds=creds, skip_instance_cache=True + token="service_account", + creds=creds, + skip_instance_cache=True, ) from_info.assert_called_once() assert from_info.call_args.kwargs["info"] == {"type": "service_account"} @pytest.mark.parametrize("creds", ["", " ", "\t\n"]) -def test_service_account_empty_creds_raises(creds): +def test_service_account_empty_creds_raises(creds: str) -> None: with pytest.raises(ValueError, match="Empty credentials"): GoogleDriveFileSystem( - token="service_account", creds=creds, skip_instance_cache=True + token="service_account", + creds=creds, + skip_instance_cache=True, ) - - -# --------------------------------------------------------------------------- -# Integration (require live Google Drive credentials) -# --------------------------------------------------------------------------- - - -@pytest.mark.integration -def test_simple(fs): - assert fs.ls("") - data = b"hello" - fn = TESTDIR + "/testfile" - with fs.open(fn, "wb") as f: - f.write(data) - assert fs.cat(fn) == data - - -@pytest.mark.integration -def test_create_directory(fs): - fs.makedirs(TESTDIR + "/data") - fs.makedirs(TESTDIR + "/data/bar/baz") - - assert fs.exists(TESTDIR + "/data") - assert fs.exists(TESTDIR + "/data/bar") - assert fs.exists(TESTDIR + "/data/bar/baz") - - data = b"intermediate path" - with fs.open(TESTDIR + "/data/bar/test", "wb") as f: - f.write(data) - assert fs.cat(TESTDIR + "/data/bar/test") == data diff --git a/tests/test_core_auth.py b/tests/test_core_auth.py new file mode 100644 index 0000000..c6a2991 --- /dev/null +++ b/tests/test_core_auth.py @@ -0,0 +1,188 @@ +"""Unit tests for GoogleDriveFileSystem authentication and construction.""" + +from pathlib import Path +from typing import Any +from unittest import mock + +from gdrive_fsspec.core import ROOT_ID, GoogleDriveFileSystem + + +def test_anon_clears_drive() -> None: + fs = GoogleDriveFileSystem( + token="anon", + drive="would-resolve", + skip_instance_cache=True, + ) + + assert fs.drive is None + + +def test_init_resolves_drive_for_non_anon() -> None: + target = "gdrive_fsspec.core.service_account.Credentials.from_service_account_info" + with mock.patch(target, return_value=mock.Mock()): + with mock.patch("gdrive_fsspec.core.build"): + with mock.patch.object( + GoogleDriveFileSystem, + "_resolve_drive_id", + return_value="resolved-id", + ) as resolve: + fs = GoogleDriveFileSystem( + token="service_account", + creds={"type": "service_account"}, + drive="My Drive", + skip_instance_cache=True, + ) + + resolve.assert_called_once_with("My Drive") + assert fs.drive == "resolved-id" + + +def test_init_validates_root_file_id() -> None: + target = "gdrive_fsspec.core.service_account.Credentials.from_service_account_info" + with mock.patch(target, return_value=mock.Mock()): + with mock.patch("gdrive_fsspec.core.build"): + with mock.patch.object( + GoogleDriveFileSystem, "_validate_root_file_id" + ) as validate: + GoogleDriveFileSystem( + token="service_account", + creds={"type": "service_account"}, + root_file_id="folder-id", + skip_instance_cache=True, + ) + + validate.assert_called_once_with("folder-id") + + +def test_init_skips_validation_for_default_root() -> None: + target = "gdrive_fsspec.core.service_account.Credentials.from_service_account_info" + with mock.patch(target, return_value=mock.Mock()): + with mock.patch("gdrive_fsspec.core.build"): + with mock.patch.object( + GoogleDriveFileSystem, "_validate_root_file_id" + ) as validate: + GoogleDriveFileSystem( + token="service_account", + creds={"type": "service_account"}, + root_file_id=ROOT_ID, + skip_instance_cache=True, + ) + + validate.assert_not_called() + + +def test_init_root_file_id_defaults_to_drive_or_root() -> None: + target = "gdrive_fsspec.core.service_account.Credentials.from_service_account_info" + with mock.patch(target, return_value=mock.Mock()): + with mock.patch("gdrive_fsspec.core.build"): + with mock.patch.object( + GoogleDriveFileSystem, + "_resolve_drive_id", + return_value="drive-id", + ): + scoped = GoogleDriveFileSystem( + token="service_account", + creds={"type": "service_account"}, + drive="team", + skip_instance_cache=True, + ) + plain = GoogleDriveFileSystem( + token="anon", + skip_instance_cache=True, + ) + + assert scoped.root_file_id == "drive-id" + assert plain.root_file_id == ROOT_ID + + +def test_connect_browser_removes_cache_before_cache_connect() -> None: + fs = GoogleDriveFileSystem(token="anon", skip_instance_cache=True) + cred = mock.Mock() + + with mock.patch("gdrive_fsspec.core.os.remove") as remove: + with mock.patch.object(fs, "_connect_cache", return_value=cred) as cache: + with mock.patch("gdrive_fsspec.core.build"): + fs.connect(method="browser") + + remove.assert_called_once_with(fs._user_credentials_cache_path) + cache.assert_called_once() + assert fs.service is not None + + +def test_connect_browser_ignores_missing_cache_file() -> None: + fs = GoogleDriveFileSystem(token="anon", skip_instance_cache=True) + + with mock.patch("gdrive_fsspec.core.os.remove", side_effect=FileNotFoundError): + with mock.patch.object(fs, "_connect_cache", return_value=mock.Mock()): + with mock.patch("gdrive_fsspec.core.build"): + fs.connect(method="browser") + + +def test_connect_cache_passes_auth_kwargs() -> None: + target = "pydata_google_auth.get_user_credentials" + with mock.patch(target, return_value=mock.Mock()) as get_creds: + with mock.patch("gdrive_fsspec.core.build"): + GoogleDriveFileSystem( + token="cache", + auth_kwargs={"use_local_webserver": False}, + skip_instance_cache=True, + ) + + get_creds.assert_called_once_with( + ["https://www.googleapis.com/auth/drive"], + use_local_webserver=False, + ) + + +def test_service_account_creds_from_file(tmp_path: Path) -> None: + cred_file = tmp_path / "sa.json" + cred_file.write_text('{"type": "service_account", "project_id": "proj"}') + target = "gdrive_fsspec.core.service_account.Credentials.from_service_account_info" + + with mock.patch(target) as from_info: + with mock.patch("gdrive_fsspec.core.build"): + GoogleDriveFileSystem( + token="service_account", + creds=str(cred_file), + skip_instance_cache=True, + ) + + assert from_info.call_args.kwargs["info"] == { + "type": "service_account", + "project_id": "proj", + } + + +def test_service_account_passes_auth_kwargs() -> None: + target = "gdrive_fsspec.core.service_account.Credentials.from_service_account_info" + creds: dict[str, Any] = {"type": "service_account"} + + with mock.patch(target) as from_info: + with mock.patch("gdrive_fsspec.core.build"): + GoogleDriveFileSystem( + token="service_account", + creds=creds, + auth_kwargs={"quota_project_id": "my-project"}, + skip_instance_cache=True, + ) + + assert from_info.call_args.kwargs["quota_project_id"] == "my-project" + + +def test_connect_owns_authed_http_and_shares_with_build() -> None: + fs = GoogleDriveFileSystem(token="anon", skip_instance_cache=True) + sentinel = mock.Mock() + + with mock.patch( + "gdrive_fsspec.core.AuthorizedHttp", return_value=sentinel + ) as authed: + with mock.patch("gdrive_fsspec.core.build") as build: + fs.connect(method="anon") + + # The filesystem owns its own AuthorizedHttp built from the credentials... + authed.assert_called_once() + assert fs.authed_http is sentinel + # ...and hands that same transport to the discovery client so raw + # resumable-upload requests and the client share one connection/creds. + assert build.call_args.kwargs["http"] is sentinel + assert "credentials" not in build.call_args.kwargs diff --git a/tests/test_core_file.py b/tests/test_core_file.py new file mode 100644 index 0000000..c2334a7 --- /dev/null +++ b/tests/test_core_file.py @@ -0,0 +1,638 @@ +"""Unit tests for GoogleDriveFile read/write behavior.""" + +import io +import json +from typing import Any +from unittest import mock + +import pytest +from conftest import MockedDriveFS, empty_headers, empty_listing +from googleapiclient.errors import HttpError + +from gdrive_fsspec.core import ( + GoogleDriveFile, + GoogleDriveFileSystem, + MultipleFilesError, + _parse_range_end, + _with_supports_all_drives, +) + + +def _http_error(message: str) -> HttpError: + response = mock.Mock(status=416, reason="Range Not Satisfiable") + return HttpError(response, message.encode()) + + +def _write_file( + fs: GoogleDriveFileSystem, + path: str = "parent/file.txt", + existing_id: str | None = None, + parent_id: str = "parent-id", +) -> GoogleDriveFile: + """Build a ``wb`` file, stubbing ``fs.info`` for the path and its parent. + + ``existing_id`` is the id returned for ``path`` itself (``None`` means the + path does not exist yet, so the upload should create a new file). + """ + parent = fs._parent(path) + + def _info(p: str, *args: object, **kwargs: object) -> dict[str, Any]: + if fs._strip_protocol(p) == parent: + return {"id": parent_id, "type": "directory"} + if existing_id is not None: + return {"id": existing_id, "type": "file"} + raise FileNotFoundError(p) + + fs.info = mock.Mock(side_effect=_info) + fs._path_to_id = mock.Mock(return_value=parent_id) + file = GoogleDriveFile(fs, path, mode="wb") + file.location = "https://example.invalid/upload?upload_id=abc" + return file + + +def _read_file( + fs: GoogleDriveFileSystem, path: str = "path/file.txt" +) -> GoogleDriveFile: + fs._path_to_id = mock.Mock(return_value="file-id") + fs.info = mock.Mock( + return_value={"id": "file-id", "size": 5, "type": "file", "name": path} + ) + return GoogleDriveFile(fs, path, mode="rb") + + +def test_fetch_range_full_read(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + media = mock.Mock() + media.headers = empty_headers() + media.execute.return_value = b"hello" + mocked_fs.files.get_media.return_value = media + + file = _read_file(fs) + data = file._fetch_range() + + assert data == b"hello" + mocked_fs.files.get_media.assert_called_once_with( + fileId="file-id", supportsAllDrives=True + ) + assert "Range" not in media.headers + + +def test_fetch_range_with_byte_range(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + media = mock.Mock() + media.headers = empty_headers() + media.execute.return_value = b"hel" # codespell:ignore hel + mocked_fs.files.get_media.return_value = media + + file = _read_file(fs) + file._fetch_range(0, 3) + + assert media.headers["Range"] == "bytes=0-2" + + +def test_fetch_range_not_satisfiable_returns_empty( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + media = mock.Mock() + media.headers = empty_headers() + media.execute.side_effect = _http_error("not satisfiable") + mocked_fs.files.get_media.return_value = media + + file = _read_file(fs) + + assert file._fetch_range(100, 200) == b"" + + +def test_fetch_range_propagates_other_http_errors( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + media = mock.Mock() + media.headers = empty_headers() + media.execute.side_effect = HttpError( + mock.Mock(status=403, reason="Forbidden"), b"denied" + ) + mocked_fs.files.get_media.return_value = media + + file = _read_file(fs) + + with pytest.raises(HttpError): + file._fetch_range() + + +def test_initiate_upload_new_file(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ( + {"status": "200", "location": "https://upload.example/resume?upload_id=xyz"}, + b"", + ) + + file = _write_file(fs) + assert file.file_id is None + try: + file._initiate_upload() + finally: + file.closed = True + + assert file.location == "https://upload.example/resume?upload_id=xyz" + args, kwargs = mocked_fs.files._http.request.call_args + assert kwargs["method"] == "POST" + assert args[0].endswith("/files?uploadType=resumable&supportsAllDrives=true") + assert json.loads(kwargs["body"].decode()) == { + "name": "file.txt", + "parents": ["parent-id"], + } + + +def test_initiate_upload_existing_file_patches(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ( + {"status": "200", "location": "https://upload.example/resume?upload_id=xyz"}, + b"", + ) + + file = _write_file(fs, existing_id="existing-id") + assert file.file_id == "existing-id" + try: + file._initiate_upload() + finally: + file.closed = True + + assert file.location == "https://upload.example/resume?upload_id=xyz" + args, kwargs = mocked_fs.files._http.request.call_args + assert kwargs["method"] == "PATCH" + assert args[0].startswith( + "https://www.googleapis.com/upload/drive/v3/files/existing-id?" + ) + # No new resource is created, so name/parents are not re-sent. + assert json.loads(kwargs["body"].decode()) == {} + + +def test_open_wb_propagates_multiple_files_error(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + # A path that already resolves to duplicates must not be overwritten by + # creating a third copy; surface the ambiguity instead. Drive the real + # resolution path (dircache -> _path_to_id) rather than mocking info(). + fs.dircache["parent"] = [ + {"name": "parent/file.txt", "id": "id-1", "type": "file"}, + {"name": "parent/file.txt", "id": "id-2", "type": "file"}, + ] + + with pytest.raises(MultipleFilesError): + GoogleDriveFile(fs, "parent/file.txt", mode="wb") + + +def test_open_wb_on_directory_raises(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + # Opening an existing directory for writing must not resolve its id as an + # overwrite target; bytes cannot be PATCHed onto a folder. + fs.info = mock.Mock( + return_value={"id": "dir-id", "type": "directory", "name": "parent/sub"} + ) + + with pytest.raises(IsADirectoryError): + GoogleDriveFile(fs, "parent/sub", mode="wb") + + +def test_upload_chunk_partial(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ( + {"status": "308", "range": "0-999"}, + b"", + ) + file = _write_file(fs) + file.write(b"x" * 1000) + file.offset = 0 + + try: + file._upload_chunk(final=False) + finally: + file.closed = True + + headers = mocked_fs.files._http.request.call_args.kwargs["headers"] + assert headers["Content-Range"] == "bytes 0-999/*" + + +def test_upload_chunk_final_308_raises(mocked_fs: MockedDriveFS) -> None: + """A 308 on the finalizing PUT means the object was not committed. + + The final chunk sends a concrete total and expects 200/201. Treating a 308 + here as partial consumption would silently leave the upload unfinalized, + since commit()/close() flush only once and ignore the return. It must raise. + """ + fs = mocked_fs.fs + mocked_fs.authed_http.request.return_value = ( + {"status": "308", "range": "bytes=0-499"}, + b"", + ) + file = _write_file(fs) + file.write(b"x" * 1000) + file.offset = 0 + + with pytest.raises(IOError, match="not finalized"): + try: + file._upload_chunk(final=True) + finally: + file.closed = True + + +def test_upload_chunk_partial_accept_keeps_unsent_tail( + mocked_fs: MockedDriveFS, +) -> None: + """Google accepts intermediate data only up to a 256 KiB boundary. + + When the server stores fewer bytes than were sent (308 with a ``Range`` + short of the buffer end), the unaccepted tail must stay buffered and + ``offset`` must track the server, otherwise the upload silently never + completes. The method returns False so fsspec does not advance past the + tail itself. + """ + fs = mocked_fs.fs + # Sent 1000 bytes from offset 0; server stored only 0-599 (600 bytes). + mocked_fs.authed_http.request.return_value = ( + {"status": "308", "range": "bytes=0-599"}, + b"", + ) + file = _write_file(fs) + file.write(b"y" * 1000) + file.offset = 0 + + try: + result = file._upload_chunk(final=False) + finally: + file.closed = True + + # _upload_chunk parsed the 308, delegated to _consume_accepted, and + # propagated its result: the tail stays buffered and offset tracks the + # server. (Branch-level cases are covered directly below.) + assert result is False + assert file.offset == 600 + assert file.buffer.tell() == 400 + file.buffer.seek(0) + assert file.buffer.read() == b"y" * 400 + + +# --------------------------------------------------------------------------- +# Granular, transport-free tests for the 308 reconciliation helper. These call +# _consume_accepted directly so each branch is exercised in isolation, without +# the _upload_chunk / mocked-transport scaffolding above. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "header,expected", + [ + ("bytes=0-499", 499), # canonical resumable form + ("0-499", 499), # bare form (some responses omit the unit) + ("bytes=0-0", 0), # a single stored byte + (None, None), # no header + ("", None), # empty header + ("bytes=*", None), # no dash + ("bytes=0-notanint", None), # garbled end + ("bytes=10-20", None), # non-zero start: must not be read as end=20 + ("10-20", None), # same, bare form + ("garbage-20", None), # not a range at all + ("bytes=0-", None), # missing end + ], +) +def test_parse_range_end(header: str | None, expected: int | None) -> None: + assert _parse_range_end(header) == expected + + +@pytest.mark.parametrize( + "url,expected_query", + [ + # No existing param: it is added. + ("https://up/resume?upload_id=x", "upload_id=x&supportsAllDrives=true"), + # Already true: stays true, not duplicated. + ( + "https://up/resume?upload_id=x&supportsAllDrives=true", + "upload_id=x&supportsAllDrives=true", + ), + # Explicitly false: forced to true (the substring check missed this). + ( + "https://up/resume?supportsAllDrives=false&upload_id=x", + "supportsAllDrives=true&upload_id=x", + ), + # No query string at all. + ("https://up/resume", "supportsAllDrives=true"), + ], +) +def test_with_supports_all_drives(url: str, expected_query: str) -> None: + from urllib.parse import urlsplit + + assert urlsplit(_with_supports_all_drives(url)).query == expected_query + + +def _consume( + fs: GoogleDriveFileSystem, data: bytes | None, header: str | None, offset: int +) -> tuple[bool, GoogleDriveFile]: + """Run _consume_accepted on a fresh file at ``offset`` and return its result.""" + file = _write_file(fs) + file.offset = offset + try: + result = file._consume_accepted(data, header) + finally: + file.closed = True + return result, file + + +def test_consume_accepted_none_data_returns_true(mocked_fs: MockedDriveFS) -> None: + """An empty finalizing PUT (data=None) has nothing to reconcile.""" + result, _ = _consume(mocked_fs.fs, None, "bytes=0-9", offset=10) + assert result is True + + +def test_consume_accepted_full_accept_returns_true(mocked_fs: MockedDriveFS) -> None: + result, file = _consume(mocked_fs.fs, b"x" * 100, "bytes=0-99", offset=0) + assert result is True + + +def test_consume_accepted_partial_keeps_tail(mocked_fs: MockedDriveFS) -> None: + result, file = _consume(mocked_fs.fs, b"x" * 100, "bytes=0-59", offset=0) + assert result is False + assert file.offset == 60 + file.buffer.seek(0) + assert file.buffer.read() == b"x" * 40 + + +def test_consume_accepted_partial_at_nonzero_offset( + mocked_fs: MockedDriveFS, +) -> None: + """Accounting is relative to the chunk's starting offset, not absolute 0.""" + # Chunk covers bytes 1000..1099; server stored through 1049 β†’ 50 accepted. + result, file = _consume(mocked_fs.fs, b"y" * 100, "bytes=0-1049", offset=1000) + assert result is False + assert file.offset == 1050 + file.buffer.seek(0) + assert file.buffer.read() == b"y" * 50 + + +def test_consume_accepted_no_range_rebuffers_all(mocked_fs: MockedDriveFS) -> None: + """A 308 without a Range header means nothing was stored; re-send all.""" + result, file = _consume(mocked_fs.fs, b"z" * 100, None, offset=0) + assert result is False + assert file.offset == 0 + file.buffer.seek(0) + assert file.buffer.read() == b"z" * 100 + + +def test_consume_accepted_end_behind_offset_raises( + mocked_fs: MockedDriveFS, +) -> None: + """Server reporting a stored end behind the chunk start β†’ negative accepted.""" + with pytest.raises(IOError, match="accepted"): + _consume(mocked_fs.fs, b"z" * 100, "bytes=0-499", offset=600) + + +def test_consume_accepted_over_report_raises(mocked_fs: MockedDriveFS) -> None: + """Server claiming more stored than we sent in this chunk is a protocol error.""" + # offset 0, chunk is 100 bytes, but server says it stored through byte 999. + with pytest.raises(IOError, match="accepted"): + _consume(mocked_fs.fs, b"z" * 100, "bytes=0-999", offset=0) + + +def test_upload_chunk_final_updates_dircache(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.dircache["parent"] = empty_listing() + mocked_fs.files._http.request.return_value = ( + {"status": "200"}, + json.dumps( + {"id": "file-id", "name": "file.txt", "mimeType": "text/plain"} + ).encode(), + ) + file = _write_file(fs) + file.write(b"data") + file.offset = 0 + + try: + file._upload_chunk(final=True) + finally: + file.closed = True + + assert file.file_id == "file-id" + assert fs.dircache["parent"] == [ + { + "id": "file-id", + "name": "parent/file.txt", + "mimeType": "text/plain", + "size": 4, + "type": "file", + } + ] + + +def test_upload_chunk_final_overwrites_dircache_entry( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + # Existing listing already has the file; overwriting must not duplicate it. + fs.dircache["parent"] = [ + {"name": "parent/file.txt", "id": "old-id", "size": 1, "type": "file"} + ] + mocked_fs.files._http.request.return_value = ( + {"status": "200"}, + json.dumps( + {"id": "new-id", "name": "file.txt", "mimeType": "text/plain"} + ).encode(), + ) + file = _write_file(fs, existing_id="old-id") + file.write(b"hello") + file.offset = 0 + + try: + file._upload_chunk(final=True) + finally: + file.closed = True + + # Whole-listing compare: the single entry is fully replaced, with no stale + # fields (old id/size) leaking through from the pre-existing entry. + assert fs.dircache["parent"] == [ + { + "id": "new-id", + "name": "parent/file.txt", + "mimeType": "text/plain", + "size": 5, + "type": "file", + } + ] + assert file.file_id == "new-id" + + +def test_upload_chunk_final_empty_buffer(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ( + {"status": "200"}, + json.dumps({"id": "file-id", "name": "file.txt"}).encode(), + ) + file = _write_file(fs) + file.buffer = io.BytesIO() + file.offset = 10 + file.autocommit = True + + try: + file._upload_chunk(final=True) + finally: + file.closed = True + + headers = mocked_fs.files._http.request.call_args.kwargs["headers"] + assert headers["Content-Range"] == "bytes */10" + assert mocked_fs.files._http.request.call_args.kwargs["body"] is None + + +def test_upload_chunk_unexpected_status_raises(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ({"status": "500"}, b"error") + file = _write_file(fs) + file.write(b"data") + file.offset = 0 + + with pytest.raises(IOError, match=r"Chunk upload failed \(HTTP 500\): error"): + try: + file._upload_chunk(final=False) + finally: + file.closed = True + + +def test_upload_chunk_error_non_utf8_body_raises_ioerror( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ({"status": "503"}, b"\xff\xfe") + file = _write_file(fs) + file.write(b"data") + file.offset = 0 + + with pytest.raises(IOError, match=r"Chunk upload failed \(HTTP 503\)"): + try: + file._upload_chunk(final=False) + finally: + file.closed = True + + +def test_upload_chunk_unexpected_response_raises_ioerror( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ({"status": "204"}, b"") + file = _write_file(fs) + file.write(b"data") + file.offset = 0 + + with pytest.raises(IOError): + try: + file._upload_chunk(final=False) + finally: + file.closed = True + + +def test_commit_finalizes_upload(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + file = _write_file(fs) + file.autocommit = False + + with mock.patch.object(file, "_upload_chunk") as upload: + try: + file.commit() + finally: + file.closed = True + + assert file.autocommit + upload.assert_called_once_with(final=True) + + +def test_discard_noop_without_location(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + file = _write_file(fs) + file.location = None + + try: + file.discard() + finally: + file.closed = True + + mocked_fs.files._http.request.assert_not_called() + + +def test_discard_cancels_resumable_upload(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ({"status": "204"}, b"") + file = _write_file(fs) + file.location = "https://upload.example/resume?upload_id=abc123" + + try: + file.discard() + finally: + file.closed = True + + args, kwargs = mocked_fs.files._http.request.call_args + assert args[0] == ( + "https://upload.example/resume?upload_id=abc123&supportsAllDrives=true" + ) + assert kwargs["method"] == "DELETE" + # Session URI is cleared so a later close() does not re-cancel. + assert file.location is None + + +def test_discard_keeps_existing_supports_all_drives( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ({"status": "204"}, b"") + file = _write_file(fs) + file.location = ( + "https://upload.example/resume?upload_id=abc123&supportsAllDrives=true" + ) + + try: + file.discard() + finally: + file.closed = True + + # The flag is already present; do not append a duplicate. + args, _ = mocked_fs.files._http.request.call_args + assert args[0].count("supportsAllDrives") == 1 + + +def test_discard_accepts_http_499(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + # Google replies 499 to a successful resumable-upload cancellation. + mocked_fs.files._http.request.return_value = ({"status": "499"}, b"") + file = _write_file(fs) + file.location = "https://upload.example/resume?upload_id=abc123" + + try: + file.discard() + finally: + file.closed = True + + assert file.location is None + + +def test_discard_raises_on_failure(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + mocked_fs.files._http.request.return_value = ({"status": "500"}, b"error") + file = _write_file(fs) + file.location = "https://upload.example/resume?upload_id=abc123" + + with pytest.raises(IOError): + try: + file.discard() + finally: + file.closed = True + + +def test_transaction_rollback_discards_once(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + file = _write_file(fs) + tx = fs.transaction + tx.start() + tx.files.append(file) + + with mock.patch.object(file, "discard") as discard: + # A failed transaction rolls back via complete(commit=False). + tx.complete(commit=False) + + discard.assert_called_once_with() + file.closed = True diff --git a/tests/test_core_fs.py b/tests/test_core_fs.py new file mode 100644 index 0000000..68dddfe --- /dev/null +++ b/tests/test_core_fs.py @@ -0,0 +1,789 @@ +"""Unit tests for GoogleDriveFileSystem directory and path operations.""" + +import pathlib +from typing import Any +from unittest import mock + +import pytest +from conftest import MockedDriveFS, empty_files_list_response, empty_listing + +from gdrive_fsspec.core import ( + DIR_MIME_TYPE, + INFO_FIELDS, + ROOT_ID, + GoogleDriveFile, + GoogleDriveFileSystem, + MultipleFilesError, +) +from gdrive_fsspec.utils import merge_fields + + +def test_mkdir_creates_folder_and_updates_dircache(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.exists = mock.Mock(return_value=False) + fs._path_to_id = mock.Mock(return_value="parent-id") + mocked_fs.files.create.return_value.execute.return_value = { + "id": "new-id", + "name": "newfolder", + "mimeType": DIR_MIME_TYPE, + } + fs.dircache["parent"] = empty_listing() + + result = fs.mkdir("parent/newfolder", create_parents=False) + + mocked_fs.files.create.assert_called_once_with( + body={ + "name": "newfolder", + "mimeType": DIR_MIME_TYPE, + "parents": ["parent-id"], + }, + supportsAllDrives=True, + ) + assert result == { + "id": "new-id", + "name": "newfolder", + "mimeType": DIR_MIME_TYPE, + } + assert fs.dircache["parent/newfolder"] == [] + assert fs.dircache["parent"] == [ + { + "id": "new-id", + "name": "parent/newfolder", + "mimeType": DIR_MIME_TYPE, + "size": 0, + "type": "directory", + } + ] + + +def test_mkdir_raises_when_path_exists(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.exists = mock.Mock(return_value=True) + fs._path_to_id = mock.Mock(return_value="parent-id") + + with pytest.raises(FileExistsError): + fs.mkdir("parent/existing", create_parents=False) + + # The existence check short-circuits before the parent id is resolved. + fs._path_to_id.assert_not_called() + mocked_fs.files.create.assert_not_called() + + +def test_mkdir_create_parents_calls_makedirs(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.makedirs = mock.Mock() + fs.exists = mock.Mock(return_value=False) + fs._path_to_id = mock.Mock(return_value="parent-id") + mocked_fs.files.create.return_value.execute.return_value = { + "id": "new-id", + "name": "child", + "mimeType": DIR_MIME_TYPE, + } + + fs.mkdir("parent/child", create_parents=True) + + fs.makedirs.assert_called_once_with("parent", exist_ok=True) + + +def test_mkdir_skips_parent_creation_at_root(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.makedirs = mock.Mock() + fs.exists = mock.Mock(return_value=False) + fs.root_file_id = "root-id" + mocked_fs.files.create.return_value.execute.return_value = { + "id": "new-id", + "name": "top", + "mimeType": DIR_MIME_TYPE, + } + + fs.mkdir("top", create_parents=True) + + fs.makedirs.assert_not_called() + + +def test_makedirs_creates_missing_segments(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.exists = mock.Mock(side_effect=[False, False, True]) + fs.mkdir = mock.Mock() + + fs.makedirs("a/b/c", exist_ok=True) + + assert fs.mkdir.call_count == 2 + fs.mkdir.assert_any_call("a", create_parents=False) + fs.mkdir.assert_any_call("a/b", create_parents=False) + + +def test_makedirs_exist_ok_false_raises(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.exists = mock.Mock(side_effect=[True, True]) + + with pytest.raises(FileExistsError): + fs.makedirs("a/b", exist_ok=False) + + +def _deletable_info(**extra: Any) -> dict[str, Any]: + """A file-info dict for a file the caller may permanently delete.""" + return {"id": "file-id", "capabilities": {"canDelete": True}, **extra} + + +def _trashable_info(**extra: Any) -> dict[str, Any]: + """A file-info dict for a file the caller may move to trash.""" + return {"id": "file-id", "capabilities": {"canTrash": True}, **extra} + + +def test_rm_file_trashes_and_updates_dircache(mocked_fs: MockedDriveFS) -> None: + # rm defaults to trash (files.update trashed=True), matching the Drive UI. + fs = mocked_fs.fs + fs.info = mock.Mock(return_value=_trashable_info()) + fs.dircache["parent"] = [{"name": "parent/file", "id": "file-id"}] + fs.dircache["parent/file"] = empty_listing() + + fs.rm_file("parent/file") + + mocked_fs.files.update.assert_called_once_with( + fileId="file-id", body={"trashed": True}, supportsAllDrives=True + ) + mocked_fs.files.delete.assert_not_called() + assert fs.dircache["parent"] == [] + assert "parent/file" not in fs.dircache + + +def test_rm_permanent_deletes_and_updates_dircache(mocked_fs: MockedDriveFS) -> None: + # permanent=True hard-deletes via files.delete instead of trashing. + fs = mocked_fs.fs + fs.info = mock.Mock(return_value=_deletable_info()) + fs.dircache["parent"] = [{"name": "parent/file", "id": "file-id"}] + fs.dircache["parent/file"] = empty_listing() + + fs.rm("parent/file", permanent=True) + + mocked_fs.files.delete.assert_called_once_with( + fileId="file-id", supportsAllDrives=True + ) + mocked_fs.files.update.assert_not_called() + assert fs.dircache["parent"] == [] + assert "parent/file" not in fs.dircache + + +def test_rm_requests_capabilities_and_drive_id(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.info = mock.Mock(return_value=_trashable_info()) + + fs._rm("parent/file") + + # Both capability signals must be resolved in the same info() call, not a + # separate follow-up request. + fs.info.assert_called_once_with( + "parent/file", + fields="driveId,capabilities/canDelete,capabilities/canTrash", + ) + + +def test_rm_no_trash_permission_raises(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.info = mock.Mock( + return_value={"id": "file-id", "capabilities": {"canTrash": False}} + ) + + with pytest.raises(PermissionError, match="Trash"): + fs._rm("parent/file") + + # Nothing is trashed when the capability check fails. + mocked_fs.files.update.assert_not_called() + + +def test_rm_permanent_no_delete_permission_on_shared_drive_raises_with_role_hint( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + fs.info = mock.Mock( + return_value={ + "id": "file-id", + "driveId": "drive-1", + "capabilities": {"canDelete": False}, + } + ) + + with pytest.raises(PermissionError, match="Manager access"): + fs._rm("parent/file", permanent=True) + + # Nothing is deleted when the capability check fails. + mocked_fs.files.delete.assert_not_called() + + +def test_rm_permanent_no_delete_permission_on_my_drive_omits_shared_drive_advice( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + # No driveId β†’ a My Drive file; the shared-drive role hint would mislead. + fs.info = mock.Mock( + return_value={"id": "file-id", "capabilities": {"canDelete": False}} + ) + + with pytest.raises(PermissionError) as excinfo: + fs._rm("parent/file", permanent=True) + + assert "shared drives" not in str(excinfo.value) + mocked_fs.files.delete.assert_not_called() + + +def test_rm_permanent_missing_capabilities_treated_as_not_deletable( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + # Absent capabilities block deletion rather than risk a masked-404 failure. + fs.info = mock.Mock(return_value={"id": "file-id"}) + + with pytest.raises(PermissionError): + fs._rm("parent/file", permanent=True) + + mocked_fs.files.delete.assert_not_called() + + +def test_rm_missing_file_raises_file_not_found(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + # info() surfaces a genuinely missing file before the capability check. + fs.info = mock.Mock(side_effect=FileNotFoundError("parent/file")) + + with pytest.raises(FileNotFoundError): + fs._rm("parent/file") + + mocked_fs.files.delete.assert_not_called() + mocked_fs.files.update.assert_not_called() + + +def test_rm_non_empty_folder_without_recursive_raises( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + fs.isdir = mock.Mock(return_value=True) + fs.ls = mock.Mock(return_value=["child"]) + + with pytest.raises(ValueError, match="non-empty"): + fs.rm("folder", recursive=False) + + # The guard must fire before any Drive delete is issued. + mocked_fs.files.delete.assert_not_called() + mocked_fs.files.update.assert_not_called() + + +def test_rm_root_raises_value_error(mocked_fs: MockedDriveFS) -> None: + # Deleting the root must fail clearly, not with a misleading PermissionError. + fs = mocked_fs.fs + + with pytest.raises(ValueError, match="root"): + fs._rm("") + + mocked_fs.files.delete.assert_not_called() + mocked_fs.files.update.assert_not_called() + + +def test_rm_trashes_file(mocked_fs: MockedDriveFS) -> None: + # rm -> _rm (our override) -> files.update (trash by default). + fs = mocked_fs.fs + fs.isdir = mock.Mock(return_value=False) + fs.info = mock.Mock(return_value=_trashable_info()) + + fs.rm("file.txt") + + mocked_fs.files.update.assert_called_once_with( + fileId="file-id", body={"trashed": True}, supportsAllDrives=True + ) + + +def test_rmdir_requires_directory(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.isdir = mock.Mock(return_value=False) + + with pytest.raises(ValueError, match="not a directory"): + fs.rmdir("file.txt") + + +def test_rmdir_trashes_empty_directory(mocked_fs: MockedDriveFS) -> None: + # rmdir -> rm -> _rm (our override) -> files.update (trash by default). + fs = mocked_fs.fs + fs.isdir = mock.Mock(return_value=True) + fs.ls = mock.Mock(return_value=[]) + fs.info = mock.Mock(return_value=_trashable_info(id="dir-id")) + + fs.rmdir("empty") + + mocked_fs.files.update.assert_called_once_with( + fileId="dir-id", body={"trashed": True}, supportsAllDrives=True + ) + + +def test_rmdir_permanent_forwards_flag(mocked_fs: MockedDriveFS) -> None: + # permanent=True must thread through rmdir -> rm -> _rm to files.delete. + fs = mocked_fs.fs + fs.isdir = mock.Mock(return_value=True) + fs.ls = mock.Mock(return_value=[]) + fs.info = mock.Mock(return_value=_deletable_info(id="dir-id")) + + fs.rmdir("empty", permanent=True) + + mocked_fs.files.delete.assert_called_once_with( + fileId="dir-id", supportsAllDrives=True + ) + mocked_fs.files.update.assert_not_called() + + +def test_ls_from_dircache_returns_sorted_names( + anon_fs: GoogleDriveFileSystem, +) -> None: + anon_fs.dircache["parent"] = [ + {"name": "parent/b", "type": "file"}, + {"name": "parent/a", "type": "file"}, + ] + + assert anon_fs.ls("parent") == ["parent/a", "parent/b"] + + +def test_ls_from_dircache_detail(anon_fs: GoogleDriveFileSystem) -> None: + listing = [{"name": "parent/a", "type": "file"}] + anon_fs.dircache["parent"] = listing + + assert anon_fs.ls("parent", detail=True) == listing + + +def test_ls_nested_directory(anon_fs: GoogleDriveFileSystem) -> None: + def list_by_id( + file_id: str, + trashed: bool = False, + path_prefix: str | None = None, + fields: str | None = None, + ) -> list[dict[str, Any]]: + if file_id == "root": + return [ + { + "name": "parent", + "id": "parent-id", + "type": "directory", + "mimeType": DIR_MIME_TYPE, + } + ] + if file_id == "parent-id": + return [ + { + "name": "parent/child.txt", + "id": "child-id", + "type": "file", + "mimeType": "text/plain", + } + ] + return [] + + anon_fs.root_file_id = "root" + anon_fs._list_directory_by_id = mock.Mock(side_effect=list_by_id) + + assert anon_fs.ls("parent") == ["parent/child.txt"] + assert anon_fs.dircache["parent"] == [ + { + "name": "parent/child.txt", + "id": "child-id", + "type": "file", + "mimeType": "text/plain", + } + ] + + +def test_ls_nested_file_resolves_via_parent_listing( + anon_fs: GoogleDriveFileSystem, +) -> None: + anon_fs.dircache["parent"] = [ + { + "name": "parent/child.txt", + "id": "child-id", + "type": "file", + "mimeType": "text/plain", + } + ] + + assert anon_fs.ls("parent/child.txt") == ["parent/child.txt"] + + +def test_info_honors_fields_after_listing_cache_warmed_without_them( + mocked_fs: MockedDriveFS, +) -> None: + """Regression: a warm dircache entry must not satisfy ``info(..., fields=...)``. + + Resolves the file id from the listing cache, then fetches authoritative + metadata via ``files.get``. Before the ``info()`` rewrite, a listing cached + without ``capabilities`` caused ``info(..., fields="capabilities/canDelete")`` + to return stale metadata and ``_rm`` to raise a false ``PermissionError``. + """ + fs = mocked_fs.fs + fs.dircache[""] = [ + { + "name": "file.txt", + "id": "file-id", + "type": "file", + "size": 3, + "mimeType": "text/plain", + } + ] + mocked_fs.files.get.return_value.execute.return_value = { + "id": "file-id", + "name": "file.txt", + "mimeType": "text/plain", + "size": "3", + "capabilities": {"canDelete": True}, + } + + info = fs.info("file.txt", fields="capabilities/canDelete") + + mocked_fs.files.get.assert_called_once_with( + fileId="file-id", + fields=merge_fields(INFO_FIELDS, "capabilities/canDelete"), + supportsAllDrives=True, + ) + assert info == { + "name": "file.txt", + "id": "file-id", + "type": "file", + "size": 3, + "mimeType": "text/plain", + "capabilities": {"canDelete": True}, + } + + +def test_info_without_fields_reuses_listing_entry_without_get( + mocked_fs: MockedDriveFS, +) -> None: + # With no extra fields, the parent listing already carries the full entry, + # so info() must not make a per-file files.get request. + fs = mocked_fs.fs + fs.dircache[""] = [ + { + "name": "file.txt", + "id": "file-id", + "type": "file", + "size": 3, + "mimeType": "text/plain", + } + ] + + info = fs.info("file.txt") + + mocked_fs.files.get.assert_not_called() + assert info["id"] == "file-id" + assert info["type"] == "file" + + +def test_info_empty_fields_uses_listing_fast_path(mocked_fs: MockedDriveFS) -> None: + # A blank mask is equivalent to no extra fields: reuse the listing entry. + fs = mocked_fs.fs + fs.dircache[""] = [ + {"name": "file.txt", "id": "file-id", "type": "file", "mimeType": "text/plain"} + ] + + info = fs.info("file.txt", fields="") + + mocked_fs.files.get.assert_not_called() + assert info["id"] == "file-id" + + +def test_info_ignores_reserved_kwargs_for_files_get( + mocked_fs: MockedDriveFS, +) -> None: + # Forwarded **kwargs must not collide with the explicit files.get args. + fs = mocked_fs.fs + fs.dircache[""] = [ + {"name": "file.txt", "id": "file-id", "type": "file", "mimeType": "text/plain"} + ] + mocked_fs.files.get.return_value.execute.return_value = { + "id": "file-id", + "name": "file.txt", + "mimeType": "text/plain", + "driveId": "drive-1", + } + + info = fs.info( + "file.txt", fields="driveId", supportsAllDrives=False, fileId="bogus" + ) + + _, kwargs = mocked_fs.files.get.call_args + assert kwargs["fileId"] == "file-id" + assert kwargs["supportsAllDrives"] is True + assert info["driveId"] == "drive-1" + + +def test_ls_non_canonical_bypasses_cache_read_and_write( + anon_fs: GoogleDriveFileSystem, +) -> None: + fetched = [{"name": "a", "id": "1", "type": "file", "driveId": "drive-1"}] + anon_fs.dircache[""] = [{"name": "a", "id": "1", "type": "file"}] + anon_fs._list_directory_by_id = mock.Mock(return_value=fetched) + + result = anon_fs.ls("", detail=True, fields="driveId") + + anon_fs._list_directory_by_id.assert_called_once() + assert result[0]["driveId"] == "drive-1" + assert "driveId" not in anon_fs.dircache[""][0] + + anon_fs.dircache.clear() + anon_fs._list_directory_by_id.reset_mock() + + anon_fs.ls("", detail=True, fields="driveId") + + anon_fs._list_directory_by_id.assert_called_once() + assert "" not in anon_fs.dircache + + +def test_ls_fields_without_detail_raises(anon_fs: GoogleDriveFileSystem) -> None: + # Requesting fields with detail=False would silently discard them, since the + # names-only result carries no metadata. Reject the misuse instead. + anon_fs._list_directory_by_id = mock.Mock() + + with pytest.raises(ValueError, match="detail=True"): + anon_fs.ls("", fields="driveId") + + anon_fs._list_directory_by_id.assert_not_called() + + +def test_ls_empty_fields_uses_cache(anon_fs: GoogleDriveFileSystem) -> None: + # A blank mask must not bypass the cache; it means no extra fields. + cached = [{"name": "a", "id": "1", "type": "file"}] + anon_fs.dircache[""] = cached + anon_fs._list_directory_by_id = mock.Mock() + + result = anon_fs.ls("", detail=True, fields="") + + assert result == cached + anon_fs._list_directory_by_id.assert_not_called() + + +def test_ls_skips_cache_when_trashed_requested( + anon_fs: GoogleDriveFileSystem, +) -> None: + canonical = [{"name": "a", "id": "1", "type": "file"}] + anon_fs.dircache[""] = [dict(entry) for entry in canonical] + anon_fs._list_directory_by_id = mock.Mock( + return_value=[{"name": "trashed-a", "id": "2", "type": "file", "trashed": True}] + ) + + result = anon_fs.ls("", detail=True, trashed=True) + + anon_fs._list_directory_by_id.assert_called_once() + assert result[0]["name"] == "trashed-a" + assert anon_fs.dircache[""] == canonical + + +def test_path_to_id_resolves_from_parent_dircache( + anon_fs: GoogleDriveFileSystem, +) -> None: + anon_fs.root_file_id = "root-id" + anon_fs.dircache["parent"] = [ + { + "name": "parent/child.txt", + "id": "child-id", + "type": "file", + "mimeType": "text/plain", + } + ] + + assert anon_fs._path_to_id("") == "root-id" + assert anon_fs._path_to_id("parent/child.txt") == "child-id" + + +def test_path_to_id_missing_raises_file_not_found( + anon_fs: GoogleDriveFileSystem, +) -> None: + anon_fs.dircache["parent"] = [ + {"name": "parent/other", "id": "other-id", "type": "file"} + ] + with pytest.raises(FileNotFoundError): + anon_fs._path_to_id("parent/child") + + +def test_path_to_id_duplicate_raises_multiple_files_error( + anon_fs: GoogleDriveFileSystem, +) -> None: + # Ambiguous resolution must fail, not silently pick one, so callers like the + # write path can refuse to overwrite an arbitrary duplicate. + anon_fs.dircache["parent"] = [ + {"name": "parent/dup", "id": "1", "type": "file"}, + {"name": "parent/dup", "id": "2", "type": "file"}, + ] + with pytest.raises(MultipleFilesError): + anon_fs._path_to_id("parent/dup") + + +def test_resolve_entry_rejects_root(anon_fs: GoogleDriveFileSystem) -> None: + # Root has no parent to list; callers must handle it before resolving. + with pytest.raises(ValueError, match="root"): + anon_fs._resolve_entry("") + + +def test_google_drive_file_normalizes_pathlike(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs._path_to_id = mock.Mock(return_value="file-id") + fs.info = mock.Mock( + return_value={"id": "file-id", "size": 0, "type": "file", "name": "file.txt"} + ) + + opened = GoogleDriveFile(fs, pathlib.PurePosixPath("file.txt"), mode="rb") + + assert opened.path == "file.txt" + fs._path_to_id.assert_called_once_with("file.txt") + + +def test_ls_file_at_root_returns_parent_listing(anon_fs: GoogleDriveFileSystem) -> None: + anon_fs._list_directory_by_id = mock.Mock( + return_value=[ + { + "name": "file.txt", + "id": "file-id", + "type": "file", + "mimeType": "text/plain", + } + ] + ) + + assert anon_fs.ls("file.txt") == ["file.txt"] + + +def test_ls_raises_multiple_files_error(anon_fs: GoogleDriveFileSystem) -> None: + anon_fs._list_directory_by_id = mock.Mock( + return_value=[ + {"name": "dup", "id": "1", "type": "file"}, + {"name": "dup", "id": "2", "type": "file"}, + ] + ) + + with pytest.raises(MultipleFilesError): + anon_fs.ls("dup") + + +def test_list_directory_by_id_paginates(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + list_request = mock.Mock() + list_request.execute.side_effect = [ + {"files": [{"name": "a", "id": "1"}], "nextPageToken": "page-2"}, + {"files": [{"name": "b", "id": "2"}]}, + ] + mocked_fs.files.list.return_value = list_request + + result = fs._list_directory_by_id("folder-id") + + assert len(result) == 2 + assert mocked_fs.files.list.call_count == 2 + assert mocked_fs.files.list.call_args_list[1].kwargs["pageToken"] == "page-2" + + +def test_list_directory_by_id_shared_drive_root_query( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + fs.drive = "drive-123" + list_request = mock.Mock() + list_request.execute.return_value = empty_files_list_response() + mocked_fs.files.list.return_value = list_request + + fs._list_directory_by_id(ROOT_ID) + + query = mocked_fs.files.list.call_args.kwargs["q"] + assert "'drive-123' in parents" in query + assert "trashed = false" in query + + +def test_list_directory_by_id_includes_trashed_when_requested( + mocked_fs: MockedDriveFS, +) -> None: + fs = mocked_fs.fs + list_request = mock.Mock() + list_request.execute.return_value = empty_files_list_response() + mocked_fs.files.list.return_value = list_request + + fs._list_directory_by_id("folder-id", trashed=True) + + query = mocked_fs.files.list.call_args.kwargs["q"] + assert "trashed = false" not in query + + +def test_list_directory_by_id_passes_drive_kwargs(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.drive = "drive-123" + list_request = mock.Mock() + list_request.execute.return_value = empty_files_list_response() + mocked_fs.files.list.return_value = list_request + + fs._list_directory_by_id("folder-id") + + kwargs = mocked_fs.files.list.call_args.kwargs + assert kwargs["driveId"] == "drive-123" + assert kwargs["supportsAllDrives"] is True + + +def test_drives_paginates(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + list_request = mock.Mock() + list_request.execute.side_effect = [ + {"drives": [{"id": "1", "name": "a"}], "nextPageToken": "t"}, + {"drives": [{"id": "2", "name": "b"}]}, + ] + mocked_fs.service.drives.return_value.list.return_value = list_request + + assert fs.drives == [{"id": "1", "name": "a"}, {"id": "2", "name": "b"}] + + +DOC_MIME = "application/vnd.google-apps.document" + + +def _set_export_formats(fs: GoogleDriveFileSystem, formats: dict[str, Any]) -> None: + # export_formats is a cached_property; seed its cache so service.about() is + # not hit during the test. + fs.__dict__["export_formats"] = formats + + +def test_export_streams_via_export_media(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.info = mock.Mock(return_value={"id": "doc-id", "mimeType": DOC_MIME}) + _set_export_formats(fs, {DOC_MIME: ["text/plain", "application/pdf"]}) + request = mock.Mock() + mocked_fs.files.export_media.return_value = request + + def fake_downloader(buffer: Any, req: Any) -> mock.Mock: + assert req is request + downloader = mock.Mock() + # Two chunks, then done; second next_chunk reports completion. + chunks = iter([b"expo", b"rted"]) + + def next_chunk(**_kwargs: Any) -> tuple[mock.Mock, bool]: + buffer.write(next(chunks)) + done = buffer.getvalue() == b"exported" + return mock.Mock(), done + + downloader.next_chunk.side_effect = next_chunk + return downloader + + with mock.patch("gdrive_fsspec.core.MediaIoBaseDownload", fake_downloader): + result = fs.export("doc.gdoc", "text/plain") + + mocked_fs.files.export_media.assert_called_once_with( + fileId="doc-id", mimeType="text/plain" + ) + assert result == b"exported" + + +def test_export_rejects_unsupported_mime_type(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + fs.info = mock.Mock(return_value={"id": "doc-id", "mimeType": DOC_MIME}) + _set_export_formats(fs, {DOC_MIME: ["text/plain", "application/pdf"]}) + + with pytest.raises(ValueError, match="text/plain, application/pdf"): + fs.export("doc.gdoc", "text/doc") + + mocked_fs.files.export_media.assert_not_called() + + +def test_export_formats_queries_about_resource(mocked_fs: MockedDriveFS) -> None: + fs = mocked_fs.fs + expected = {DOC_MIME: ["text/plain"]} + mocked_fs.service.about().get().execute.return_value = {"exportFormats": expected} + + assert fs.export_formats == expected + # cached_property: second access does not re-query + mocked_fs.service.about.reset_mock() + assert fs.export_formats == expected + mocked_fs.service.about.assert_not_called() diff --git a/tests/test_helpers.py b/tests/test_helpers.py new file mode 100644 index 0000000..12b2582 --- /dev/null +++ b/tests/test_helpers.py @@ -0,0 +1,72 @@ +# --------------------------------------------------------------------------- +# Pure helpers +# --------------------------------------------------------------------------- + +import pytest + +from gdrive_fsspec.core import DIR_MIME_TYPE, _finfo_from_response, _normalize_path +from gdrive_fsspec.utils import merge_fields + + +@pytest.mark.parametrize( + "base, extra, expected", + [ + # No extra fields: base is returned unchanged. + ("name,id", None, "name,id"), + ("name,id", "", "name,id"), + # Extra fields are appended. + ("name,id", "driveId", "name,id,driveId"), + # Duplicate tokens across base and extra are dropped, order preserved. + ("name,id,size", "id,driveId", "name,id,size,driveId"), + # Surrounding whitespace and empty tokens are stripped. + ("name, id ", " id ,driveId", "name,id,driveId"), + ("name,id", "driveId,", "name,id,driveId"), + # Nested-field selectors are treated as opaque tokens. + ( + "name,id", + "capabilities/canDelete", + "name,id,capabilities/canDelete", + ), + ], +) +def test_merge_fields(base: str, extra: str | None, expected: str) -> None: + assert merge_fields(base, extra) == expected + + +@pytest.mark.parametrize( + "prefix, name, expected", + [ + ("/a/b/", "c", "/a/b/c"), + ("a/b", "c", "/a/b/c"), + ], +) +def test_normalize_path(prefix: str, name: str, expected: str) -> None: + assert _normalize_path(prefix, name) == expected + + +@pytest.mark.parametrize( + "mime_type, expected_type", + [ + ("text/plain", "file"), + (DIR_MIME_TYPE, "directory"), + ], +) +def test_finfo_from_response_type(mime_type: str, expected_type: str) -> None: + info = _finfo_from_response( + {"name": "child", "mimeType": mime_type}, path_prefix="parent" + ) + assert info["type"] == expected_type + assert info["name"] == "parent/child" + + +def test_finfo_from_response_casts_size() -> None: + assert _finfo_from_response({"name": "x", "size": "12"})["size"] == 12 + + +def test_finfo_from_response_defaults_missing_size() -> None: + assert _finfo_from_response({"name": "x"})["size"] == 0 + + +def test_finfo_from_response_strips_leading_slash() -> None: + info = _finfo_from_response({"name": "f"}, path_prefix="/top") + assert info["name"] == "top/f" diff --git a/tests/test_integration.py b/tests/test_integration.py new file mode 100644 index 0000000..bb72a50 --- /dev/null +++ b/tests/test_integration.py @@ -0,0 +1,572 @@ +# --------------------------------------------------------------------------- +# Integration tests (require live Google Drive credentials) +# +# Run: uv run pytest -v -m integration +# +# Each profile targets a different drive and has different roles. +# Any profile whose variables are unset is skipped, so you can run a subset locally. +# +# Service-account key (shared by every service-account profile): +# GDRIVE_FSSPEC_CREDENTIALS_PATH=/path/to/sa.json # path or JSON string +# +# Per-profile shared-drive targets (name or ID): +# GDRIVE_FSSPEC_DRIVE_FULL_ACCESS=drive-full-access # Manager role +# GDRIVE_FSSPEC_DRIVE_CONTENT_MANAGER=drive-test # Content-manager role +# GDRIVE_FSSPEC_DRIVE_READONLY=drive-readonly # Viewer role +# +# sa_my_drive profile: same key, no shared drive (the SA's own My Drive). +# +# The default ``fs``/``make_fs`` suite runs as the full-access service account +# when GDRIVE_FSSPEC_CREDENTIALS_PATH is set. With it unset, the same suite runs +# as a user via OAuth: a one-time browser login populates the cache and every +# later filesystem reuses it. That OAuth path is skipped in CI (which always has +# the service-account key). Shared-drive-only tests skip under OAuth (My Drive +# has no shared drive). +# --------------------------------------------------------------------------- + +from typing import cast + +import pytest +from conftest import TESTDIR, FsFactory +from googleapiclient.errors import HttpError + +from gdrive_fsspec.core import GoogleDriveFile, GoogleDriveFileSystem + + +def _test_path(name: str) -> str: + return f"{TESTDIR}/{name}" + + +@pytest.mark.integration +def test_simple(fs: GoogleDriveFileSystem) -> None: + assert fs.ls("") + data = b"hello" + filename = _test_path("testfile") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(data) + assert fs.cat(filename) == data + + +@pytest.mark.integration +def test_overwrite_updates_in_place(fs: GoogleDriveFileSystem) -> None: + """Writing to an existing path updates it instead of creating a duplicate.""" + filename = _test_path("overwrite") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"first") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"second longer content") + + entries = fs.ls(TESTDIR, detail=True) + match = [e for e in entries if e["name"] == filename] + assert len(match) == 1, "overwrite created a duplicate child" + assert fs.cat(filename) == b"second longer content" + + +@pytest.mark.integration +def test_overwrite_preserves_file_id(fs: GoogleDriveFileSystem) -> None: + """Overwrite PATCHes the existing file rather than delete-and-recreate.""" + filename = _test_path("overwrite_id") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"v1") + original_id = fs.info(filename)["id"] + + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"v2") + + assert fs.info(filename)["id"] == original_id + assert fs.cat(filename) == b"v2" + + +@pytest.mark.integration +def test_overwrite_updates_live_dircache(fs: GoogleDriveFileSystem) -> None: + """The live dircache reflects an overwrite without re-listing. + + Exercises the in-place dircache update on commit: ``ls`` populates the + cache, the overwrite must replace that entry (not append a second one). + """ + filename = _test_path("overwrite_cache") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"one") + # Populate the dircache for the parent. + fs.ls(TESTDIR, detail=True) + + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"two!") + + entries = fs.ls(TESTDIR, detail=True) # served from cache + match = [e for e in entries if e["name"] == filename] + assert len(match) == 1 + assert match[0]["size"] == 4 + + +@pytest.mark.integration +def test_create_directory(fs: GoogleDriveFileSystem) -> None: + fs.makedirs(_test_path("data")) + fs.makedirs(_test_path("data/bar/baz")) + + assert fs.exists(_test_path("data")) + assert fs.exists(_test_path("data/bar")) + assert fs.exists(_test_path("data/bar/baz")) + + data = b"intermediate path" + with fs.open(_test_path("data/bar/test"), "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(data) + assert fs.cat(_test_path("data/bar/test")) == data + + +@pytest.mark.integration +def test_rm_file_trashes_by_default(fs: GoogleDriveFileSystem) -> None: + # rm defaults to trashing: the file leaves the default listing but is + # recoverable and still resolvable with trashed=True. + filename = _test_path("to_delete") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"gone soon") + + assert fs.exists(filename) + fs.rm(filename) + assert not fs.exists(filename) + # Trashed, not purged: it is still findable when trashed items are included. + assert fs.info(filename, trashed=True)["trashed"] is True + + +@pytest.mark.integration +def test_rm_permanent_removes_file(fs: GoogleDriveFileSystem) -> None: + # permanent=True hard-deletes: the file is gone even from trashed listings. + filename = _test_path("to_purge") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"gone for good") + + assert fs.exists(filename) + fs.rm(filename, permanent=True) + assert not fs.exists(filename) + with pytest.raises(FileNotFoundError): + fs.info(filename, trashed=True) + + +@pytest.mark.integration +def test_rm_missing_file_raises_file_not_found( + fs: GoogleDriveFileSystem, +) -> None: + # Deleting a file that does not exist should surface FileNotFoundError, not a + # raw HttpError. rm resolves the file via info() first, which raises when the + # path is absent. + with pytest.raises(FileNotFoundError): + fs.rm(_test_path("never_existed")) + + +# --------------------------------------------------------------------------- +# Content-manager profile (drive-test): may trash but not permanently delete. +# --------------------------------------------------------------------------- + + +@pytest.mark.integration +def test_content_manager_can_trash(content_manager_fs: GoogleDriveFileSystem) -> None: + # Content managers have write + trash rights, so a normal rm() succeeds. + filename = _test_path("cm_trash") + with content_manager_fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"trash me") + + assert content_manager_fs.exists(filename) + content_manager_fs.rm(filename) + assert not content_manager_fs.exists(filename) + + +@pytest.mark.integration +def test_content_manager_permanent_delete_raises_permission_error( + content_manager_fs: GoogleDriveFileSystem, +) -> None: + # permanent=True checks capabilities.canDelete and raises an actionable + # PermissionError (mentioning Manager access) instead of a masked 404, since + # a content manager lacks the Manager role required to hard-delete. + filename = _test_path("cm_forbidden_delete") + with content_manager_fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"cannot delete me") + + assert content_manager_fs.exists(filename) + with pytest.raises(PermissionError, match="Manager"): + content_manager_fs.rm(filename, permanent=True) + + +# --------------------------------------------------------------------------- +# Read-only profile (drive-readonly): reads succeed, every mutation is denied. +# --------------------------------------------------------------------------- + + +@pytest.mark.integration +def test_readonly_lists_root(readonly_fs: GoogleDriveFileSystem) -> None: + listing = readonly_fs.ls("", detail=True) + assert isinstance(listing, list) + + +@pytest.mark.integration +def test_readonly_write_is_denied(readonly_fs: GoogleDriveFileSystem) -> None: + # Uploads run the resumable-session initiation, which surfaces the 403 as an + # OSError (IOError) rather than a raw HttpError. + with pytest.raises(OSError): + with readonly_fs.open("gdrive_fsspec_readonly_probe", "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"nope") + + +@pytest.mark.integration +def test_readonly_mkdir_is_denied(readonly_fs: GoogleDriveFileSystem) -> None: + # Folder creation goes through the discovery client, so the 403 arrives as + # an HttpError. + with pytest.raises(HttpError): + readonly_fs.mkdir("gdrive_fsspec_readonly_dir") + + +@pytest.mark.integration +def test_readonly_trash_is_denied_for_existing_file( + readonly_fs: GoogleDriveFileSystem, +) -> None: + # A viewer can see files but not trash them. This needs a pre-seeded file in + # the read-only drive (the viewer cannot create one); skip when empty. + entries = readonly_fs.ls("", detail=True) + files = [e for e in entries if e["type"] == "file"] + if not files: + pytest.skip("drive-readonly has no seed file to attempt trashing") + target = files[0]["name"] + with pytest.raises(PermissionError, match="Trash"): + readonly_fs.rm(target) + + +# --------------------------------------------------------------------------- +# Service account without a shared drive: its own My Drive has no storage quota. +# --------------------------------------------------------------------------- + + +@pytest.mark.integration +def test_sa_my_drive_lists_root(sa_my_drive_fs: GoogleDriveFileSystem) -> None: + listing = sa_my_drive_fs.ls("", detail=True) + assert isinstance(listing, list) + + +@pytest.mark.integration +def test_sa_my_drive_upload_exceeds_quota( + sa_my_drive_fs: GoogleDriveFileSystem, +) -> None: + # Service accounts cannot own files in their own My Drive (no quota), so an + # upload must fail rather than silently succeed. + with pytest.raises(OSError): + with sa_my_drive_fs.open("gdrive_fsspec_sa_probe", "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"no quota here") + + +@pytest.mark.integration +@pytest.mark.xfail(reason="dircache not updated correctly after mutations", strict=True) +def test_rm_recursive_deletes_directory_tree(fs: GoogleDriveFileSystem) -> None: + root = _test_path("tree") + fs.makedirs(root + "/a/b") + with fs.open(root + "/a/b/leaf", "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"leaf") + + fs.rm(root, recursive=True) + + # Recursive delete only pops the root listing from dircache; nested + # listings populated during setup may linger until invalidated. + # fs.invalidate_cache() + + assert not fs.exists(root) + assert not fs.exists(root + "/a") + assert not fs.exists(root + "/a/b/leaf") + + +@pytest.mark.integration +def test_rmdir_empty_directory(fs: GoogleDriveFileSystem) -> None: + path = _test_path("empty_dir") + fs.mkdir(path) + + assert fs.exists(path) + fs.rmdir(path) + assert not fs.exists(path) + + +@pytest.mark.integration +def test_rmdir_non_empty_raises(fs: GoogleDriveFileSystem) -> None: + path = _test_path("nonempty_dir") + fs.mkdir(path) + with fs.open(path + "/child", "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"x") + + with pytest.raises(ValueError, match="non-empty"): + fs.rmdir(path) + + +@pytest.mark.integration +def test_read_with_seek(fs: GoogleDriveFileSystem) -> None: + data = b"0123456789abcdef" + filename = _test_path("seekable") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(data) + + with fs.open(filename, "rb") as f: + f.seek(4) + assert f.read(4) == b"4567" + assert f.read(2) == b"89" + + +@pytest.mark.integration +def test_multiblock_upload(fs: GoogleDriveFileSystem) -> None: + """Resumable upload across multiple chunks. + + With the 5 MiB default block size every write fits in a single chunk, so + the 308-continuation loop in ``_upload_chunk`` (and its ``Content-Range: + bytes X-Y/*`` wildcard) is otherwise never exercised live. A small block + size forces several chunks plus the final commit. + """ + # Several full blocks plus a partial trailing block. + block_size = 256 * 1024 # minimum Drive accepts is a 256 KiB multiple + data = b"abcd" * (block_size // 4 * 3 + 7) + fn = _test_path("multiblock") + with fs.open(fn, "wb", block_size=block_size) as f: + # pyrefly: ignore [bad-argument-type] + f.write(data) + + assert fs.cat(fn) == data + assert fs.info(fn)["size"] == len(data) + + +@pytest.mark.integration +def test_transaction_rollback_discards_upload(fs: GoogleDriveFileSystem) -> None: + """A failed transaction cancels an in-progress resumable upload. + + This is the path that was previously broken: rollback calls + ``GoogleDriveFile.discard()``, which issues the resumable-session DELETE. + The upload must have actually started (a block flushed, so a session URI + exists) for the cancel to do real work, hence the small block size and a + payload larger than one block. + """ + block_size = 256 * 1024 + data = b"z" * (block_size * 2) + fn = _test_path("rolled_back") + + class Boom(RuntimeError): + pass + + with pytest.raises(Boom): + with fs.transaction: + f = cast( + GoogleDriveFile, + fs.open(fn, "wb", block_size=block_size, autocommit=False), + ) + try: + f.write(data) # flushes β‰₯1 block β†’ opens the resumable session + assert f.location is not None, "expected an open upload session" + raise Boom("abort before commit") + finally: + f.closed = True + + # discard() clears location only after a successful DELETE/499, so this + # proves the rollback actually cancelled the session (not merely that the + # file was never committed, which a leaked session would also satisfy). + assert f.location is None, "rollback should cancel the resumable session" + # The aborted upload must not have produced a committed file. + assert not fs.exists(fn) + + +@pytest.mark.integration +def test_discard_after_partial_write(fs: GoogleDriveFileSystem) -> None: + """Directly cancelling a started upload leaves no committed file. + + Exercises ``discard()`` end-to-end against the live API (DELETE on the + session URI, accepting Google's 499) without relying on the transaction + machinery. + """ + block_size = 256 * 1024 + fn = _test_path("discarded") + f = cast( + GoogleDriveFile, + fs.open(fn, "wb", block_size=block_size, autocommit=False), + ) + try: + f.write(b"q" * (block_size + 1)) # start the session + assert f.location is not None + f.discard() + assert f.location is None # cleared after a successful cancel + finally: + f.closed = True + + assert not fs.exists(fn) + + +@pytest.mark.integration +def test_ls_detail_includes_metadata(fs: GoogleDriveFileSystem) -> None: + filename = _test_path("detail_check") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"meta") + + entries = fs.ls(TESTDIR, detail=True) + match = [e for e in entries if e["name"] == filename] + assert len(match) == 1 + assert match[0]["type"] == "file" + assert match[0]["size"] == 4 + assert "id" in match[0] + + +@pytest.mark.integration +def test_nested_ls_lists_children(fs: GoogleDriveFileSystem) -> None: + parent = _test_path("nested_parent") + fs.mkdir(parent) + with fs.open(parent + "/child.txt", "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"child") + + names = fs.ls(parent) + assert parent + "/child.txt" in names + + +@pytest.mark.integration +def test_root_file_id_rejects_file( + fs: GoogleDriveFileSystem, make_fs: FsFactory +) -> None: + """A regular file ID must not be accepted as the filesystem root.""" + filename = _test_path("root_is_a_file") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"x") + file_id = fs.info(filename)["id"] + + with pytest.raises(NotADirectoryError): + make_fs(root_file_id=file_id) + + +@pytest.mark.integration +def test_root_file_id_accepts_folder( + fs: GoogleDriveFileSystem, make_fs: FsFactory +) -> None: + """A folder ID is a valid root and lists its children from ``ls("")``.""" + folder = _test_path("root_folder") + fs.mkdir(folder) + with fs.open(folder + "/child", "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"data") + folder_id = fs.info(folder)["id"] + + rooted = make_fs(root_file_id=folder_id) + names = [item["name"] for item in rooted.ls("", detail=True)] + assert "child" in names + + +@pytest.mark.integration +def test_root_file_id_scoped_to_shared_drive( + fs: GoogleDriveFileSystem, + make_fs: FsFactory, + requires_shared_drive: None, +) -> None: + """A folder inside the configured shared drive works as ``root_file_id``.""" + folder = _test_path("scoped_root") + fs.mkdir(folder) + folder_id = fs.info(folder)["id"] + + rooted = make_fs(root_file_id=folder_id) + assert rooted.root_file_id == folder_id + assert rooted.ls("") == [] + + +@pytest.mark.integration +def test_shared_drive_root_lists( + make_fs: FsFactory, + requires_shared_drive: None, +) -> None: + """Listing ``ls("")`` at the shared-drive root succeeds.""" + drive_fs = make_fs() + listing = drive_fs.ls("") + assert isinstance(listing, list) + + +@pytest.mark.integration +def test_info_returns_directory_for_root(fs: GoogleDriveFileSystem) -> None: + info = fs.info("") + assert info["type"] == "directory" + assert info["size"] == 0 + assert info["id"] == fs.root_file_id + + +@pytest.mark.integration +def test_info_honors_fields_with_warm_listing_cache( + fs: GoogleDriveFileSystem, +) -> None: + """``info(fields=...)`` must fetch from the API, not stale ``ls`` dircache.""" + filename = _test_path("info_fields") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"x") + + fs.ls(TESTDIR, detail=True) + cached = next(e for e in fs.dircache[TESTDIR] if e["name"] == filename) + assert "capabilities" not in cached + + info = fs.info(filename, fields="capabilities/canDelete") + assert info.get("capabilities", {}).get("canDelete") is True + + +@pytest.mark.integration +def test_ls_with_fields_bypasses_stale_cache(fs: GoogleDriveFileSystem) -> None: + """``ls(..., fields=...)`` must refetch when the canonical cache lacks fields.""" + filename = _test_path("ls_fields") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"abc") + + fs.ls(TESTDIR, detail=True) + cached = next(e for e in fs.dircache[TESTDIR] if e["name"] == filename) + assert "capabilities" not in cached + + entries = fs.ls(TESTDIR, detail=True, fields="capabilities/canDelete") + match = [e for e in entries if e["name"] == filename] + assert len(match) == 1 + capabilities = match[0]["capabilities"] + assert isinstance(capabilities, dict) + assert capabilities["canDelete"] is True + + +@pytest.mark.integration +def test_ls_with_fields_does_not_overwrite_canonical_cache( + fs: GoogleDriveFileSystem, +) -> None: + """Non-canonical ``ls`` reads fresh data but leaves the default dircache unchanged.""" + filename = _test_path("ls_no_cache_pollution") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"x") + + fs.ls(TESTDIR, detail=True) + before = next(e for e in fs.dircache[TESTDIR] if e["name"] == filename) + + fs.ls(TESTDIR, detail=True, fields="capabilities/canDelete") + + after = next(e for e in fs.dircache[TESTDIR] if e["name"] == filename) + assert after == before + assert "capabilities" not in after + + +@pytest.mark.integration +def test_rm_succeeds_after_exists_warmed_cache(fs: GoogleDriveFileSystem) -> None: + """Regression: ``exists()`` warming dircache must not cause a false ``PermissionError`` on ``rm``.""" + filename = _test_path("rm_after_exists") + with fs.open(filename, "wb") as f: + # pyrefly: ignore [bad-argument-type] + f.write(b"delete me") + + assert fs.exists(filename) + fs.rm(filename) + + assert not fs.exists(filename)