Skip to content

[Feature Request] Add new directive to prefer test targets during import resolution when duplicate packages exist #2113

@clinto8

Description

@clinto8

Background

Gazelle will appropriately fail if there are multiple modules with the same package name. However, Gazelle ignores cases where the same package name is used in both the main and test directories of the same module.

It's not uncommon for test code to live in parallel directory trees that mirror the structure of main or source code, such as for shared helpers and cross-package testing patterns However, if test code depends on other test code, and the package names in test directories match those of main code, Gazelle currently resolves imports based on the non-test code path, even when the import originates from test code. This results in incorrect or undesired dependency resolution that requires manually adding and maintaining several dependencies with the #keep comment.

Proposed Solution

Introduce a new directive to instruct Gazelle to prefer test targets (e.g., targets in paths matching /test/, /tests/, or user-defined test directory) when resolving imports that appear in test contexts.

Possible Syntax: # gazelle:prefer_test_imports true

Example

Suppose a test class located at module1/src/test/java/com/package1/FooTest.java has import com.package2.Bar; If com.package2.Bar lives in module2/src/test/com/package2, but there also exists a module2/src/main/com/package2, Gazelle will resolve this dependency by adding the java_library target //module2/src/main/com/package2. With the prefer_test_imports directive enabled, Gazelle would instead use the //module2/src/test/com/package2 target to resolve the dependency found in FooTest.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions