github.com/googleapis/api-linter@v1.65.2/rules/aip0164/request_unknown_fields_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 aip0164
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/googleapis/api-linter/rules/internal/testutils"
    21  	"github.com/jhump/protoreflect/desc/builder"
    22  )
    23  
    24  func TestRequestUnknownFields(t *testing.T) {
    25  	// Set up the testing permutations.
    26  	tests := []struct {
    27  		testName    string
    28  		messageName string
    29  		fieldName   string
    30  		fieldType   *builder.FieldType
    31  		problems    testutils.Problems
    32  	}{
    33  		{"Etag", "UndeleteBookRequest", "etag", builder.FieldTypeString(), testutils.Problems{}},
    34  		{"RequestId", "UndeleteBookRequest", "request_id", builder.FieldTypeString(), testutils.Problems{}},
    35  		{"ValidateOnly", "UndeleteBookRequest", "validate_only", builder.FieldTypeBool(), testutils.Problems{}},
    36  		{"Invalid", "UndeleteBookRequest", "application_id", builder.FieldTypeString(), testutils.Problems{{
    37  			Message: "Unexpected field",
    38  		}}},
    39  		{"Irrelevant", "RemoveBookRequest", "application_id", builder.FieldTypeString(), testutils.Problems{}},
    40  	}
    41  
    42  	// Run each test individually.
    43  	for _, test := range tests {
    44  		t.Run(test.testName, func(t *testing.T) {
    45  			// Create an appropriate message descriptor.
    46  			message, err := builder.NewMessage(test.messageName).AddField(
    47  				builder.NewField("name", builder.FieldTypeString()),
    48  			).AddField(
    49  				builder.NewField(test.fieldName, test.fieldType),
    50  			).Build()
    51  			if err != nil {
    52  				t.Fatalf("Could not build UndeleteBookRequest message.")
    53  			}
    54  
    55  			// Run the lint rule, and establish that it returns the correct problems.
    56  			wantProblems := test.problems.SetDescriptor(message.FindFieldByName(test.fieldName))
    57  			gotProblems := requestUnknownFields.Lint(message.GetFile())
    58  			if diff := wantProblems.Diff(gotProblems); diff != "" {
    59  				t.Errorf(diff)
    60  			}
    61  		})
    62  	}
    63  }