• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pantsbuild / pants / 18822648545

26 Oct 2025 07:24PM UTC coverage: 79.831% (-0.4%) from 80.28%
18822648545

Pull #22809

github

web-flow
Merge 9401c4830 into 170094e99
Pull Request #22809: golang: fix Go SDK version check for coverage experiment

0 of 1 new or added line in 1 file covered. (0.0%)

439 existing lines in 25 files now uncovered.

77436 of 97000 relevant lines covered (79.83%)

3.35 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.82
/src/python/pants/backend/go/util_rules/embed_integration_test.py
1
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
2
# Licensed under the Apache License, Version 2.0 (see LICENSE).
3

4
from __future__ import annotations
1✔
5

6
import inspect
1✔
7
from textwrap import dedent
1✔
8

9
import pytest
1✔
10

11
from pants.backend.go import target_type_rules
1✔
12
from pants.backend.go.goals.test import GoTestFieldSet, GoTestRequest
1✔
13
from pants.backend.go.goals.test import rules as _test_rules
1✔
14
from pants.backend.go.target_types import GoModTarget, GoPackageTarget
1✔
15
from pants.backend.go.testutil import gen_module_gomodproxy
1✔
16
from pants.backend.go.util_rules import (
1✔
17
    assembly,
18
    build_pkg,
19
    build_pkg_target,
20
    first_party_pkg,
21
    go_mod,
22
    link,
23
    sdk,
24
    tests_analysis,
25
    third_party_pkg,
26
)
27
from pants.backend.go.util_rules.embedcfg import EmbedConfig
1✔
28
from pants.build_graph.address import Address
1✔
29
from pants.core.goals.test import TestResult, get_filtered_environment
1✔
30
from pants.core.target_types import ResourcesGeneratorTarget, ResourceTarget
1✔
31
from pants.core.util_rules import source_files
1✔
32
from pants.testutil.rule_runner import QueryRule, RuleRunner
1✔
33

34

35
@pytest.fixture
1✔
36
def rule_runner() -> RuleRunner:
1✔
37
    rule_runner = RuleRunner(
1✔
38
        rules=[
39
            *_test_rules(),
40
            *assembly.rules(),
41
            *build_pkg.rules(),
42
            *build_pkg_target.rules(),
43
            *first_party_pkg.rules(),
44
            *go_mod.rules(),
45
            *link.rules(),
46
            *sdk.rules(),
47
            *target_type_rules.rules(),
48
            *tests_analysis.rules(),
49
            *third_party_pkg.rules(),
50
            *source_files.rules(),
51
            get_filtered_environment,
52
            QueryRule(TestResult, [GoTestRequest.Batch]),
53
        ],
54
        target_types=[
55
            GoModTarget,
56
            GoPackageTarget,
57
            ResourceTarget,
58
            ResourcesGeneratorTarget,
59
        ],
60
    )
61
    rule_runner.set_options(["--go-test-args=-v -bench=."], env_inherit={"PATH"})
1✔
62
    return rule_runner
1✔
63

64

65
def test_merge_embedcfg() -> None:
1✔
66
    x = EmbedConfig(
1✔
67
        patterns={
68
            "*.go": ["foo.go", "bar.go"],
69
            "*.x": ["only_in_x"],
70
        },
71
        files={"foo.go": "path/to/foo.go", "bar.go": "path/to/bar.go", "only_in_x": "only_in_x"},
72
    )
73
    y = EmbedConfig(
1✔
74
        patterns={
75
            "*.go": ["foo.go", "bar.go"],
76
            "*.y": ["only_in_y"],
77
        },
78
        files={"foo.go": "path/to/foo.go", "bar.go": "path/to/bar.go", "only_in_y": "only_in_y"},
79
    )
80
    merged = x.merge(y)
1✔
81
    assert merged == EmbedConfig(
1✔
82
        patterns={
83
            "*.go": ["foo.go", "bar.go"],
84
            "*.x": ["only_in_x"],
85
            "*.y": ["only_in_y"],
86
        },
87
        files={
88
            "foo.go": "path/to/foo.go",
89
            "bar.go": "path/to/bar.go",
90
            "only_in_x": "only_in_x",
91
            "only_in_y": "only_in_y",
92
        },
93
    )
94

95
    a = EmbedConfig(
1✔
96
        patterns={
97
            "*.go": ["foo.go"],
98
        },
99
        files={"foo.go": "path/to/foo.go"},
100
    )
101
    b = EmbedConfig(
1✔
102
        patterns={
103
            "*.go": ["bar.go"],
104
        },
105
        files={"bar.go": "path/to/bar.go"},
106
    )
107
    with pytest.raises(AssertionError):
1✔
108
        _ = a.merge(b)
1✔
109

110

111
def _assert_test_result_success(test_result: TestResult) -> None:
1✔
UNCOV
112
    if test_result.exit_code != 0:
×
113
        f = inspect.currentframe()
×
114
        assert f is not None
×
115
        f = f.f_back
×
116
        assert f is not None
