Debian Codegraph @

internal/librariangen/request/request_test.go

raw
1 // Copyright 2025 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 // 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 package request
16
17 import (
18 "os"
19 "path/filepath"
20 "testing"
21
22 "github.com/google/go-cmp/cmp"
23 )
24
25 func TestParseLibrary(t *testing.T) {
26 testCases := []struct {
27 name string
28 content string
29 want *Library
30 wantErr bool
31 }{
32 {
33 name: "valid request",
34 content: `{
35 "id": "asset",
36 "version": "1.15.0",
37 "apis": [
38 {
39 "path": "google/cloud/asset/v1",
40 "service_config": "cloudasset_v1.yaml"
41 }
42 ],
43 "source_roots": ["asset/apiv1"],
44 "preserve_regex": ["asset/apiv1/foo.go"],
45 "remove_regex": ["asset/apiv1/bar.go"]
46 }`,
47 want: &Library{
48 ID: "asset",
49 Version: "1.15.0",
50 APIs: []API{
51 {
52 Path: "google/cloud/asset/v1",
53 ServiceConfig: "cloudasset_v1.yaml",
54 },
55 },
56 SourcePaths: []string{"asset/apiv1"},
57 PreserveRegex: []string{"asset/apiv1/foo.go"},
58 RemoveRegex: []string{"asset/apiv1/bar.go"},
59 },
60 wantErr: false,
61 },
62 {
63 name: "malformed json",
64 content: `{"id": "foo",`,
65 wantErr: true,
66 },
67 }
68
69 for _, tc := range testCases {
70 t.Run(tc.name, func(t *testing.T) {
71 tmpDir := t.TempDir()
72 reqPath := filepath.Join(tmpDir, "generate-request.json")
73 if err := os.WriteFile(reqPath, []byte(tc.content), 0644); err != nil {
74 t.Fatalf("failed to write test file: %v", err)
75 }
76
77 got, err := ParseLibrary(reqPath)
78
79 if (err != nil) != tc.wantErr {
80 t.Errorf("Parse() error = %v, wantErr %v", err, tc.wantErr)
81 return
82 }
83
84 if !tc.wantErr {
85 if diff := cmp.Diff(tc.want, got); diff != "" {
86 t.Errorf("Parse() mismatch (-want +got):\n%s", diff)
87 }
88 }
89 })
90 }
91 }
92
93 func TestParseLibrary_FileNotFound(t *testing.T) {
94 _, err := ParseLibrary("non-existent-file.json")
95 if err == nil {
96 t.Error("Parse() expected error for non-existent file, got nil")
97 }
98 }