Skip to content

Add support for passing name to enum_value #3841

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 19, 2025
Merged

Conversation

patrick91
Copy link
Member

@patrick91 patrick91 commented Apr 15, 2025

Summary by Sourcery

Add support for custom names in enum values using the name parameter in strawberry.enum_value

New Features:

  • Introduce ability to specify a custom GraphQL name for enum values that differs from the Python enum member name

Documentation:

  • Update documentation to explain how to use custom enum value names with examples

Tests:

  • Add test cases to verify custom enum value names work for both query output and input scenarios

Copy link
Contributor

sourcery-ai bot commented Apr 15, 2025

Reviewer's Guide by Sourcery

This pull request introduces the ability to specify a custom GraphQL name for enum values using the name parameter in enum_value(). This allows developers to define different names for enum values in the GraphQL schema while keeping the original Python enum member names. The implementation involves modifying the EnumValueDefinition dataclass and the enum_value function to accept the new parameter, as well as updating the enum processing logic to use the custom name when available. The pull request also includes new tests to verify the functionality and updated documentation to reflect the changes.

Sequence diagram for enum value processing with custom name

sequenceDiagram
    participant User
    participant strawberry.enum
    participant enum_value()
    participant EnumValueDefinition
    participant _process_enum()
    participant EnumValue

    User->>strawberry.enum: Defines enum with enum_value(name='customName')
    strawberry.enum->>enum_value(): Calls enum_value with value and name
    enum_value()->>EnumValueDefinition: Creates EnumValueDefinition(value, graphql_name='customName')
    strawberry.enum->>_process_enum(): Processes enum
    _process_enum()->>EnumValueDefinition: Retrieves value and graphql_name
    alt graphql_name is not None
        _process_enum()->>EnumValue: Creates EnumValue with graphql_name
    else graphql_name is None
        _process_enum()->>EnumValue: Creates EnumValue with item_name
    end
Loading

File-Level Changes

Change Details Files
Introduced the ability to specify a custom GraphQL name for enum values using the name parameter in enum_value().
  • Added a graphql_name field to the EnumValueDefinition dataclass.
  • Modified the enum_value function to accept a name parameter.
  • Updated the _process_enum function to use the graphql_name when available.
strawberry/types/enum.py
strawberry/federation/enum.py
Added tests to verify the functionality of custom enum value names.
  • Added a test case demonstrating custom enum value naming with schema generation and query execution.
  • Added a test case demonstrating the usage of enums with custom names as input values.
tests/schema/test_enum.py
Updated the documentation to reflect the new name parameter in enum_value().
  • Added a section explaining how to use the name parameter to specify custom GraphQL names for enum values.
  • Provided examples of how the custom names are reflected in the GraphQL schema and query responses.
docs/types/enums.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@botberry
Copy link
Member

botberry commented Apr 15, 2025

Apollo Federation Subgraph Compatibility Results

Federation 1 Support Federation 2 Support
_service🟢
@key (single)🟢
@key (multi)🟢
@key (composite)🟢
repeatable @key🟢
@requires🟢
@provides🟢
federated tracing🔲
@link🟢
@shareable🟢
@tag🟢
@override🟢
@inaccessible🟢
@composeDirective🟢
@interfaceObject🟢

Learn more:

Copy link

codecov bot commented Apr 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.04%. Comparing base (be6caa0) to head (fe3866a).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #3841   +/-   ##
=======================================
  Coverage   95.04%   95.04%           
=======================================
  Files         502      502           
  Lines       32682    32719   +37     
  Branches     1695     1696    +1     
=======================================
+ Hits        31061    31098   +37     
  Misses       1348     1348           
  Partials      273      273           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@patrick91 patrick91 force-pushed the feature/enum-value-name branch from 8e713a1 to fe3866a Compare April 15, 2025 22:37
@patrick91 patrick91 marked this pull request as ready for review April 15, 2025 22:37
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

This PR adds support for custom GraphQL names for enum values in Strawberry, allowing developers to specify different names in the GraphQL schema while maintaining Python-style enum names in code.

  • Added name parameter to enum_value() in strawberry/types/enum.py to support custom GraphQL names
  • Updated _process_enum function to handle custom names during schema generation
  • Added comprehensive documentation in docs/types/enums.md with examples showing CHOCOLATE_COOKIE mapping to chocolateCookie
  • Added test cases in tests/schema/test_enum.py verifying custom naming works for both input and output scenarios
  • Maintained federation support in strawberry/federation/enum.py by preserving directive handling with new naming feature