×
117
        pytest.fail(
×
118
            f"{f.f_code.co_filename}:{f.f_lineno}: test result error: "
119
            f"stdout=`{test_result.stdout_bytes.decode()}`; "
120
            f"stderr=`{test_result.stderr_bytes.decode()}`"
121
        )
122

123

124
def test_embed_in_source_code(rule_runner: RuleRunner) -> None:
1✔
125
    rule_runner.write_files(
1✔
126
        {
127
            "BUILD": dedent(
128
                """
129
                go_mod(name='mod')
130
                go_package(name='pkg', dependencies=[":hello"])
131
                resource(name='hello', source='hello.txt')
132
                """
133
            ),
134
            "go.mod": dedent(
135
                """\
136
                module go.example.com/foo
137
                go 1.17
138
                """
139
            ),
140
            "hello.txt": "hello",
141
            "foo.go": dedent(
142
                """\
143
                package foo
144
                import _ "embed"
145
                //go:embed hello.txt
146
                var message string
147
                """
148
            ),
149
            "foo_test.go": dedent(
150
                """\
151
                package foo
152
                import "testing"
153

154
                func TestFoo(t *testing.T) {
155
                  if message != "hello" {
156
                    t.Fatalf("message mismatch: want=%s; got=%s", "hello", message)
157
                  }
158
                }
159
                """
160
            ),
161
        }
162
    )
163
    tgt = rule_runner.get_target(Address("", target_name="pkg"))
1✔
164
    result = rule_runner.request(
1✔
165
        TestResult, [GoTestRequest.Batch("", (GoTestFieldSet.create(tgt),), None)]
166
    )
UNCOV
167
    _assert_test_result_success(result)
×
168

169

170
def test_embed_in_internal_test(rule_runner: RuleRunner) -> None:
1✔
171
    rule_runner.write_files(
1✔
172
        {
173
            "BUILD": dedent(
174
                """
175
                go_mod(name='mod')
176
                go_package(name='pkg', dependencies=[":hello"])
177
                resource(name='hello', source='hello.txt')
178
                """
179
            ),
180
            "go.mod": dedent(
181
                """\
182
                module go.example.com/foo
183
                go 1.17
184
                """
185
            ),
186
            "hello.txt": "hello",
187
            "foo.go": dedent(
188
                """\
189
                package foo
190
                """
191
            ),
192
            "foo_test.go": dedent(
193
                """\
194
                package foo
195
                import (
196
                  _ "embed"
197
                  "testing"
198
                )
199
                //go:embed hello.txt
200
                var testMessage string
201

202
                func TestFoo(t *testing.T) {
203
                  if testMessage != "hello" {
204
                    t.Fatalf("testMessage mismatch: want=%s; got=%s", "hello", testMessage)
205
                  }
206
                }
207
                """
208
            ),
209
        }
210
    )
211
    tgt = rule_runner.get_target(Address("", target_name="pkg"))
1✔
212
    result = rule_runner.request(
1✔
213
        TestResult, [GoTestRequest.Batch("", (GoTestFieldSet.create(tgt),), None)]
214
    )
UNCOV
215
    _assert_test_result_success(result)
×
216

217

218
def test_embed_in_external_test(rule_runner: RuleRunner) -> None:
1✔
219
    rule_runner.write_files(
1✔
220
        {
221
            "BUILD": dedent(
222
                """
223
                go_mod(name='mod')
224
                go_package(name='pkg', dependencies=[":hello"])
225
                resource(name='hello', source='hello.txt')
226
                """
227
            ),
228
            "go.mod": dedent(
229
                """\
230
                module go.example.com/foo
231
                go 1.17
232
                """
233
            ),
234
            "hello.txt": "hello",
235
            "foo.go": dedent(
236
                """\
237
                package foo
238
                """
239
            ),
240
            "bar_test.go": dedent(
241
                """\
242
                package foo_test
243
                import (
244
                  _ "embed"
245
                  "testing"
246
                )
247
                //go:embed hello.txt
248
                var testMessage string
249

250
                func TestBar(t *testing.T) {
251
                  if testMessage != "hello" {
252
                    t.Fatalf("testMessage mismatch: want=%s; got=%s", "hello", testMessage)
253
                  }
254
                }
255
                """
256
            ),
257
        }
258
    )
259
    tgt = rule_runner.get_target(Address("", target_name="pkg"))
1✔
260
    result = rule_runner.request(
1✔
261
        TestResult, [GoTestRequest.Batch("", (GoTestFieldSet.create(tgt),), None)]
262
    )
UNCOV
263
    _assert_test_result_success(result)
×
264

265

266
def test_third_party_package_embed(rule_runner: RuleRunner) -> None:
1✔
267
    # Build the zip file and other content needed to simulate a third-party module.
268
    import_path = "pantsbuild.org/go-embed-sample-for-test"
1✔
269
    version = "v0.0.1"
1✔
270
    embed_content = "This message comes from an embedded file."
1✔
271
    fake_gomod = gen_module_gomodproxy(
1✔
272
        version,
273
        import_path,
274
        (
275
            (
276
                "pkg/message.go",
277
                dedent(
278
                    """\
279
        package pkg
280
        import _ "embed"
281
        //go:embed message.txt
282
        var Message string
283
        """
284
                ),
285
            ),
286
            ("pkg/message.txt", embed_content),
287
        ),
288
    )
