github.com/googleapis/api-linter@v1.65.2/rules/internal/utils/find_test.go (about)

     1  // Copyright 2020 Google LLC
     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  //     https://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  package utils
    16  
    17  import (
    18  	"strings"
    19  	"testing"
    20  
    21  	"github.com/googleapis/api-linter/rules/internal/testutils"
    22  )
    23  
    24  func TestFindMessage(t *testing.T) {
    25  	files := testutils.ParseProtoStrings(t, map[string]string{
    26  		"a.proto": `
    27  			package test;
    28  			message Book {}
    29  		`,
    30  		"b.proto": `
    31  			package other;
    32  			message Scroll {}
    33  		`,
    34  		"c.proto": `
    35  			package test;
    36  			import "a.proto";
    37  			import "b.proto";
    38  		`,
    39  	})
    40  	if book := FindMessage(files["c.proto"], "Book"); book == nil {
    41  		t.Errorf("Got nil, expected Book message.")
    42  	}
    43  	if scroll := FindMessage(files["c.proto"], "Scroll"); scroll != nil {
    44  		t.Errorf("Got Sctoll message, expected nil.")
    45  	}
    46  }
    47  
    48  func TestFindFieldDotNotation(t *testing.T) {
    49  	file := testutils.ParseProto3String(t, `
    50  		package test;
    51  		
    52  		message CreateBookRequest {
    53  			string parent = 1;
    54  
    55  			Book book = 2;
    56  		}
    57  
    58  		message Book {
    59  			string name = 1;
    60  
    61  			message PublishingInfo {
    62  				string publisher = 1;
    63  				int32 edition = 2;
    64  			}
    65  
    66  			PublishingInfo publishing_info = 2;
    67  		}
    68  	`)
    69  	msg := file.GetMessageTypes()[0]
    70  
    71  	for _, tst := range []struct {
    72  		name, path string
    73  	}{
    74  		{"top_level", "parent"},
    75  		{"nested", "book.name"},
    76  		{"double_nested", "book.publishing_info.publisher"},
    77  	} {
    78  		t.Run(tst.name, func(t *testing.T) {
    79  			split := strings.Split(tst.path, ".")
    80  			want := split[len(split)-1]
    81  
    82  			f := FindFieldDotNotation(msg, tst.path)
    83  
    84  			if f == nil {
    85  				t.Errorf("Got nil, expected %q field", want)
    86  			} else if got := f.GetName(); got != want {
    87  				t.Errorf("Got %q, expected %q", got, want)
    88  			}
    89  		})
    90  	}
    91  
    92  }