💡 (5/5) You can turn off certain types of comments like style here!

5 file(s) reviewed, 3 comment(s)
Edit PR Review Bot Settings | Greptile

Comment on lines +17 to +20
enum IceCreamFlavour {
VANILLA
chocolateCookie
}
Copy link

Choose a reason for hiding this comment

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

style: Indentation in GraphQL schema example is inconsistent with standard GraphQL formatting (should be 2 spaces)

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @patrick91 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • It would be good to add a release note to explain the new feature and how to use it.
  • Consider adding a test case that uses directives on the enum value.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟡 Testing: 2 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +437 to +438
@strawberry.enum
class IceCreamFlavour(Enum):
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Missing test cases for edge cases.

It would be beneficial to add tests for edge cases such as providing an invalid name argument (e.g., containing spaces or special characters) to enum_value to ensure proper error handling and prevent unexpected behavior.

Suggested implementation:

def test_invalid_enum_value_name_with_space_raises_exception():
    import pytest
    with pytest.raises(ValueError, match="Invalid custom enum value name"):
        @strawberry.enum
        class BadEnum(Enum):
            A = "a"
            B = strawberry.enum_value("b", name="invalid name")


def test_invalid_enum_value_name_with_special_characters_raises_exception():
    import pytest
    with pytest.raises(ValueError, match="Invalid custom enum value name"):
        @strawberry.enum
        class AnotherBadEnum(Enum):
            X = "x"
            Y = strawberry.enum_value("y", name="invalid@name")

Ensure that the implementation of strawberry.enum_value properly validates the custom name and raises a ValueError with a matching message ("Invalid custom enum value name") when the name is invalid. If the current implementation does not do that, you might need to update it accordingly.

Comment on lines +439 to +440
VANILLA = "vanilla"
CHOCOLATE_COOKIE = strawberry.enum_value("chocolate", name="chocolateCookie")
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Test case for duplicate names is missing.

A test case should be added to verify the behavior when a custom name is provided that duplicates an existing enum value name (e.g., defining another enum value with the name "VANILLA"). This will help ensure that the library handles such scenarios gracefully and provides informative error messages.

Suggested implementation:

import pytest
def test_duplicate_enum_custom_names():
    with pytest.raises(ValueError, match="duplicate.*VANILLA"):
        @strawberry.enum
        class DuplicateIceCreamFlavour(Enum):
            VANILLA = "vanilla"
            # Define another value with a custom name that duplicates "VANILLA"
            ANOTHER_VANILLA = strawberry.enum_value("another", name="VANILLA")

        @strawberry.type
        class Query:
            flavour: DuplicateIceCreamFlavour = strawberry.field()

        # Attempting to build the schema should raise an error due to the duplicate names.
        strawberry.Schema(Query)

• Ensure that pytest is available in your testing environment.
• Verify that the error message thrown by strawberry for duplicate enum value names matches the regex "duplicate.*VANILLA" (adjust the match string if necessary).

@botberry
Copy link
Member

Thanks for adding the RELEASE.md file!

Here's a preview of the changelog:


This release adds support for custom names in enum values using the name parameter in strawberry.enum_value.

This allows you to specify a different name for an enum value in the GraphQL schema while keeping the original Python enum member name. For example:

@strawberry.enum
class IceCreamFlavour(Enum):
    VANILLA = "vanilla"
    CHOCOLATE_COOKIE = strawberry.enum_value("chocolate", name="chocolateCookie")

This will produce a GraphQL schema with the custom name:

enum IceCreamFlavour {
    VANILLA
    chocolateCookie
}

Here's the tweet text:

🆕 Release (next) is out! Thanks to @patrick91 for the PR 👏

Get it here 👉 https://strawberry.rocks/release/(next)

Copy link

codspeed-hq bot commented Apr 15, 2025

CodSpeed Performance Report

Merging #3841 will not alter performance

Comparing feature/enum-value-name (fe3866a) with main (be6caa0)

Summary

✅ 21 untouched benchmarks

Copy link
Member

@bellini666 bellini666 left a comment

Choose a reason for hiding this comment

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

Cool one!! ❤️

@patrick91 patrick91 merged commit 30764f5 into main Apr 19, 2025
116 checks passed
@patrick91 patrick91 deleted the feature/enum-value-name branch April 19, 2025 20:54
@tim-schilling
Copy link

This is a pretty cool feature! Thanks folks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants