xref: /aosp_15_r20/external/bazelbuild-rules_python/gazelle/manifest/test/test.go (revision 60517a1edbc8ecf509223e9af94a7adec7d736b8)
1// Copyright 2023 The Bazel Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/*
16test.go is a unit test that asserts the Gazelle YAML manifest is up-to-date in
17regards to the requirements.txt.
18
19It re-hashes the requirements.txt and compares it to the recorded one in the
20existing generated Gazelle manifest.
21*/
22package test
23
24import (
25	"os"
26	"path/filepath"
27	"testing"
28
29	"github.com/bazelbuild/rules_go/go/runfiles"
30	"github.com/bazelbuild/rules_python/gazelle/manifest"
31)
32
33func TestGazelleManifestIsUpdated(t *testing.T) {
34	requirementsPath := os.Getenv("_TEST_REQUIREMENTS")
35	if requirementsPath == "" {
36		t.Fatal("_TEST_REQUIREMENTS must be set")
37	}
38
39	manifestPath := os.Getenv("_TEST_MANIFEST")
40	if manifestPath == "" {
41		t.Fatal("_TEST_MANIFEST must be set")
42	}
43
44	manifestFile := new(manifest.File)
45	if err := manifestFile.Decode(manifestPath); err != nil {
46		t.Fatalf("decoding manifest file: %v", err)
47	}
48
49	if manifestFile.Integrity == "" {
50		t.Fatal("failed to find the Gazelle manifest file integrity")
51	}
52
53	manifestGeneratorHashPath, err := runfiles.Rlocation(
54		os.Getenv("_TEST_MANIFEST_GENERATOR_HASH"))
55	if err != nil {
56		t.Fatalf("failed to resolve runfiles path of manifest: %v", err)
57	}
58
59	manifestGeneratorHash, err := os.Open(manifestGeneratorHashPath)
60	if err != nil {
61		t.Fatalf("opening %q: %v", manifestGeneratorHashPath, err)
62	}
63	defer manifestGeneratorHash.Close()
64
65	requirements, err := os.Open(requirementsPath)
66	if err != nil {
67		t.Fatalf("opening %q: %v", requirementsPath, err)
68	}
69	defer requirements.Close()
70
71	valid, err := manifestFile.VerifyIntegrity(manifestGeneratorHash, requirements)
72	if err != nil {
73		t.Fatalf("verifying integrity: %v", err)
74	}
75	if !valid {
76		manifestRealpath, err := filepath.EvalSymlinks(manifestPath)
77		if err != nil {
78			t.Fatalf("evaluating symlink %q: %v", manifestPath, err)
79		}
80		t.Errorf(
81			"%q is out-of-date. Follow the update instructions in that file to resolve this",
82			manifestRealpath)
83	}
84}
85