Skip to content

Conversation

@himanshu007-creator
Copy link

@himanshu007-creator himanshu007-creator commented Jan 7, 2026

Description

Added unit test for issue #1468

Types of Changes

  • Core
  • Bugfix
  • New feature
  • Enhancement/optimization
  • Documentation

Issues Fixed or Closed by This PR #1468

Checklist

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • I have tested the changes and verified that they work and don't break anything (as well as I can manage).

Summary by Sourcery

Add comprehensive tests for union type resolution to ensure StrawberryUnion.get_type_resolver correctly handles various return scenarios.

Tests:

  • Add tests verifying union type resolver works with normal objects, dataclasses with is_type_of hooks, and single-type unions.
  • Add tests ensuring union resolution prioritizes union member types over other entries in the type map.
  • Add tests asserting appropriate errors are raised when resolved values are not part of the union or do not match any union members.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jan 7, 2026

Reviewer's Guide

Adds a comprehensive test suite for StrawberryUnion.get_type_resolver to validate correct union member resolution, is_type_of handling, error behavior, and prioritization of union types when looking up GraphQL types in the schema type map.

File-Level Changes

Change Details Files
Add end-to-end tests covering StrawberryUnion.get_type_resolver behavior with various union definitions and resolution scenarios.
  • Verify get_type_resolver returns a callable resolver when given a simple union of two object types.
  • Exercise resolution by direct object instance where the root has an object definition, ensuring the correct GraphQL type name is returned for each union member.
  • Exercise resolution via is_type_of for roots without object definitions, confirming that custom is_type_of checks correctly map dataclass instances to union members.
  • Assert WrongReturnTypeForUnion is raised when no union member’s is_type_of matches the returned object and error messages include field and Python type names.
  • Assert UnallowedReturnTypeForUnion is raised when a returned GraphQL type is not part of the union, and that the error message lists the invalid and allowed types.
  • Ensure unions are prioritized over other entries in the schema type map when resolving types for generic container unions, preventing resolution to a different container type with overlapping structure.
  • Confirm correct behavior for single-member unions defined via Annotated[...] and strawberry.union, including that the resolver still returns the wrapped type name.
tests/types/resolving/test_union_get_type_resolver.py

Possibly linked issues


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!

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

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 - I've left some high level feedback:

  • Several tests duplicate the pattern of iterating over schema.schema_converter.type_map to locate the first StrawberryUnion; consider extracting a small helper (e.g. get_union(schema, predicate)) to make these tests shorter and easier to read.
  • The test_type_resolver_prioritizes_union_types test relies on the generated GraphQL type name containing "AContainer", which is somewhat brittle; if possible, assert based on the union’s underlying Strawberry types (e.g. matching Container[A] and A) rather than on the specific name-mangling convention.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Several tests duplicate the pattern of iterating over `schema.schema_converter.type_map` to locate the first `StrawberryUnion`; consider extracting a small helper (e.g. `get_union(schema, predicate)`) to make these tests shorter and easier to read.
- The `test_type_resolver_prioritizes_union_types` test relies on the generated GraphQL type name containing `"AContainer"`, which is somewhat brittle; if possible, assert based on the union’s underlying Strawberry types (e.g. matching `Container[A]` and `A`) rather than on the specific name-mangling convention.

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.

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Jan 7, 2026

Greptile Summary