289

290
    # mypy gets sad if update is reversed or ** is used here
291
    fake_gomod.update(
1✔
292
        {
293
            "BUILD": dedent(
294
                """
295
                go_mod(name='mod')
296
                go_package(name='pkg')
297
                """
298
            ),
299
            "go.mod": dedent(
300
                f"""\
301
                module go.example.com/foo
302
                go 1.17
303

304
                require (
305
                \t{import_path} {version}
306
                )
307
                """
308
            ),
309
            # Note: At least one Go file is necessary due to bug in Go backend even if package is only for tests.
310
            "foo.go": "package foo\n",
311
            "foo_test.go": dedent(
312
                f"""\
313
                package foo_test
314
                import (
315
                  "testing"
316
                  "{import_path}/pkg"
317
                )
318

319
                func TestFoo(t *testing.T) {{
320
                  if pkg.Message != "{embed_content}" {{
321
                    t.Fatalf("third-party embedded content did not match")
322
                  }}
323
                }}
324
                """
325
            ),
326
        }
327
    )
328

329
    rule_runner.write_files(fake_gomod)
1✔
330

331
    rule_runner.set_options(
1✔
332
        [
333
            "--go-test-args=-v -bench=.",
334
            f"--golang-subprocess-env-vars=GOPROXY=file://{rule_runner.build_root}/go-mod-proxy",
335
            "--golang-subprocess-env-vars=GOSUMDB=off",
336
        ],
337
        env_inherit={"PATH"},
338
    )
339

340
    tgt = rule_runner.get_target(Address("", target_name="pkg"))
1✔
341
    result = rule_runner.request(
1✔
342
        TestResult, [GoTestRequest.Batch("", (GoTestFieldSet.create(tgt),), None)]
343
    )
UNCOV
344
    _assert_test_result_success(result)
×
345

346

347
def test_embed_with_all_prefix(rule_runner: RuleRunner) -> None:
1✔
348
    rule_runner.write_files(
1✔
349
        {
350
            "BUILD": dedent(
351
                """
352
                go_mod(name='mod')
353
                go_package(name='pkg', dependencies=[":resources"])
354
                resources(name='resources', sources=['r/**'])
355
                """
356
            ),
357
            "go.mod": dedent(
358
                """\
359
                module go.example.com/foo
360
                go 1.17
361
                """
362
            ),
363
            "r/_foo/hello.txt": "hello",
364
            "r/_foo/.another-config.txt": "world",
365
            "r/xyzzy.txt": "another",
366
            "r/.config.txt": "some-config-file",
367
            "foo.go": dedent(
368
                """\
369
                package foo
370
                """
371
            ),
372
            "foo_test.go": dedent(
373
                """\
374
                package foo
375
                import (
376
                    "embed"
377
                    "errors"
378
                    "os"
379
                    "testing"
380
                )
381

382
                //go:embed all:r
383
                var allResources embed.FS
384

385
                //go:embed r
386
                var resources embed.FS
387

388
                func assertFileContent(t *testing.T, fsys embed.FS, name string, content string) {
389
                    t.Helper()
390

391
                    rawContent, err := fsys.ReadFile(name)
392
                    if err != nil {
393
                        t.Error(err)
394
                        return
395
                    }
396

397
                    if string(rawContent) != content {
398
                        t.Errorf("read %v = %q, want %q", name, rawContent, content)
399
                    }
400
                }
401

402
                func assertFileDoesNotExist(t *testing.T, fsys embed.FS, name string) {
403
                    _, err := fsys.ReadFile(name)
404
                    if err == nil {
405
                        t.Errorf("expected file %v to not exist but it actually exists", name)
406
                        return
407
                    }
408

409
                    if !errors.Is(err, os.ErrNotExist) {
410
                        t.Error(err)
411
                    }
412
                }
413

414
                func TestAllResources(t *testing.T) {
415
                    assertFileContent(t, allResources, "r/_foo/hello.txt", "hello")
416
                    assertFileContent(t, allResources, "r/_foo/.another-config.txt", "world")
417
                    assertFileContent(t, allResources, "r/xyzzy.txt", "another")
418
                    assertFileContent(t, allResources, "r/.config.txt", "some-config-file")
419
                }
420

421
                func TestResources(t *testing.T) {
422
                    assertFileDoesNotExist(t, resources, "r/_foo/hello.txt")
423
                    assertFileDoesNotExist(t, resources, "r/_foo/.another-config.txt")
424
                    assertFileContent(t, resources, "r/xyzzy.txt", "another")
425
                    assertFileDoesNotExist(t, resources, "r/.config.txt")
426
                }
427
                """
428
            ),
429
        }
430
    )
431
    tgt = rule_runner.get_target(Address("", target_name="pkg"))
1✔
432
    result = rule_runner.request(
1✔
433
        TestResult, [GoTestRequest.Batch("", (GoTestFieldSet.create(tgt),), None)]
434
    )
UNCOV
435
    _assert_test_result_success(result)
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc