Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .generator/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ WORKDIR /app
# TODO(https://github.com/googleapis/librarian/issues/906): Clone googleapis and run bazelisk build.

# Copy the CLI script into the container and set ownership.
# No other files or dependencies are needed for this simple script.
COPY cli.py .
COPY .generator/cli.py .

# Set the entrypoint for the container to run the script.
ENTRYPOINT ["python3.13", "./cli.py"]
32 changes: 32 additions & 0 deletions .generator/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,45 @@

import argparse
import sys
import json
import os
import logging

logger = logging.getLogger()

LIBRARIAN = "/librarian"

# Helper function that reads a json file path and returns the loaded json content.
# Remove me.
def _read_json_file(path):
if not os.path.exists(path):
raise FileNotFoundError(f"Request file not found at '{path}'")
try:
with open(path, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
raise ValueError(f"Invalid JSON in request file '{path}'")
except IOError as e:
raise IOError(f"Invalid JSON in request file '{path}': {e}")


def handle_configure(dry_run=False):
# TODO(https://github.com/googleapis/librarian/issues/466): Implement configure command.
print("'configure' command executed.")

def handle_generate(dry_run=False):
# TODO(https://github.com/googleapis/librarian/issues/448): Implement generate command.

# Read a generate-request.json file
request_path = f"{LIBRARIAN}/generate-request.json"
try:
request_data = _read_json_file(request_path)
except Exception as e:
logger.error(e)
sys.exit(1)

# Print the data:
print(json.dumps(request_data, indent=2))
print("'generate' command executed.")

def handle_build(dry_run=False):
Expand Down
16 changes: 16 additions & 0 deletions .generator/requirements-test.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

pytest
pytest-mock
39 changes: 38 additions & 1 deletion .generator/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from cli import handle_generate, handle_build, handle_configure
import pytest
import json

from cli import _read_json_file, handle_generate, handle_build, handle_configure


def test_handle_configure_dry_run():
Expand All @@ -26,3 +29,37 @@ def test_handle_generate_dry_run():
def test_handle_build_dry_run():
# This is a simple test to ensure that the dry run command succeeds.
handle_build(dry_run=True)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a test_handle_generate() that, for right now, checks that the printed output matches the input file (probably simplest to ignore formatting in both the input and output; just canonicalize the order of the elements before comparing)

def test_read_valid_json(mocker):
"""Tests reading a valid JSON file."""
mock_content = '{"key": "value"}'
mocker.patch("os.path.exists", return_value=True)
mocker.patch("builtins.open", mocker.mock_open(read_data=mock_content))
result = _read_json_file("fake/path.json")
assert result == {"key": "value"}

def test_file_not_found(mocker):
"""Tests behavior when the file does not exist."""
mocker.patch("os.path.exists", return_value=False)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Modify if you remove the exists check

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my comment above.


with pytest.raises(FileNotFoundError):
_read_json_file("non/existent/path.json")

def test_invalid_json(mocker):
"""Tests reading a file with malformed JSON."""
mock_content = '{"key": "value",}'
mocker.patch("os.path.exists", return_value=True)
mocker.patch("builtins.open", mocker.mock_open(read_data=mock_content))

with pytest.raises(ValueError, match="Invalid JSON"):
_read_json_file("fake/path.json")

def test_io_error_on_read(mocker):
"""Tests for a generic IOError."""
mocker.patch("os.path.exists", return_value=True)
mocked_open = mocker.mock_open()
mocked_open.side_effect = IOError("Permission denied")
mocker.patch("builtins.open", mocked_open)

with pytest.raises(IOError, match="Permission denied"):
_read_json_file("fake/path.json")
10 changes: 10 additions & 0 deletions .librarian/generate-request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real generation requests will go in this path, correct? So this actual file is just test data? If so; I suggest

  • place this file under some sort of test directory (call it $LIBRARIAN_TEST_DIR in this discussion)
  • configure the CLI to set the variable $LIBRARIAN to the value of the environment variable $LIBRARIAN_DIR if it exists, or otherwise the default you already have
  • when you run test_handle_generate, set $LIBRARIAN_DIR to have the value of $LIBRARIAN_TEST_DIR so it reads the input from the test dir.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've addressed this comment. However, my initial intention was to remove this file once we complete the work since we don't need it (i.e. we only need it for local testing). We won't be testing bazelisk commands in our unit tests. Let me know what you think.

"id": "google-cloud-language",
"apis": [
{
"path": "google/cloud/language/v1",
"service_config": "language.yaml"
}
]
}

28 changes: 28 additions & 0 deletions cloudbuild.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

steps:
# This step builds the Docker image.
- name: 'gcr.io/cloud-builders/docker'
args:
- 'build'
- '-t'
- 'gcr.io/$PROJECT_ID/python-librarian-generator:latest'
- '-f'
- '.generator/Dockerfile'
- '.'

# This section solves the logging error by automatically creating a bucket.
options:
default_logs_bucket_behavior: REGIONAL_USER_OWNED_BUCKET
Loading