Added comprehensive unit tests for UnionDefinition.get_type_resolver method to address issue #1468. The tests cover:

  • Basic functionality: verifies get_type_resolver returns a callable function
  • Object definition resolution: tests type resolution when root has object definition with strawberry types
  • is_type_of resolution: tests fallback to custom is_type_of methods when root doesn't have object definition
  • Error handling: validates WrongReturnTypeForUnion exception when no is_type_of matches
  • Error handling: validates UnallowedReturnTypeForUnion exception when resolved type is not in the union
  • Bug fix verification: tests that union types are prioritized over other types in type_map (from PR Fix issue with enums as params of generic inside unions #1463)
  • Edge case: validates single-type union resolution

The tests use proper mocking with MagicMock for GraphQL info objects and manually construct the schema's type map to directly test the resolver function. All tests follow the existing codebase patterns and are well-documented with clear docstrings.

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk
  • The PR only adds unit tests without modifying any production code. The tests are comprehensive, well-structured, and directly address the requirements from issue Add unit tests for Union type look-up during queries #1468. They follow existing codebase patterns and properly test both success and error paths.
  • No files require special attention

Important Files Changed

Filename Overview
tests/types/resolving/test_union_get_type_resolver.py Added comprehensive unit tests for UnionDefinition.get_type_resolver covering basic resolution, is_type_of usage, error cases, and the bug fix from PR #1463

Sequence Diagram

sequenceDiagram
    participant Test as Test Suite
    participant Union as StrawberryUnion
    participant Resolver as Type Resolver Function
    participant TypeMap as Schema Type Map
    participant GraphQL as GraphQL Union Type

    Note over Test,GraphQL: Test Setup Phase
    Test->>Union: Create union with type_annotations
    Test->>TypeMap: Build schema with types A, B
    Test->>Union: get_type_resolver(type_map)
    Union->>Resolver: Create _resolve_union_type function
    Union-->>Test: Return resolver function

    Note over Test,GraphQL: Type Resolution Test
    Test->>Resolver: Call with instance & mock info
    Resolver->>Resolver: Check if root has_object_definition
    
    alt Root has object definition
        Resolver->>TypeMap: Iterate union types first
        Resolver->>TypeMap: Check if type.is_implemented_by(root)
        TypeMap-->>Resolver: Return matching type
        Resolver->>GraphQL: Verify type in union.types
        Resolver-->>Test: Return type name (e.g., "A")
    else Root uses is_type_of
        Resolver->>GraphQL: Iterate union.types
        Resolver->>GraphQL: Call is_type_of(root, info)
        alt is_type_of matches
            GraphQL-->>Resolver: Return True
            Resolver-->>Test: Return type name
        else No is_type_of matches
            Resolver-->>Test: Raise WrongReturnTypeForUnion
        end
    else Type not in union
        Resolver-->>Test: Raise UnallowedReturnTypeForUnion
    end
Loading

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Jan 7, 2026

Greptile found no issues!

From now on, if a review finishes and we haven't found any issues, we will not post anything, but you can confirm that we reviewed your changes in the status check section.

This feature can be toggled off in your Code Review Settings by deselecting "Create a status check for each PR".

@codecov
Copy link

codecov bot commented Jan 25, 2026

Codecov Report

❌ Patch coverage is 94.39655% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.33%. Comparing base (c8d6ae4) to head (6a1cf84).
⚠️ Report is 63 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4088      +/-   ##
==========================================
- Coverage   94.22%   91.33%   -2.89%     
==========================================
  Files         541      546       +5     
  Lines       35519    36937    +1418     
  Branches     1877     1925      +48     
==========================================
+ Hits        33469    33738     +269     
- Misses       1739     2906    +1167     
+ Partials      311      293      -18     
🚀 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.

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.

Small ask, and also, tests seems to be failing

Comment on lines +309 to +318
for name, concrete_type in schema.schema_converter.type_map.items():
if isinstance(concrete_type.definition, StrawberryUnion):
# Check if this union name contains "AContainer" (indicating Container[A] | A)
# and check if A is in the union types
union_types = concrete_type.definition.types
has_a = A in union_types
if "AContainer" in name and has_a:
union_name = name
union_def = concrete_type.definition
break
Copy link
Member

Choose a reason for hiding this comment

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

Do we need this iteration? Since this is a test, we might be able to just hardcode what we are expecting, so it is easier to understand what we are doing

Same for similar for loops in this file

Choose a reason for hiding this comment

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

Sure will look into this

@codspeed-hq
Copy link

codspeed-hq bot commented Jan 25, 2026

CodSpeed Performance Report

Merging this PR will not alter performance

Comparing himanshu007-creator:1468-himanshu007-creator (6a1cf84) with main (c8d6ae4)

Summary

✅ 31 untouched benchmarks

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants