github.com/stackb/rules_proto@v0.0.0-20240221195024-5428336c51f1/pkg/rule/rules_go/go_library_test.go (about)

     1  // gencopy is a utility program that copies bazel outputs back into the
     2  // workspace source tree.  Ideally, you don't have any generated files committed
     3  // to VCS, but sometimes you do.
     4  //
     5  package rules_go
     6  
     7  import (
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/bazelbuild/bazel-gazelle/rule"
    12  	"github.com/stackb/rules_proto/pkg/protoc"
    13  )
    14  
    15  func TestGoLibraryRuleImportPath(t *testing.T) {
    16  	for name, tc := range map[string]struct {
    17  		files       []*protoc.File
    18  		ruleOptions []string
    19  		plugins     []*protoc.PluginConfiguration
    20  		want        string // importpath string
    21  	}{
    22  		"degenerate": {},
    23  		"from go_package option": {
    24  			files: []*protoc.File{
    25  				newProtoFile(t, "proto", "foo.proto",
    26  					`syntax = "proto3";`,
    27  					`option go_package = "github.com/example.com/foo";`,
    28  				),
    29  			},
    30  			want: "github.com/example.com/foo",
    31  		},
    32  		"from rule importmapping option": {
    33  			files: []*protoc.File{
    34  				newProtoFile(t, "proto", "foo.proto"),
    35  			},
    36  			ruleOptions: []string{
    37  				"Mproto/foo.proto=github.com/example.com/foo",
    38  			},
    39  			want: "github.com/example.com/foo",
    40  		},
    41  		"from plugin importmapping option": {
    42  			files: []*protoc.File{
    43  				newProtoFile(t, "proto", "foo.proto"),
    44  			},
    45  			plugins: []*protoc.PluginConfiguration{
    46  				{
    47  					Options: []string{
    48  						"Mproto/foo.proto=github.com/example.com/foo",
    49  					},
    50  				},
    51  			},
    52  			want: "github.com/example.com/foo",
    53  		},
    54  	} {
    55  		t.Run(name, func(t *testing.T) {
    56  			ruleConfig := protoc.NewLanguageRuleConfig(nil, "proto_go_library")
    57  			for _, d := range tc.ruleOptions {
    58  				ruleConfig.Options[d] = true
    59  			}
    60  			gazelleRule := rule.NewRule("proto_library", "foo_proto")
    61  			goRule := &goLibraryRule{
    62  				pc: &protoc.ProtocConfiguration{
    63  					Plugins: tc.plugins,
    64  					Library: protoc.NewOtherProtoLibrary(nil, gazelleRule, tc.files...),
    65  				},
    66  				ruleConfig: ruleConfig,
    67  			}
    68  			got := goRule.importPath()
    69  			if tc.want != got {
    70  				t.Errorf("want %q, got %q", tc.want, got)
    71  			}
    72  		})
    73  	}
    74  }
    75  
    76  func newProtoFile(t *testing.T, dir, name string, lines ...string) *protoc.File {
    77  	f := protoc.NewFile(dir, name)
    78  	content := strings.Join(lines, "\n")
    79  	in := strings.NewReader(content)
    80  	if err := f.ParseReader(in); err != nil {
    81  		t.Fatal(err)
    82  	}
    83  	return f
    84  }