Skip to content

Conversation

@BaptisteGi
Copy link
Contributor

@BaptisteGi BaptisteGi commented Dec 29, 2025

  • Documentation

    • Updated Python SDK guide with revised workflow examples for generating Pydantic models from GraphQL queries using a directory-based approach and enhanced step-by-step guidance.
  • Improvements for generate-return-types ctl command

    • Support for __typename in queries
    • Support queries in current folder

Summary by CodeRabbit

  • Documentation

    • Updated Python SDK typing guide with a directory-based workflow, clearer step-by-step examples, schema export guidance, and a warning about unique query filenames.
  • Improvements

    • Code generation now strips GraphQL __typename fields from operations and fragments before generating models.
  • Tests

    • Added extensive unit and integration tests covering query discovery, parsing, generation flows, and typename-stripping behavior.
  • Fixtures / Schema

    • Added GraphQL fixtures and a self-contained schema for tag-related types to support tests.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 29, 2025

Walkthrough

Strips __typename fields from GraphQL selection sets, operations, and fragments by adding three AST-transform functions and applying them before code generation. The generation flow uses the stripped fragments and operations and falls back to package name "graphql_client" when a directory has no name. Documentation for the Python SDK guide was revised to prefer a queries/ directory, update example query and model names, and add stepwise guidance and warnings. New unit tests and fixtures were added to validate typename-stripping behavior, file discovery, query parsing, CLI generation flows, and schema/query edge cases.

Pre-merge checks

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'Fix issue #713 and #712' is vague and does not convey the actual changes made (documentation updates, typename stripping, and directory-based workflow support). Consider revising the title to be more descriptive, such as 'Add directory support and typename stripping to generate-return-types command' to better reflect the main changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Dec 29, 2025

Codecov Report

❌ Patch coverage is 92.30769% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/graphql/utils.py 90.90% 1 Missing and 1 partial ⚠️
@@            Coverage Diff             @@
##           stable     #714      +/-   ##
==========================================
+ Coverage   76.03%   76.84%   +0.80%     
==========================================
  Files         113      113              
  Lines        9744     9768      +24     
  Branches     1491     1497       +6     
==========================================
+ Hits         7409     7506      +97     
+ Misses       1840     1757      -83     
- Partials      495      505      +10     
Flag Coverage Δ
integration-tests 34.60% <19.23%> (-0.05%) ⬇️
python-3.10 50.80% <92.30%> (+0.84%) ⬆️
python-3.11 50.82% <92.30%> (+0.87%) ⬆️
python-3.12 50.78% <92.30%> (+0.87%) ⬆️
python-3.13 50.80% <92.30%> (+0.87%) ⬆️
python-3.14 52.44% <92.30%> (+0.84%) ⬆️
python-filler-3.12 23.88% <0.00%> (-0.06%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
infrahub_sdk/ctl/graphql.py 88.54% <100.00%> (+53.43%) ⬆️
infrahub_sdk/graphql/utils.py 73.80% <90.90%> (+53.80%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Dec 29, 2025

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: f96fb55
Status: ✅  Deploy successful!
Preview URL: https://eee8b025.infrahub-sdk-python.pages.dev
Branch Preview URL: https://bgi-fix-713.infrahub-sdk-python.pages.dev

View logs

@github-actions github-actions bot added the type/documentation Improvements or additions to documentation label Dec 29, 2025
@BaptisteGi BaptisteGi marked this pull request as ready for review December 29, 2025 10:58
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/unit/ctl/test_graphql_utils.py (1)

1-242: Comprehensive test coverage with excellent structure.

The tests thoroughly validate the typename-stripping functionality across various GraphQL query structures, including edge cases like inline fragments, aliases, arguments, and directives. All tests follow best practices with clear naming and proper type hints.

However, consider relocating this test file to better align with the module structure:

Current location: tests/unit/ctl/test_graphql_utils.py
Module being tested: infrahub_sdk.graphql.utils
Recommended location: tests/unit/graphql/test_utils.py

Test files should mirror the source module structure rather than where the functionality is used. This improves discoverability and maintains consistency in the test organization.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f1cb0c and df7d5e8.

📒 Files selected for processing (4)
  • docs/docs/python-sdk/guides/python-typing.mdx
  • infrahub_sdk/ctl/graphql.py
  • infrahub_sdk/graphql/utils.py
  • tests/unit/ctl/test_graphql_utils.py
🧰 Additional context used
📓 Path-based instructions (8)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Use type hints on all function signatures
Never mix async/sync inappropriately
Never bypass type checking without justification

Files:

  • infrahub_sdk/graphql/utils.py
  • tests/unit/ctl/test_graphql_utils.py
  • infrahub_sdk/ctl/graphql.py
infrahub_sdk/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

Follow async/sync dual pattern for new features in the Python SDK

Files:

  • infrahub_sdk/graphql/utils.py
  • infrahub_sdk/ctl/graphql.py
**/*.{md,mdx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{md,mdx}: Use text language for directory structure code blocks in markdown documentation
Add blank lines before and after lists in markdown documentation
Always specify language in fenced code blocks in markdown documentation

Files:

  • docs/docs/python-sdk/guides/python-typing.mdx
docs/docs/**/*.mdx

📄 CodeRabbit inference engine (docs/AGENTS.md)

docs/docs/**/*.mdx: Create MDX files in appropriate directory within docs structure (guides, topics, or reference)
Add frontmatter with title field to MDX documentation files
Use callouts (:::warning, :::note, etc.) for important notes and information in documentation

Files:

  • docs/docs/python-sdk/guides/python-typing.mdx
docs/docs/python-sdk/{guides,topics}/**/*.mdx

📄 CodeRabbit inference engine (docs/AGENTS.md)

docs/docs/python-sdk/{guides,topics}/**/*.mdx: Use Tabs component from '@theme/Tabs' for async/sync examples in documentation
Include both async/sync examples using Tabs in documentation

Files:

  • docs/docs/python-sdk/guides/python-typing.mdx
tests/**/*.py

📄 CodeRabbit inference engine (tests/AGENTS.md)

tests/**/*.py: Use httpx_mock fixture for HTTP mocking in tests instead of making real HTTP requests
Do not add @pytest.mark.asyncio decorator to async test functions (async auto-mode is globally enabled)

Files:

  • tests/unit/ctl/test_graphql_utils.py
tests/unit/**/*.py

📄 CodeRabbit inference engine (tests/AGENTS.md)

Unit tests must be fast, mocked, and have no external dependencies

Files:

  • tests/unit/ctl/test_graphql_utils.py
infrahub_sdk/ctl/**/*.py

📄 CodeRabbit inference engine (infrahub_sdk/ctl/AGENTS.md)

infrahub_sdk/ctl/**/*.py: Use @catch_exception(console=console) decorator on all async CLI commands
Include CONFIG_PARAM in all CLI command function parameters, even if unused
Use initialize_client() or initialize_client_sync() from ctl.client for client creation in CLI commands
Use Rich library for output formatting in CLI commands (tables, panels, console.print) instead of plain print() statements
Do not instantiate InfrahubClient directly; always use initialize_client() or initialize_client_sync() helper functions
Do not use plain print() statements in CLI commands; use Rich console.print() instead

Files:

  • infrahub_sdk/ctl/graphql.py
🧠 Learnings (2)
📚 Learning: 2025-12-10T17:13:14.678Z
Learnt from: CR
Repo: opsmill/infrahub-sdk-python PR: 0
File: docs/AGENTS.md:0-0
Timestamp: 2025-12-10T17:13:14.678Z
Learning: Applies to docs/python-sdk/reference/config.mdx : Do not edit `docs/python-sdk/reference/config.mdx` directly; regenerate with `uv run invoke generate-sdk` instead

Applied to files:

  • docs/docs/python-sdk/guides/python-typing.mdx
📚 Learning: 2025-12-10T17:13:21.977Z
Learnt from: CR
Repo: opsmill/infrahub-sdk-python PR: 0
File: infrahub_sdk/ctl/AGENTS.md:0-0
Timestamp: 2025-12-10T17:13:21.977Z
Learning: Applies to infrahub_sdk/ctl/**/*.py : Use `initialize_client()` or `initialize_client_sync()` from ctl.client for client creation in CLI commands

Applied to files:

  • infrahub_sdk/ctl/graphql.py
🧬 Code graph analysis (2)
tests/unit/ctl/test_graphql_utils.py (1)
infrahub_sdk/graphql/utils.py (3)
  • strip_typename_from_fragment (72-84)
  • strip_typename_from_operation (57-69)
  • strip_typename_from_selection_set (14-54)
infrahub_sdk/ctl/graphql.py (1)
infrahub_sdk/graphql/utils.py (4)
  • insert_fragments_inline (96-114)
  • remove_fragment_import (117-123)
  • strip_typename_from_fragment (72-84)
  • strip_typename_from_operation (57-69)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: integration-tests-latest-infrahub
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (10)
infrahub_sdk/ctl/graphql.py (4)

25-30: LGTM! Clean imports for typename stripping utilities.

The imports are well-organized and bring in the necessary utilities for stripping __typename fields from GraphQL operations and fragments.


160-164: Excellent explanation and implementation of typename stripping.

The comment clearly explains why __typename must be removed (ariadne-codegen validation issue), and the implementation correctly applies the stripping functions to both queries and fragments before code generation.


168-168: LGTM! Consistent use of stripped operations and fragments.

The stripped versions are correctly passed to the package generator and used in the iteration loop, maintaining consistency throughout the code generation flow.

Also applies to: 180-180


171-171: Good defensive programming with the fallback value.

The fallback to "graphql_client" when directory.name is empty/falsy prevents potential issues with unnamed directories.

docs/docs/python-sdk/guides/python-typing.mdx (2)

114-114: LGTM! Documentation accurately reflects the updated workflow.

The changes clearly document the directory-based approach for generating Pydantic models and include the schema export step, providing better guidance to users.

Also applies to: 123-130


134-170: Excellent structured workflow with helpful warnings.

The numbered steps provide clear guidance, and the warning callout appropriately alerts users to the potential file-naming conflicts when queries share names. The example code is complete and practical.

infrahub_sdk/graphql/utils.py (4)

3-11: LGTM! Necessary imports for GraphQL AST manipulation.

All required GraphQL AST node types are imported for the typename-stripping functionality.


14-54: Excellent implementation of recursive typename stripping.

The function correctly:

  • Handles the None case early
  • Skips __typename fields while preserving all other fields
  • Recursively processes nested selection sets
  • Preserves all node attributes (aliases, arguments, directives)
  • Handles inline fragments and fragment spreads appropriately
  • Returns a new immutable SelectionSetNode

The docstring clearly explains the motivation (ariadne-codegen's inability to look up __typename in the schema).


57-69: LGTM! Clean operation wrapper for typename stripping.

The function properly creates a new OperationDefinitionNode with a stripped selection set while preserving all other operation attributes.


72-84: LGTM! Clean fragment wrapper for typename stripping.

The function properly creates a new FragmentDefinitionNode with a stripped selection set while preserving all fragment attributes.

Copy link
Contributor

@ajtmccarty ajtmccarty left a comment

Choose a reason for hiding this comment

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

not sure exactly how much testing we have for infrahubctl commands, but it would be good to have a test for this that actually calls generate_return_types

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/unit/ctl/test_graphql_app.py (2)

68-103: Invalid-query test is good; message match could be made more future-proof

The invalid query fixture and use of the real schema give good coverage of validation failures. The assertion match="Cannot query field" is reasonable but couples the test to the exact GraphQL error wording; if the underlying GraphQL library ever changes this phrasing, the test may fail even though behavior is still correct. You could consider matching a more generic pattern (e.g., just checking that a ValueError is raised, or matching on the invalid field name) to reduce brittleness, but it's optional.


105-266: CLI tests are comprehensive; a couple of tiny optional assertion improvements

The generate-return-types tests nicely cover:

  • single-file vs directory input
  • missing schema
  • invalid queries (non-fatal)
  • __typename handling
  • default CWD behavior
  • empty directories
  • multiple queries in one directory.

Two small, optional tightenings you might consider:

  • In test_generate_return_types_no_gql_files, the comment mentions “no output”; you could assert result.stdout == "" (or .strip() == "") to capture that contract explicitly.
  • In test_generate_return_types_invalid_query, you already assert "Error" in clean_output; optionally asserting that the invalid filename or query name appears too would make it clearer that the error is tied to the right input.

These are niceties only; the current tests are already quite strong.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 401d1d5 and f96fb55.

📒 Files selected for processing (5)
  • tests/fixtures/unit/test_infrahubctl/graphql/invalid_query.gql
  • tests/fixtures/unit/test_infrahubctl/graphql/query_with_typename.gql
  • tests/fixtures/unit/test_infrahubctl/graphql/test_schema.graphql
  • tests/fixtures/unit/test_infrahubctl/graphql/valid_query.gql
  • tests/unit/ctl/test_graphql_app.py
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Use type hints on all function signatures
Never mix async/sync inappropriately
Never bypass type checking without justification

Files:

  • tests/unit/ctl/test_graphql_app.py
tests/**/*.py

📄 CodeRabbit inference engine (tests/AGENTS.md)

tests/**/*.py: Use httpx_mock fixture for HTTP mocking in tests instead of making real HTTP requests
Do not add @pytest.mark.asyncio decorator to async test functions (async auto-mode is globally enabled)

Files:

  • tests/unit/ctl/test_graphql_app.py
tests/unit/**/*.py

📄 CodeRabbit inference engine (tests/AGENTS.md)

Unit tests must be fast, mocked, and have no external dependencies

Files:

  • tests/unit/ctl/test_graphql_app.py
🧬 Code graph analysis (1)
tests/unit/ctl/test_graphql_app.py (2)
infrahub_sdk/ctl/graphql.py (2)
  • find_gql_files (43-59)
  • get_graphql_query (62-79)
tests/helpers/cli.py (1)
  • remove_ansi_color (4-6)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: unit-tests (3.11)
  • GitHub Check: unit-tests (3.14)
  • GitHub Check: unit-tests (3.10)
  • GitHub Check: unit-tests (3.13)
  • GitHub Check: unit-tests (3.12)
  • GitHub Check: documentation
  • GitHub Check: integration-tests-latest-infrahub
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (5)
tests/fixtures/unit/test_infrahubctl/graphql/invalid_query.gql (1)

1-9: Invalid query fixture correctly exercises validation failures

The query is intentionally invalid against the provided schema and is well-suited for testing error handling in get_graphql_query and the CLI flows. No changes needed.

tests/fixtures/unit/test_infrahubctl/graphql/valid_query.gql (1)

1-15: Valid query fixture aligns with test schema and covers key fields

The GetTags query matches the BuiltinTag schema (arguments and nested fields) and provides a solid happy-path example for parsing and codegen tests. Looks good as-is.

tests/fixtures/unit/test_infrahubctl/graphql/query_with_typename.gql (1)

1-16: Typename-heavy fixture provides good coverage for stripping logic

Including __typename at root, edge, node, and nested field levels is ideal for testing that the typename-stripping utilities and CLI flows handle all nesting cases. No changes needed.

tests/fixtures/unit/test_infrahubctl/graphql/test_schema.graphql (1)

1-47: Schema is coherent and consistent with query fixtures

The schema types and fields (especially Query.BuiltinTag, PaginatedBuiltinTag.edges, and BuiltinTag/TextAttribute) line up cleanly with all the supplied fixtures, providing a solid, self-contained test schema. No issues spotted.

tests/unit/ctl/test_graphql_app.py (1)

19-66: find_gql_files tests exercise core behaviors and edge cases well

The tests cover single-file, directory, nested directory, nonexistent path, and empty-directory scenarios, matching the implementation of find_gql_files closely. Assertions avoid relying on ordering (except for the single-file case, which is deterministic), so this looks solid.

@BaptisteGi BaptisteGi merged commit 25ead97 into stable Dec 30, 2025
21 checks passed
@BaptisteGi BaptisteGi deleted the bgi-fix-713 branch December 30, 2025 08:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type/documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: TypeError: Redefinition of reserved type 'String' - Graphql generate-return-types bug: Provided name cannot be used as python identifier.

3 participants