feat(gazelle): resolve pytest_plugins declarations as dependencies (#4207)

AI written, human reviewed.

## Summary

Pytest loads reusable fixture modules through `pytest_plugins`, but
Gazelle
currently discovers only ordinary imports. Users must therefore
duplicate plugin
dependencies in BUILD files or `gazelle:include_dep` annotations.

Treat static module-level `pytest_plugins` assignments as imports and
reuse the
existing dependency resolver. Support literal strings, lists, tuples,
annotated
and chained assignments, implicit string concatenation, and common
Python string
escapes. Reuse buildtools' existing unquoting with narrow Python 3
normalization.
Match pytest's comma-separated single-string form and retain literal
dependencies
when lists or tuples also contain dynamic entries.

Preserve dependency-ignore annotations, resolution directives, source
locations,
and type-checking metadata. Exclude function/class-local declarations
and document
unsupported dynamic expressions. Conditional declarations are
conservatively
included, as with ordinary conditional imports.

Add parser edge-case tests and BUILD-generation regressions covering
reusable
plugin prerequisites, a workspace-root conftest, external modules,
duplicate dependencies,
resolution overrides, ignore behavior, and unrelated sibling test
isolation.

Fixes #4196.

## Verification

From `gazelle/`:

- `bazel test --config=fast-tests //...` — all 87 test targets pass.
- `gofmt` check on the modified Go files — clean.
- `git diff --check` — clean.

This changes dependency generation only; pytest's invocation-wide plugin
registration behavior is unchanged. Dynamic declarations and named
Unicode
escapes remain unsupported and can use the existing explicit dependency
annotation.
diff --git a/gazelle/docs/directives.md b/gazelle/docs/directives.md
index 949a8e5..17ff48c 100644
--- a/gazelle/docs/directives.md
+++ b/gazelle/docs/directives.md
@@ -181,6 +181,12 @@
   * Default: `true`
   * Allowed Values: `true`, `false`
 
+[`# gazelle:python_resolve_pytest_plugins bool`](#directive-python-resolve-pytest-plugins)
+: Controls whether module-level `pytest_plugins` declarations are resolved into
+  target dependencies.
+  * Default: `true`
+  * Allowed Values: `true`, `false`
+
 (directive-python-extension)=
 ## `python_extension`
 
@@ -931,3 +937,73 @@
     ],
 )
 ```
+
+
+(directive-python-resolve-pytest-plugins)=
+## `python_resolve_pytest_plugins`
+
+:::{versionadded} VERSION_NEXT_FEATURE
+{gh-pr}`4207`
+:::
+
+Gazelle resolves static, module-level `pytest_plugins` declarations into
+dependencies (see {ref}`gazelle-pytest-plugins`). The
+`python_resolve_pytest_plugins` directive controls this behavior. It defaults
+to `true`.
+
+Setting the directive to `false` makes Gazelle ignore `pytest_plugins`
+declarations in the package and its subpackages: their entries are neither
+added as dependencies nor validated. Ordinary imports are unaffected.
+
+For example, with `# gazelle:python_generation_mode file` and these two
+Python files in the repository root:
+
+```python
+# plugins.py
+import pytest
+```
+
+```python
+# foo_test.py
+pytest_plugins = ["plugins"]
+```
+
+`# gazelle:python_resolve_pytest_plugins true` (the default) results in:
+
+```starlark
+# gazelle:python_generation_mode file
+# gazelle:python_resolve_pytest_plugins true
+
+py_library(
+    name = "plugins",
+    srcs = ["plugins.py"],
+    visibility = ["//:__subpackages__"],
+    deps = ["@pip//pytest"],
+)
+
+py_test(
+    name = "foo_test",
+    srcs = ["foo_test.py"],
+    deps = [":plugins"],
+)
+```
+
+And `# gazelle:python_resolve_pytest_plugins false` results in no dependency
+on `:plugins`:
+
+```starlark
+# gazelle:python_generation_mode file
+# gazelle:python_resolve_pytest_plugins false
+
+py_library(
+    name = "plugins",
+    srcs = ["plugins.py"],
+    visibility = ["//:__subpackages__"],
+    deps = ["@pip//pytest"],
+)
+
+py_test(
+    name = "foo_test",
+    srcs = ["foo_test.py"],
+)
+```
diff --git a/gazelle/docs/installation_and_usage.md b/gazelle/docs/installation_and_usage.md
index 3a8733c..c82505a 100644
--- a/gazelle/docs/installation_and_usage.md
+++ b/gazelle/docs/installation_and_usage.md
@@ -206,6 +206,35 @@
 {term}`# gazelle:python_test_naming_convention value` directive.
 
 
+(gazelle-pytest-plugins)=
+#### Pytest plugins
+
+Gazelle resolves module-level `pytest_plugins` declarations into dependencies in
+tests, root conftests, and reusable plugin modules:
+
+```python
+pytest_plugins = ["myapp.testing.database", "myapp.testing.http"]
+```
+
+Literal strings, lists, and tuples are supported, including annotated assignments
+and pytest's comma-separated string form. Existing resolution directives and
+dependency-ignore annotations apply as they do to normal imports.
+Built-in plugin aliases such as `pytester`, `capture`, and `logging` resolve to
+their `_pytest` modules from the pytest distribution. Ignores and resolution
+overrides still match the declared alias. Ordinary imports are not remapped.
+
+Conditional declarations are included conservatively. Function/class-local
+declarations are ignored. Literal entries in mixed lists are resolved, but dynamic
+values, bytes, f-strings, and named Unicode escapes are not evaluated; use
+{ref}`annotation-include-dep` for their dependencies. This does not change pytest's
+invocation-wide plugin registration or its restriction on non-root conftests.
+
+Set the {term}`# gazelle:python_resolve_pytest_plugins bool` directive to `false`
+to turn this off for a package and its subpackages.
+
+:::{versionadded} VERSION_NEXT_FEATURE
+:::
+
 ### Binaries
 
 When a `__main__.py` file is encountered, this indicates the entry point
diff --git a/gazelle/python/BUILD.bazel b/gazelle/python/BUILD.bazel
index d395f7c..5579dd7 100644
--- a/gazelle/python/BUILD.bazel
+++ b/gazelle/python/BUILD.bazel
@@ -142,6 +142,7 @@
     ],
     embed = [":python"],
     deps = [
+        "@com_github_emirpasic_gods//sets/treeset:go_default_library",
         "@com_github_stretchr_testify//assert",
     ],
 )
diff --git a/gazelle/python/configure.go b/gazelle/python/configure.go
index 1fe95a1..01db685 100644
--- a/gazelle/python/configure.go
+++ b/gazelle/python/configure.go
@@ -75,6 +75,7 @@
 		pythonconfig.GenerateProto,
 		pythonconfig.PythonResolveSiblingImports,
 		pythonconfig.PythonIncludeAncestorConftest,
+		pythonconfig.PythonResolvePytestPlugins,
 	}
 }
 
@@ -268,6 +269,12 @@
 				log.Fatal(err)
 			}
 			config.SetIncludeAncestorConftest(v)
+		case pythonconfig.PythonResolvePytestPlugins:
+			v, err := strconv.ParseBool(strings.TrimSpace(d.Value))
+			if err != nil {
+				log.Fatal(err)
+			}
+			config.SetResolvePytestPlugins(v)
 		}
 	}
 
diff --git a/gazelle/python/file_parser.go b/gazelle/python/file_parser.go
index 7bc3838..04ba14a 100644
--- a/gazelle/python/file_parser.go
+++ b/gazelle/python/file_parser.go
@@ -20,8 +20,10 @@
 	"log"
 	"os"
 	"path/filepath"
+	"strconv"
 	"strings"
 
+	bzl "github.com/bazelbuild/buildtools/build"
 	sitter "github.com/tree-sitter/go-tree-sitter"
 	tree_sitter_python "github.com/tree-sitter/tree-sitter-python/bindings/go"
 )
@@ -51,6 +53,7 @@
 	relFilepath         string
 	output              ParserOutput
 	inTypeCheckingBlock bool
+	inLocalScope        bool
 }
 
 func NewFileParser() *FileParser {
@@ -256,6 +259,166 @@
 	return false
 }
 
+// pytestPluginExpression unwraps parentheses, ignoring comments before the value.
+func pytestPluginExpression(node *sitter.Node) *sitter.Node {
+	for node != nil && node.Kind() == "parenthesized_expression" {
+		var expression *sitter.Node
+		for i := uint(0); i < node.NamedChildCount(); i++ {
+			child := node.NamedChild(i)
+			if child.Kind() != sitterNodeTypeComment {
+				expression = child
+				break
+			}
+		}
+		node = expression
+	}
+	return node
+}
+
+// pytestPluginString evaluates literal Python strings without executing Python.
+// Dynamic expressions, bytes, f-strings, and named Unicode escapes are not evaluated.
+func pytestPluginString(node *sitter.Node, code []byte) (string, bool) {
+	node = pytestPluginExpression(node)
+	if node == nil {
+		return "", false
+	}
+	if node.Kind() == "concatenated_string" {
+		var value strings.Builder
+		for i := uint(0); i < node.NamedChildCount(); i++ {
+			child := node.NamedChild(i)
+			if child.Kind() == sitterNodeTypeComment {
+				continue
+			}
+			part, ok := pytestPluginString(child, code)
+			if !ok {
+				return "", false
+			}
+			value.WriteString(part)
+		}
+		return value.String(), true
+	}
+	if node.Kind() != sitterNodeTypeString || node.HasError() {
+		return "", false
+	}
+	literal := node.Utf8Text(code)
+	quote := strings.IndexAny(literal, "\"'")
+	if quote < 0 {
+		return "", false
+	}
+	prefix := strings.ToLower(literal[:quote])
+	if prefix != "" && prefix != "r" && prefix != "u" {
+		return "", false
+	}
+	// Python normalizes source newlines even inside raw string literals.
+	content := strings.ReplaceAll(literal[quote:], "\r\n", "\n")
+	content = strings.ReplaceAll(content, "\r", "\n")
+	if prefix == "r" {
+		value, _, err := bzl.Unquote("r" + content)
+		return value, err == nil
+	}
+	if !strings.Contains(content, "\\") {
+		value, _, err := bzl.Unquote(content)
+		return value, err == nil
+	}
+	// Buildtools already handles Python-style quotes and escapes. Normalize
+	// newlines and byte escapes to preserve Python 3's Unicode string semantics:
+	// buildtools interprets hex and octal escapes as bytes instead of code points.
+	var normalized strings.Builder
+	for len(content) > 0 {
+		if content[0] != '\\' {
+			normalized.WriteByte(content[0])
+			content = content[1:]
+			continue
+		}
+		if len(content) < 2 {
+			return "", false
+		}
+		if content[1] == 'N' {
+			return "", false
+		}
+		if content[1] == 'x' || (content[1] >= '0' && content[1] <= '7') {
+			end := 2
+			base := 8
+			start := 1
+			if content[1] == 'x' {
+				end, start, base = 4, 2, 16
+				if len(content) < end {
+					return "", false
+				}
+			} else {
+				for end < len(content) && end < 4 && content[end] >= '0' && content[end] <= '7' {
+					end++
+				}
+			}
+			r, err := strconv.ParseUint(content[start:end], base, 16)
+			if err != nil {
+				return "", false
+			}
+			fmt.Fprintf(&normalized, "\\u%04x", r)
+			content = content[end:]
+			continue
+		}
+		normalized.WriteString(content[:2])
+		content = content[2:]
+	}
+	value, _, err := bzl.Unquote(normalized.String())
+	return value, err == nil
+}
+
+// parsePytestPlugins treats static module-level pytest_plugins declarations as
+// imports. As with conditional imports, all statically declared alternatives are
+// included; Python code is never executed to determine the active branch.
+func (p *FileParser) parsePytestPlugins(node *sitter.Node) {
+	if p.inLocalScope || node.Kind() != "assignment" {
+		return
+	}
+	left := node.ChildByFieldName("left")
+	if left == nil || left.Kind() != sitterNodeTypeIdentifier || left.Utf8Text(p.code) != "pytest_plugins" {
+		return
+	}
+	right := node.ChildByFieldName("right")
+	for right != nil && right.Kind() == "assignment" {
+		right = right.ChildByFieldName("right")
+	}
+	right = pytestPluginExpression(right)
+	if right == nil || right.HasError() {
+		return
+	}
+	add := func(value string, node *sitter.Node) {
+		if value != "" {
+			p.output.Modules = append(p.output.Modules, Module{
+				Name:             value,
+				LineNumber:       uint32(node.StartPosition().Row) + 1,
+				Filepath:         p.relFilepath,
+				TypeCheckingOnly: p.inTypeCheckingBlock,
+				PytestPlugin:     true,
+			})
+		}
+	}
+	if right.Kind() == "list" || right.Kind() == "tuple" || right.Kind() == "expression_list" {
+		for i := uint(0); i < right.NamedChildCount(); i++ {
+			child := right.NamedChild(i)
+			if child.Kind() == sitterNodeTypeComment {
+				continue
+			}
+			value, ok := pytestPluginString(child, p.code)
+			if !ok {
+				continue
+			}
+			add(value, child)
+		}
+	} else {
+		value, ok := pytestPluginString(right, p.code)
+		if !ok {
+			return
+		}
+		// Pytest also accepts comma-separated module names in a single string.
+		for _, name := range strings.Split(value, ",") {
+			add(name, right)
+		}
+	}
+}
+
 func (p *FileParser) parse(ctx context.Context, node *sitter.Node) {
 	if node == nil {
 		return
@@ -263,6 +426,14 @@
 
 	// Check if this is a TYPE_CHECKING block
 	wasInTypeCheckingBlock := p.inTypeCheckingBlock
+	wasInLocalScope := p.inLocalScope
+	defer func() {
+		p.inTypeCheckingBlock = wasInTypeCheckingBlock
+		p.inLocalScope = wasInLocalScope
+	}()
+	if node.Kind() == "function_definition" || node.Kind() == "class_definition" || node.Kind() == "lambda" {
+		p.inLocalScope = true
+	}
 	if p.isTypeCheckingBlock(node) {
 		p.inTypeCheckingBlock = true
 	}
@@ -272,6 +443,7 @@
 			return
 		}
 		child := node.Child(i)
+		p.parsePytestPlugins(child)
 		if p.parseImportStatements(child) {
 			continue
 		}
@@ -281,8 +453,6 @@
 		p.parse(ctx, child)
 	}
 
-	// Restore the previous state
-	p.inTypeCheckingBlock = wasInTypeCheckingBlock
 }
 
 func (p *FileParser) Parse(ctx context.Context) (*ParserOutput, error) {
diff --git a/gazelle/python/file_parser_test.go b/gazelle/python/file_parser_test.go
index 81c5b99..c3711a6 100644
--- a/gazelle/python/file_parser_test.go
+++ b/gazelle/python/file_parser_test.go
@@ -16,8 +16,10 @@
 
 import (
 	"context"
+	"path/filepath"
 	"testing"
 
+	"github.com/emirpasic/gods/sets/treeset"
 	"github.com/stretchr/testify/assert"
 )
 
@@ -147,6 +149,170 @@
 	}
 }
 
+func TestParsePytestPlugins(t *testing.T) {
+	t.Parallel()
+	units := []struct {
+		name string
+		code string
+		want []string
+	}{
+		{"string", `pytest_plugins = "foo.bar"`, []string{"foo.bar"}},
+		{"single quotes", `pytest_plugins = 'foo.bar'`, []string{"foo.bar"}},
+		{"list", `pytest_plugins = ["foo.bar", 'foo.baz']`, []string{"foo.bar", "foo.baz"}},
+		{"tuple", `pytest_plugins = ("foo.bar", "foo.baz")`, []string{"foo.bar", "foo.baz"}},
+		{"unparenthesized tuple", `pytest_plugins = "foo.bar", "foo.baz"`, []string{"foo.bar", "foo.baz"}},
+		{"one element tuple", `pytest_plugins = ("foo.bar",)`, []string{"foo.bar"}},
+		{"parentheses", `pytest_plugins = (("foo.bar"))`, []string{"foo.bar"}},
+		{"parenthesized list", `pytest_plugins = (["foo.bar"])`, []string{"foo.bar"}},
+		{"leading parenthesis comment", "pytest_plugins = (\n# comment\n'foo.bar'\n)", []string{"foo.bar"}},
+		{"leading list parenthesis comment", "pytest_plugins = (\n# comment\n['foo.bar']\n)", []string{"foo.bar"}},
+		{"parenthesized list item comment", "pytest_plugins = [(\n# comment\n'foo.bar'\n)]", []string{"foo.bar"}},
+		{"annotated", `pytest_plugins: list[str] = ["foo.bar"]`, []string{"foo.bar"}},
+		{"chained left", `pytest_plugins = other = ["foo.bar"]`, []string{"foo.bar"}},
+		{"chained right", `other = pytest_plugins = ["foo.bar"]`, []string{"foo.bar"}},
+		{"comma separated string", `pytest_plugins = "foo.bar,foo.baz"`, []string{"foo.bar", "foo.baz"}},
+		{"comma in list string", `pytest_plugins = ["foo.bar,foo.baz"]`, []string{"foo.bar,foo.baz"}},
+		{"raw", `pytest_plugins = R"foo.bar"`, []string{"foo.bar"}},
+		{"unicode prefix", `pytest_plugins = u'foo.bar'`, []string{"foo.bar"}},
+		{"triple quotes", `pytest_plugins = """foo.bar"""`, []string{"foo.bar"}},
+		{"triple single quotes", `pytest_plugins = '''foo.bar'''`, []string{"foo.bar"}},
+		{"raw triple quotes", `pytest_plugins = r'''foo.bar'''`, []string{"foo.bar"}},
+		{"raw CRLF newlines", "pytest_plugins = r'''foo\r\nbar'''", []string{"foo\nbar"}},
+		{"raw CR newlines", "pytest_plugins = r'''foo\rbar'''", []string{"foo\nbar"}},
+		{"plain CRLF newlines", "pytest_plugins = '''foo\r\nbar'''", []string{"foo\nbar"}},
+		{"non-ASCII module", `pytest_plugins = 'foo.café'`, []string{"foo.café"}},
+		{"implicit concatenation", `pytest_plugins = "foo." 'bar'`, []string{"foo.bar"}},
+		{"concatenation with comment", "pytest_plugins = (\"foo.\" # comment\n'bar')", []string{"foo.bar"}},
+		{"escape sequences", `pytest_plugins = ["foo\x2ebar", 'foo\u002ebaz', "foo\U0000002equx", 'foo\056last']`, []string{"foo.bar", "foo.baz", "foo.qux", "foo.last"}},
+		{"short octal", `pytest_plugins = 'foo\7bar'`, []string{"foo\abar"}},
+		{"octal non-ASCII", `pytest_plugins = 'foo.\351'`, []string{"foo.é"}},
+		{"hex non-ASCII", `pytest_plugins = 'foo.\xe9'`, []string{"foo.é"}},
+		{"escaped backslash", `pytest_plugins = 'foo\\bar'`, []string{`foo\bar`}},
+		{"control escapes", `pytest_plugins = '\a\b\f\n\r\t\v'`, []string{"\a\b\f\n\r\t\v"}},
+		{"surrogate escape", `pytest_plugins = 'foo.\ud800'`, nil},
+		{"out of range Unicode escape", `pytest_plugins = 'foo.\U00110000'`, nil},
+		{"escaped quotes", `pytest_plugins = ["foo\"bar", 'foo\'baz']`, []string{"foo\"bar", "foo'baz"}},
+		{"unrecognized escape", `pytest_plugins = 'foo\qbar'`, []string{`foo\qbar`}},
+		{"raw escape", `pytest_plugins = r'foo\u002ebar'`, []string{`foo\u002ebar`}},
+		{"continued string", "pytest_plugins = 'foo.\\\nbar'", []string{"foo.bar"}},
+		{"continued CRLF string", "pytest_plugins = 'foo.\\\r\nbar'", []string{"foo.bar"}},
+		{"conditional", "if condition:\n    pytest_plugins = ['foo.bar']\nelse:\n    pytest_plugins = ['foo.baz']", []string{"foo.bar", "foo.baz"}},
+		{"reassignment", "pytest_plugins = ['foo.bar']\npytest_plugins = ['foo.baz']", []string{"foo.bar", "foo.baz"}},
+		{"empty string", `pytest_plugins = ""`, nil},
+		{"empty list", `pytest_plugins = []`, nil},
+		{"empty tuple", `pytest_plugins = ()`, nil},
+		{"comments in empty list", "pytest_plugins = [\n# comment\n]", nil},
+		{"none", `pytest_plugins = None`, nil},
+		{"annotation only", `pytest_plugins: list[str]`, nil},
+		{"different name", `other_plugins = ["foo.bar"]`, nil},
+		{"attribute", `module.pytest_plugins = ["foo.bar"]`, nil},
+		{"unpacking", `pytest_plugins, other = ["foo.bar", "foo.baz"]`, nil},
+		{"function local", "def f():\n    pytest_plugins = ['foo.bar']", nil},
+		{"class local", "class C:\n    pytest_plugins = ['foo.bar']", nil},
+		{"async function local", "async def f():\n    pytest_plugins = ['foo.bar']", nil},
+		{"decorated function local", "@decorate\ndef f():\n    pytest_plugins = ['foo.bar']", nil},
+		{"scope restored", "def f():\n    pytest_plugins = ['foo.local']\npytest_plugins = ['foo.bar']", []string{"foo.bar"}},
+		{"ordinary imports remain local", "def f():\n    import foo.bar\n    pytest_plugins = ['foo.local']", []string{"foo.bar"}},
+		{"dynamic call", `pytest_plugins = plugins()`, nil},
+		{"dynamic identifier", `pytest_plugins = plugins`, nil},
+		{"dynamic list", `pytest_plugins = ["foo.bar", plugin]`, []string{"foo.bar"}},
+		{"dynamic entries first", `pytest_plugins = [plugin, "foo.bar", *plugins, "foo.baz"]`, []string{"foo.bar", "foo.baz"}},
+		{"mixed tuple", `pytest_plugins = (plugin, "foo.bar")`, []string{"foo.bar"}},
+		{"unsupported string entry", `pytest_plugins = [f"{name}", "foo.bar"]`, []string{"foo.bar"}},
+		{"escaped named escape text", `pytest_plugins = 'foo\\N{bar}'`, []string{`foo\N{bar}`}},
+		{"raw named escape text", `pytest_plugins = r'foo\N{bar}'`, []string{`foo\N{bar}`}},
+		{"dynamic concatenated string", `pytest_plugins = "foo." f"{name}"`, nil},
+		{"nested list", `pytest_plugins = [["foo.bar"]]`, nil},
+		{"starred list", `pytest_plugins = ["foo.bar", *plugins]`, []string{"foo.bar"}},
+		{"comprehension", `pytest_plugins = [name for name in plugins]`, nil},
+		{"addition", `pytest_plugins = ["foo.bar"] + plugins`, nil},
+		{"augmented assignment", `pytest_plugins += ["foo.bar"]`, nil},
+		{"set", `pytest_plugins = {"foo.bar"}`, nil},
+		{"bytes", `pytest_plugins = b"foo.bar"`, nil},
+		{"f-string", `pytest_plugins = f"foo.{name}"`, nil},
+		{"constant f-string", `pytest_plugins = f"foo.bar"`, nil},
+		{"malformed declaration", `pytest_plugins = [`, nil},
+		{"malformed list", `pytest_plugins = ["foo.bar",`, nil},
+		{"invalid escape", `pytest_plugins = "foo\xZZbar"`, nil},
+		{"named Unicode escape", `pytest_plugins = "foo\N{FULL STOP}bar"`, nil},
+	}
+	for _, unit := range units {
+		t.Run(unit.name, func(t *testing.T) {
+			p := NewFileParser()
+			p.SetCodeAndFile([]byte(unit.code), "tests", "example_test.py")
+			output, err := p.Parse(context.Background())
+			assert.NoError(t, err)
+			var names []string
+			for _, module := range output.Modules {
+				names = append(names, module.Name)
+				assert.Equal(t, filepath.Join("tests", "example_test.py"), module.Filepath)
+				assert.Empty(t, module.From)
+				assert.False(t, module.TypeCheckingOnly)
+			}
+			assert.Equal(t, unit.want, names)
+		})
+	}
+}
+
+func TestParseRestoresStateOnCancellation(t *testing.T) {
+	t.Parallel()
+	for _, code := range []string{
+		"def f():\n    pytest_plugins = ['foo.bar']",
+		"if TYPE_CHECKING:\n    import foo.bar",
+	} {
+		t.Run(code, func(t *testing.T) {
+			root, err := ParseCode([]byte(code), "example.py")
+			assert.NoError(t, err)
+			if root == nil {
+				t.Fatal("missing syntax tree")
+			}
+			ctx, cancel := context.WithCancel(context.Background())
+			cancel()
+			p := NewFileParser()
+			p.SetCodeAndFile([]byte(code), "", "example.py")
+			// Enter the scope directly so cancellation occurs after its state
+			// has changed, rather than before traversal reaches it.
+			p.parse(ctx, root.NamedChild(0))
+			assert.False(t, p.inLocalScope)
+			assert.False(t, p.inTypeCheckingBlock)
+			assert.Empty(t, p.output.Modules)
+		})
+	}
+}
+
+func TestPytestPluginsLocationsAndComments(t *testing.T) {
+	t.Parallel()
+	p := NewFileParser()
+	p.SetCodeAndFile([]byte("pytest_plugins = [\n    'foo.bar', # gazelle:ignore foo.bar\n    'foo.baz',\n]\nif TYPE_CHECKING:\n    pytest_plugins = 'foo.typing'\n"), "", "conftest.py")
+	output, err := p.Parse(context.Background())
+	assert.NoError(t, err)
+	assert.Equal(t, []Module{
+		{Name: "foo.bar", LineNumber: 2, Filepath: "conftest.py", PytestPlugin: true},
+		{Name: "foo.baz", LineNumber: 3, Filepath: "conftest.py", PytestPlugin: true},
+		{Name: "foo.typing", LineNumber: 6, Filepath: "conftest.py", TypeCheckingOnly: true, PytestPlugin: true},
+	}, output.Modules)
+	assert.Equal(t, []Comment{"# gazelle:ignore foo.bar"}, output.Comments)
+}
+
+func TestPluginAndImportDependenciesRemainDistinct(t *testing.T) {
+	t.Parallel()
+	for _, pluginFirst := range []bool{false, true} {
+		modules := treeset.NewWith(moduleComparator)
+		ordinary := Module{Name: "logging", TypeCheckingOnly: true}
+		plugin := Module{Name: "logging", PytestPlugin: true}
+		if pluginFirst {
+			addModuleToTreeSet(modules, plugin)
+			addModuleToTreeSet(modules, ordinary)
+		} else {
+			addModuleToTreeSet(modules, ordinary)
+			addModuleToTreeSet(modules, plugin)
+		}
+		assert.Equal(t, []interface{}{ordinary, plugin}, modules.Values())
+		addModuleToTreeSet(modules, Module{Name: "logging", PytestPlugin: true, TypeCheckingOnly: true})
+		assert.Equal(t, []interface{}{ordinary, plugin}, modules.Values())
+	}
+}
+
 func TestParseComments(t *testing.T) {
 	t.Parallel()
 	units := []struct {
@@ -277,9 +443,9 @@
 
 	// Check that we found the expected modules
 	expectedModules := map[string]bool{
-		"sys": false,
-		"typing.TYPE_CHECKING": false,
-		"boto3": true,
+		"sys":                        false,
+		"typing.TYPE_CHECKING":       false,
+		"boto3":                      true,
 		"rest_framework.serializers": true,
 	}
 
diff --git a/gazelle/python/parser.go b/gazelle/python/parser.go
index 3d0dbe7..50cbea1 100644
--- a/gazelle/python/parser.go
+++ b/gazelle/python/parser.go
@@ -163,11 +163,24 @@
 	From string `json:"from"`
 	// Whether this import is type-checking only (inside if TYPE_CHECKING block).
 	TypeCheckingOnly bool `json:"type_checking_only"`
+	// Whether the name was declared in pytest_plugins, whose built-in aliases
+	// resolve differently from ordinary Python imports.
+	PytestPlugin bool `json:"pytest_plugin"`
 }
 
-// moduleComparator compares modules by name.
+// moduleComparator compares modules by name and plugin declaration status.
 func moduleComparator(a, b interface{}) int {
-	return godsutils.StringComparator(a.(Module).Name, b.(Module).Name)
+	left, right := a.(Module), b.(Module)
+	if cmp := godsutils.StringComparator(left.Name, right.Name); cmp != 0 {
+		return cmp
+	}
+	if left.PytestPlugin == right.PytestPlugin {
+		return 0
+	}
+	if left.PytestPlugin {
+		return 1
+	}
+	return -1
 }
 
 // addModuleToTreeSet adds a module to a treeset.Set, ensuring that a TypeCheckingOnly=false module is
diff --git a/gazelle/python/resolve.go b/gazelle/python/resolve.go
index cc57180..2a1859b 100644
--- a/gazelle/python/resolve.go
+++ b/gazelle/python/resolve.go
@@ -45,6 +45,26 @@
 // in rules generated by this extension.
 type Resolver struct{}
 
+// pytestPluginModule mirrors pytest's builtin_plugins in _pytest/config/__init__.py.
+// Keep the declared name on Module so ignores and resolve overrides still match
+// it. Only plugin declarations use these aliases; ordinary imports do not.
+func pytestPluginModule(name string) string {
+	switch name {
+	case "mark", "main", "runner", "fixtures", "helpconfig", "python",
+		"terminal", "debugging", "unittest", "capture", "skipping", "legacypath",
+		"tmpdir", "monkeypatch", "recwarn", "pastebin", "assertion", "junitxml",
+		"doctest", "cacheprovider", "setuponly", "setupplan", "stepwise",
+		"unraisableexception", "threadexception", "warnings", "logging",
+		"reports", "faulthandler", "subtests", "pytester", "pytester_assertions",
+		"terminalprogress",
+		// Built-ins in older pytest releases.
+		"nose", "freeze_support":
+		return "_pytest." + name
+	default:
+		return name
+	}
+}
+
 // Name returns the name of the language. This is the prefix of the kinds of
 // rules generated. E.g. py_library and py_binary.
 func (*Resolver) Name() string { return languageName }
@@ -168,7 +188,14 @@
 	MODULES_LOOP:
 		for it.Next() {
 			mod := it.Value().(Module)
+			if mod.PytestPlugin && !cfg.ResolvePytestPlugins() {
+				continue MODULES_LOOP
+			}
 			moduleName := mod.Name
+			if mod.PytestPlugin {
+				moduleName = pytestPluginModule(moduleName)
+			}
+			builtinPluginAlias := mod.PytestPlugin && moduleName != mod.Name
 			// Transform relative imports `.` or `..foo.bar` into the package path from root.
 			if strings.HasPrefix(mod.From, ".") {
 				if !cfg.ExperimentalAllowRelativeImports() {
@@ -229,6 +256,11 @@
 				moduleParts = moduleParts[:len(moduleParts)-1]
 				possibleModules = append(possibleModules, strings.Join(moduleParts, "."))
 			}
+			if builtinPluginAlias {
+				// Give explicit overrides for the declared alias precedence, but
+				// do not resolve that alias as a local, third-party, or stdlib module.
+				possibleModules = append([]string{mod.Name}, possibleModules...)
+			}
 			errs := []error{}
 		POSSIBLE_MODULE_LOOP:
 			for _, moduleName := range possibleModules {
@@ -252,6 +284,9 @@
 						continue MODULES_LOOP
 					}
 				} else {
+					if builtinPluginAlias && moduleName == mod.Name {
+						continue POSSIBLE_MODULE_LOOP
+					}
 					if dep, distributionName, ok := cfg.FindThirdPartyDependency(moduleName); ok {
 						addDependency(dep, mod.TypeCheckingOnly, deps, pyiDeps)
 						// Add the type and stub dependencies if they exist.
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/BUILD.in b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/BUILD.in
new file mode 100644
index 0000000..af2c2ce
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/BUILD.in
@@ -0,0 +1 @@
+# gazelle:python_generation_mode file
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/BUILD.out b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/BUILD.out
new file mode 100644
index 0000000..76aa068
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/BUILD.out
@@ -0,0 +1,16 @@
+load("@rules_python//python:defs.bzl", "py_library", "py_test")
+
+# gazelle:python_generation_mode file
+
+py_library(
+    name = "plugins",
+    srcs = ["plugins.py"],
+    visibility = ["//:__subpackages__"],
+    deps = ["@gazelle_python_test//pytest"],
+)
+
+py_test(
+    name = "enabled_test",
+    srcs = ["enabled_test.py"],
+    deps = [":plugins"],
+)
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/README.md b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/README.md
new file mode 100644
index 0000000..ddb2560
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/README.md
@@ -0,0 +1,12 @@
+# Directive: `python_resolve_pytest_plugins`
+
+This test case asserts that the `# gazelle:python_resolve_pytest_plugins`
+directive controls whether module-level `pytest_plugins` declarations are
+resolved into dependencies, and that child packages inherit the value:
+
++ The root level does not set the directive (it defaults to true), so
+  `enabled_test` depends on the `plugins` module it declares.
++ `disabled/` sets the directive to false. `disabled_test` keeps its ordinary
+  `import pytest` dependency, but none of its `pytest_plugins` entries are
+  added, including an unresolvable one that would otherwise fail validation.
++ `disabled/reenabled/` sets the directive back to true.
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/WORKSPACE b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/WORKSPACE
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/WORKSPACE
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/BUILD.in b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/BUILD.in
new file mode 100644
index 0000000..2d21129
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/BUILD.in
@@ -0,0 +1 @@
+# gazelle:python_resolve_pytest_plugins false
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/BUILD.out b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/BUILD.out
new file mode 100644
index 0000000..ba64434
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/BUILD.out
@@ -0,0 +1,9 @@
+load("@rules_python//python:defs.bzl", "py_test")
+
+# gazelle:python_resolve_pytest_plugins false
+
+py_test(
+    name = "disabled_test",
+    srcs = ["disabled_test.py"],
+    deps = ["@gazelle_python_test//pytest"],
+)
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/disabled_test.py b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/disabled_test.py
new file mode 100644
index 0000000..28481ae
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/disabled_test.py
@@ -0,0 +1,7 @@
+import pytest
+
+pytest_plugins = ["plugins", "pytester", "not_a_real_plugin"]
+
+
+def test_database(database):
+    assert database == "database"
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/BUILD.in b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/BUILD.in
new file mode 100644
index 0000000..f4d5696
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/BUILD.in
@@ -0,0 +1 @@
+# gazelle:python_resolve_pytest_plugins true
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/BUILD.out b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/BUILD.out
new file mode 100644
index 0000000..a4ef797
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/BUILD.out
@@ -0,0 +1,9 @@
+load("@rules_python//python:defs.bzl", "py_test")
+
+# gazelle:python_resolve_pytest_plugins true
+
+py_test(
+    name = "reenabled_test",
+    srcs = ["reenabled_test.py"],
+    deps = ["//:plugins"],
+)
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/reenabled_test.py b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/reenabled_test.py
new file mode 100644
index 0000000..d62ec40
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/disabled/reenabled/reenabled_test.py
@@ -0,0 +1,5 @@
+pytest_plugins = ["plugins"]
+
+
+def test_database(database):
+    assert database == "database"
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/enabled_test.py b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/enabled_test.py
new file mode 100644
index 0000000..d62ec40
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/enabled_test.py
@@ -0,0 +1,5 @@
+pytest_plugins = ["plugins"]
+
+
+def test_database(database):
+    assert database == "database"
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/gazelle_python.yaml b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/gazelle_python.yaml
new file mode 100644
index 0000000..4b6f3cc
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/gazelle_python.yaml
@@ -0,0 +1,5 @@
+manifest:
+  modules_mapping:
+    _pytest: pytest
+    pytest: pytest
+  pip_deps_repository_name: gazelle_python_test
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/plugins.py b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/plugins.py
new file mode 100644
index 0000000..158882f
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/plugins.py
@@ -0,0 +1,6 @@
+import pytest
+
+
+@pytest.fixture(name="database")
+def fixture_database():
+    return "database"
diff --git a/gazelle/python/testdata/directive_python_resolve_pytest_plugins/test.yaml b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/test.yaml
new file mode 100644
index 0000000..7c9bd59
--- /dev/null
+++ b/gazelle/python/testdata/directive_python_resolve_pytest_plugins/test.yaml
@@ -0,0 +1,2 @@
+expect:
+  exit_code: 0
diff --git a/gazelle/python/testdata/pytest_plugins/BUILD.in b/gazelle/python/testdata/pytest_plugins/BUILD.in
new file mode 100644
index 0000000..7c16102
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/BUILD.in
@@ -0,0 +1,6 @@
+# gazelle:python_root
+# gazelle:python_generation_mode file
+# gazelle:python_include_ancestor_conftest false
+# gazelle:resolve py aliased_plugin //support:admin
+# gazelle:python_ignore_dependencies ignored_plugin,monkeypatch
+# gazelle:resolve py terminal //support:admin
diff --git a/gazelle/python/testdata/pytest_plugins/BUILD.out b/gazelle/python/testdata/pytest_plugins/BUILD.out
new file mode 100644
index 0000000..0c23299
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/BUILD.out
@@ -0,0 +1,63 @@
+load("@rules_python//python:defs.bzl", "py_library", "py_test")
+
+# gazelle:python_root
+# gazelle:python_generation_mode file
+# gazelle:python_include_ancestor_conftest false
+# gazelle:resolve py aliased_plugin //support:admin
+# gazelle:python_ignore_dependencies ignored_plugin,monkeypatch
+# gazelle:resolve py terminal //support:admin
+
+py_library(
+    name = "capture",
+    srcs = ["capture.py"],
+    visibility = ["//:__subpackages__"],
+)
+
+py_test(
+    name = "builtin_controls_test",
+    srcs = ["builtin_controls_test.py"],
+    deps = ["//support:admin"],
+)
+
+py_test(
+    name = "builtin_plugins_test",
+    srcs = ["builtin_plugins_test.py"],
+    deps = ["@gazelle_python_test//pytest"],
+)
+
+py_test(
+    name = "isolated_test",
+    srcs = ["isolated_test.py"],
+)
+
+py_test(
+    name = "logging_plugin_test",
+    srcs = ["logging_plugin_test.py"],
+    deps = ["@gazelle_python_test//pytest"],
+)
+
+py_test(
+    name = "ordinary_import_test",
+    srcs = ["ordinary_import_test.py"],
+    deps = [
+        ":capture",
+        "@gazelle_python_test//pytest",
+    ],
+)
+
+py_test(
+    name = "plugin_test",
+    srcs = ["plugin_test.py"],
+    deps = [
+        "//support:admin",
+        "//support:database",
+        "@gazelle_python_test//external_plugin",
+        "@gazelle_python_test//pytest",
+    ],
+)
+
+py_test(
+    name = "pytester_plugin_test",
+    srcs = ["pytester_plugin_test.py"],
+    deps = ["@gazelle_python_test//pytest"],
+)
diff --git a/gazelle/python/testdata/pytest_plugins/README.md b/gazelle/python/testdata/pytest_plugins/README.md
new file mode 100644
index 0000000..0a3caa4
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/README.md
@@ -0,0 +1,10 @@
+# Pytest plugin dependencies
+
+Also covers pytest built-in aliases (including stdlib-name collisions), alias
+ignores and overrides, and ordinary imports sharing a plugin alias's name.
+
+Resolve literal plugin declarations in tests and reusable plugin
+modules. Verify prerequisite chains, external modules, duplicate imports,
+resolution overrides, dependency ignores, mixed dynamic entries, and unrelated
+sibling test isolation. External and ignored module names are resolution inputs;
+this fixture is not intended to execute pytest.
diff --git a/gazelle/python/testdata/pytest_plugins/WORKSPACE b/gazelle/python/testdata/pytest_plugins/WORKSPACE
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/WORKSPACE
diff --git a/gazelle/python/testdata/pytest_plugins/builtin_controls_test.py b/gazelle/python/testdata/pytest_plugins/builtin_controls_test.py
new file mode 100644
index 0000000..0a7c561
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/builtin_controls_test.py
@@ -0,0 +1,3 @@
+# Ignores use declared names, and the terminal alias has an explicit override.
+# gazelle:ignore pytester
+pytest_plugins = ["pytester", "terminal", "monkeypatch"]
diff --git a/gazelle/python/testdata/pytest_plugins/builtin_plugins_test.py b/gazelle/python/testdata/pytest_plugins/builtin_plugins_test.py
new file mode 100644
index 0000000..d4a5571
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/builtin_plugins_test.py
@@ -0,0 +1,7 @@
+pytest_plugins = (
+    "mark,main,runner,fixtures,helpconfig,python,debugging,unittest,capture,"
+    "skipping,legacypath,tmpdir,monkeypatch,recwarn,pastebin,assertion,junitxml,"
+    "doctest,cacheprovider,setuponly,setupplan,stepwise,unraisableexception,"
+    "threadexception,warnings,reports,faulthandler,subtests,pytester_assertions,"
+    "terminalprogress,nose,freeze_support"
+)
diff --git a/gazelle/python/testdata/pytest_plugins/capture.py b/gazelle/python/testdata/pytest_plugins/capture.py
new file mode 100644
index 0000000..a614f25
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/capture.py
@@ -0,0 +1 @@
+"""A local module whose name also happens to be a built-in pytest plugin alias."""
diff --git a/gazelle/python/testdata/pytest_plugins/gazelle_python.yaml b/gazelle/python/testdata/pytest_plugins/gazelle_python.yaml
new file mode 100644
index 0000000..e0d828a
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/gazelle_python.yaml
@@ -0,0 +1,6 @@
+manifest:
+  modules_mapping:
+    _pytest: pytest
+    external_plugin: external_plugin
+    pytest: pytest
+  pip_deps_repository_name: gazelle_python_test
diff --git a/gazelle/python/testdata/pytest_plugins/isolated_test.py b/gazelle/python/testdata/pytest_plugins/isolated_test.py
new file mode 100644
index 0000000..81d3472
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/isolated_test.py
@@ -0,0 +1,2 @@
+def test_isolated():
+    assert True
diff --git a/gazelle/python/testdata/pytest_plugins/logging_plugin_test.py b/gazelle/python/testdata/pytest_plugins/logging_plugin_test.py
new file mode 100644
index 0000000..f1f8400
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/logging_plugin_test.py
@@ -0,0 +1,4 @@
+import logging
+
+# Unlike the ordinary import above, this alias needs the pytest wheel.
+pytest_plugins = ["logging"]
diff --git a/gazelle/python/testdata/pytest_plugins/ordinary_import_test.py b/gazelle/python/testdata/pytest_plugins/ordinary_import_test.py
new file mode 100644
index 0000000..01fa960
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/ordinary_import_test.py
@@ -0,0 +1,4 @@
+import capture
+
+# Keep both dependencies even though the ordinary import and alias share a name.
+pytest_plugins = ["capture"]
diff --git a/gazelle/python/testdata/pytest_plugins/plugin_test.py b/gazelle/python/testdata/pytest_plugins/plugin_test.py
new file mode 100644
index 0000000..642cb21
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/plugin_test.py
@@ -0,0 +1,22 @@
+import pytest
+
+plugin_name = "support.admin"
+additional_plugins = []
+
+# gazelle:ignore nonexistent.plugin
+pytest_plugins = [
+    "support.database",
+    "support.database",  # Duplicate declarations resolve to one dependency.
+    "pytest",
+    "external_plugin",
+    "aliased_plugin",
+    "ignored_plugin",
+    "nonexistent.plugin",
+    # Dynamic entries do not hide the statically known dependencies above.
+    plugin_name,
+    *additional_plugins,
+]
+
+
+def test_database(database):
+    assert database == "database"
diff --git a/gazelle/python/testdata/pytest_plugins/pytester_plugin_test.py b/gazelle/python/testdata/pytest_plugins/pytester_plugin_test.py
new file mode 100644
index 0000000..434f853
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/pytester_plugin_test.py
@@ -0,0 +1 @@
+pytest_plugins = ["pytester", "_pytest.pytester"]
diff --git a/gazelle/python/testdata/pytest_plugins/support/BUILD.in b/gazelle/python/testdata/pytest_plugins/support/BUILD.in
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/support/BUILD.in
diff --git a/gazelle/python/testdata/pytest_plugins/support/BUILD.out b/gazelle/python/testdata/pytest_plugins/support/BUILD.out
new file mode 100644
index 0000000..0e40491
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/support/BUILD.out
@@ -0,0 +1,18 @@
+load("@rules_python//python:defs.bzl", "py_library")
+
+py_library(
+    name = "admin",
+    srcs = ["admin.py"],
+    visibility = ["//:__subpackages__"],
+    deps = ["@gazelle_python_test//pytest"],
+)
+
+py_library(
+    name = "database",
+    srcs = ["database.py"],
+    visibility = ["//:__subpackages__"],
+    deps = [
+        ":admin",
+        "@gazelle_python_test//pytest",
+    ],
+)
diff --git a/gazelle/python/testdata/pytest_plugins/support/admin.py b/gazelle/python/testdata/pytest_plugins/support/admin.py
new file mode 100644
index 0000000..2b1ecb5
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/support/admin.py
@@ -0,0 +1,6 @@
+import pytest
+
+
+@pytest.fixture(name="admin")
+def fixture_admin():
+    return "database"
diff --git a/gazelle/python/testdata/pytest_plugins/support/database.py b/gazelle/python/testdata/pytest_plugins/support/database.py
new file mode 100644
index 0000000..28ca3b3
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/support/database.py
@@ -0,0 +1,11 @@
+import pytest
+
+pytest_plugins = (
+    # A comment before a parenthesized value must not hide its dependency.
+    ("support.admin",)
+)
+
+
+@pytest.fixture(name="database")
+def fixture_database(admin):
+    return admin
diff --git a/gazelle/python/testdata/pytest_plugins/test.yaml b/gazelle/python/testdata/pytest_plugins/test.yaml
new file mode 100644
index 0000000..7c9bd59
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins/test.yaml
@@ -0,0 +1,2 @@
+expect:
+  exit_code: 0
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/BUILD.in b/gazelle/python/testdata/pytest_plugins_conftest/BUILD.in
new file mode 100644
index 0000000..af2c2ce
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/BUILD.in
@@ -0,0 +1 @@
+# gazelle:python_generation_mode file
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/BUILD.out b/gazelle/python/testdata/pytest_plugins_conftest/BUILD.out
new file mode 100644
index 0000000..f0e40df
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/BUILD.out
@@ -0,0 +1,24 @@
+load("@rules_python//python:defs.bzl", "py_library", "py_test")
+
+# gazelle:python_generation_mode file
+
+py_library(
+    name = "database_fixtures",
+    srcs = ["database_fixtures.py"],
+    visibility = ["//:__subpackages__"],
+    deps = ["@gazelle_python_test//pytest"],
+)
+
+py_library(
+    name = "conftest",
+    testonly = True,
+    srcs = ["conftest.py"],
+    visibility = ["//:__subpackages__"],
+    deps = [":database_fixtures"],
+)
+
+py_test(
+    name = "consumer_test",
+    srcs = ["consumer_test.py"],
+    deps = [":conftest"],
+)
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/README.md b/gazelle/python/testdata/pytest_plugins_conftest/README.md
new file mode 100644
index 0000000..788c244
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/README.md
@@ -0,0 +1,6 @@
+# Root conftest plugins
+
+Resolve a root conftest's plugin declaration and include its dependencies in the
+consumer test. Unlike nested conftest plugin declarations, this layout can also
+be collected by pytest from the workspace root.
+The local plugin avoids pytest's reserved built-in alias `fixtures`.
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/WORKSPACE b/gazelle/python/testdata/pytest_plugins_conftest/WORKSPACE
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/WORKSPACE
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/conftest.py b/gazelle/python/testdata/pytest_plugins_conftest/conftest.py
new file mode 100644
index 0000000..8c2e7e6
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = "database_fixtures"
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/consumer_test.py b/gazelle/python/testdata/pytest_plugins_conftest/consumer_test.py
new file mode 100644
index 0000000..2fa0f08
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/consumer_test.py
@@ -0,0 +1,2 @@
+def test_database(database):
+    assert database == "database"
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/database_fixtures.py b/gazelle/python/testdata/pytest_plugins_conftest/database_fixtures.py
new file mode 100644
index 0000000..158882f
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/database_fixtures.py
@@ -0,0 +1,6 @@
+import pytest
+
+
+@pytest.fixture(name="database")
+def fixture_database():
+    return "database"
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/gazelle_python.yaml b/gazelle/python/testdata/pytest_plugins_conftest/gazelle_python.yaml
new file mode 100644
index 0000000..bbba766
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/gazelle_python.yaml
@@ -0,0 +1,4 @@
+manifest:
+  modules_mapping:
+    pytest: pytest
+  pip_deps_repository_name: gazelle_python_test
diff --git a/gazelle/python/testdata/pytest_plugins_conftest/test.yaml b/gazelle/python/testdata/pytest_plugins_conftest/test.yaml
new file mode 100644
index 0000000..7c9bd59
--- /dev/null
+++ b/gazelle/python/testdata/pytest_plugins_conftest/test.yaml
@@ -0,0 +1,2 @@
+expect:
+  exit_code: 0
diff --git a/gazelle/pythonconfig/pythonconfig.go b/gazelle/pythonconfig/pythonconfig.go
index c88d59a..e9843aa 100644
--- a/gazelle/pythonconfig/pythonconfig.go
+++ b/gazelle/pythonconfig/pythonconfig.go
@@ -125,6 +125,10 @@
 	// https://github.com/bazel-contrib/rules_python/issues/3595 which requested
 	// that the behavior be configurable.
 	PythonIncludeAncestorConftest = "python_include_ancestor_conftest"
+	// PythonResolvePytestPlugins represents the directive that controls
+	// whether module-level pytest_plugins declarations are resolved into
+	// dependencies. Defaults to true.
+	PythonResolvePytestPlugins = "python_resolve_pytest_plugins"
 )
 
 // GenerationModeType represents one of the generation modes for the Python
@@ -219,6 +223,7 @@
 	generateProto                             bool
 	resolveSiblingImports                     bool
 	includeAncestorConftest                   bool
+	resolvePytestPlugins                      bool
 }
 
 type LabelNormalizationType int
@@ -261,6 +266,7 @@
 		generateProto:                             false,
 		resolveSiblingImports:                     false,
 		includeAncestorConftest:                   true,
+		resolvePytestPlugins:                      true,
 	}
 }
 
@@ -300,6 +306,7 @@
 		generateProto:                             c.generateProto,
 		resolveSiblingImports:                     c.resolveSiblingImports,
 		includeAncestorConftest:                   c.includeAncestorConftest,
+		resolvePytestPlugins:                      c.resolvePytestPlugins,
 	}
 }
 
@@ -651,6 +658,16 @@
 	return c.includeAncestorConftest
 }
 
+// SetResolvePytestPlugins sets whether pytest_plugins declarations are resolved into dependencies.
+func (c *Config) SetResolvePytestPlugins(resolvePytestPlugins bool) {
+	c.resolvePytestPlugins = resolvePytestPlugins
+}
+
+// ResolvePytestPlugins returns whether pytest_plugins declarations are resolved into dependencies.
+func (c *Config) ResolvePytestPlugins() bool {
+	return c.resolvePytestPlugins
+}
+
 // FormatThirdPartyDependency returns a label to a third-party dependency performing all formating and normalization.
 func (c *Config) FormatThirdPartyDependency(repositoryName string, distributionName string) label.Label {
 	conventionalDistributionName := strings.ReplaceAll(c.labelConvention, distributionNameLabelConventionSubstitution, distributionName)
diff --git a/news/4196.added.md b/news/4196.added.md
new file mode 100644
index 0000000..6d01daf
--- /dev/null
+++ b/news/4196.added.md
@@ -0,0 +1,3 @@
+(gazelle) Resolve literal `pytest_plugins` declarations into Python target
+dependencies, including reusable plugins' prerequisite declarations. Set
+`# gazelle:python_resolve_pytest_plugins false` to turn this off.