Skip to content

Commit 5e8a43b

Browse files
feat(modelarmor): code refactor
1 parent a9f0e31 commit 5e8a43b

File tree

6 files changed

+69
-165
lines changed

6 files changed

+69
-165
lines changed

modelarmor/create_template.go

-105
This file was deleted.

modelarmor/go.mod

-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ require (
66
cloud.google.com/go/modelarmor v0.1.0
77
github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736
88
github.com/google/uuid v1.6.0
9-
github.com/joho/godotenv v1.5.1
109
google.golang.org/api v0.226.0
1110
google.golang.org/grpc v1.71.0
1211
)

modelarmor/go.sum

-2
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,6 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.5 h1:VgzTY2jogw3xt39CusE
6767
github.com/googleapis/enterprise-certificate-proxy v0.3.5/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA=
6868
github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q=
6969
github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA=
70-
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
71-
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
7270
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
7371
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
7472
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=

modelarmor/modelarmor_test.go

+55-19
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,16 @@ import (
2727

2828
"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
2929
"github.com/google/uuid"
30-
"github.com/joho/godotenv"
3130
"google.golang.org/api/option"
3231
grpccodes "google.golang.org/grpc/codes"
3332
grpcstatus "google.golang.org/grpc/status"
3433
)
3534

35+
// testLocation returns the test location from the environment variable `GOLANG_SAMPLES_LOCATION`.
36+
// If not set, the test is skipped.
3637
func testLocation(t *testing.T) string {
3738
t.Helper()
3839

39-
// Load the test.env file
40-
err := godotenv.Load("./testdata/env/test.env")
41-
if err != nil {
42-
t.Fatalf("failed to load test environment file: %v", err)
43-
}
44-
4540
v := os.Getenv("GOLANG_SAMPLES_LOCATION")
4641
if v == "" {
4742
t.Skip("testIamUser: missing GOLANG_SAMPLES_LOCATION")
@@ -50,36 +45,76 @@ func testLocation(t *testing.T) string {
5045
return v
5146
}
5247

48+
// testClient initializes and returns a new Model Armor client and context
49+
// for use in tests. The client is created using the location-specific endpoint.
5350
func testClient(t *testing.T) (*modelarmor.Client, context.Context) {
5451
t.Helper()
5552

5653
ctx := context.Background()
5754

58-
locationId := testLocation(t)
55+
locationID := testLocation(t)
5956

60-
//Endpoint to send the request to regional server
61-
client, err := modelarmor.NewClient(ctx,
62-
option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationId)),
63-
)
57+
// Create options for Model Armor client.
58+
opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
59+
// Create the Model Armor client.
60+
client, err := modelarmor.NewClient(ctx, opts)
6461
if err != nil {
6562
t.Fatalf("failed to create client: %v", err)
6663
}
6764

6865
return client, ctx
6966
}
7067

68+
// testModelArmorTemplate creates a new ModelArmor template for use in tests.
69+
// It returns the created template or an error.
70+
func testModelArmorTemplate(t *testing.T, templateID string) (*modelarmorpb.Template, error) {
71+
t.Helper()
72+
tc := testutil.SystemTest(t)
73+
locationID := testLocation(t)
74+
client, ctx := testClient(t)
75+
76+
template := &modelarmorpb.Template{
77+
FilterConfig: &modelarmorpb.FilterConfig{
78+
PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{
79+
FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED,
80+
ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE,
81+
},
82+
MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{
83+
FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED,
84+
},
85+
},
86+
}
87+
88+
req := &modelarmorpb.CreateTemplateRequest{
89+
Parent: fmt.Sprintf("projects/%s/locations/%s", tc.ProjectID, locationID),
90+
TemplateId: templateID,
91+
Template: template,
92+
}
93+
94+
response, err := client.CreateTemplate(ctx, req)
95+
if err != nil {
96+
return nil, fmt.Errorf("failed to create template: %v", err)
97+
}
98+
99+
return response, err
100+
}
101+
102+
// testCleanupTemplate deletes a Model Armor template by name, used for cleanup
103+
// after tests. Ignores errors if the template is already deleted.
71104
func testCleanupTemplate(t *testing.T, templateName string) {
72105
t.Helper()
73106

74107
client, ctx := testClient(t)
75108
if err := client.DeleteTemplate(ctx, &modelarmorpb.DeleteTemplateRequest{Name: templateName}); err != nil {
76109
if terr, ok := grpcstatus.FromError(err); !ok || terr.Code() != grpccodes.NotFound {
77-
t.Fatalf("testCleanupTemplate: failed to delete template %s: %v", templateName, err)
110+
t.Fatalf("testCleanupTemplate: failed to delete template: %v", err)
78111
}
79112
}
80113

81114
}
82115

116+
// TestScreenPDFFile scrrens the pdf file content and Sanitize
117+
// the content with the Model Armor.
83118
func TestScreenPDFFile(t *testing.T) {
84119
pdfContentBase := `"JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9UaXRsZSAoVW50aXRsZWQgZG9jdW1lbnQpCi9Qcm9kdWNlciAoU2tp
85120
YS9QREYgbTEzNSBHb29nbGUgRG9jcyBSZW5kZXJlcik+PgplbmRvYmoKMyAwIG9iago8PC9jYSAxCi9CTSAvTm9y
@@ -391,18 +426,19 @@ MDAwMTg5MTQgMDAwMDAgbiAKMDAwMDAxOTMyOSAwMDAwMCBuIAp0cmFpbGVyCjw8L1NpemUgMTkKL1Jv
391426
MCBSCi9JbmZvIDEgMCBSPj4Kc3RhcnR4cmVmCjE5ODQ0CiUlRU9GCg=="`
392427
tc := testutil.SystemTest(t)
393428
templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String())
394-
395-
var b bytes.Buffer
396-
if _, err := createModelArmorTemplate(&b, tc.ProjectID, testLocation(t), templateID); err != nil {
429+
locationID := testLocation(t)
430+
templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID)
431+
var buf bytes.Buffer
432+
if _, err := testModelArmorTemplate(t, templateID); err != nil {
397433
t.Fatal(err)
398434
}
399-
defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, testLocation(t), templateID))
435+
defer testCleanupTemplate(t, templateName)
400436

401-
if _, err := screenPDFFile(&b, tc.ProjectID, testLocation(t), templateID, pdfContentBase); err != nil {
437+
if err := screenPDFFile(&buf, tc.ProjectID, testLocation(t), templateID, pdfContentBase); err != nil {
402438
t.Fatal(err)
403439
}
404440

405-
if got, want := b.String(), "PDF screening sanitization result: "; !strings.Contains(got, want) {
441+
if got, want := buf.String(), "PDF screening sanitization result: "; !strings.Contains(got, want) {
406442
t.Errorf("screenPdf: expected %q to contain %q", got, want)
407443
}
408444
}

modelarmor/screen_pdf_file.go

+14-35
Original file line numberDiff line numberDiff line change
@@ -32,41 +32,20 @@ import (
3232
//
3333
// This method screens a PDF file based on the project, location, and template settings.
3434
//
35-
// Args:
36-
//
37-
// w io.Writer: The writer to use for logging.
38-
// projectID string: The ID of the project.
39-
// locationID string: The ID of the location.
40-
// templateID string: The ID of the template.
41-
// pdfContentBase64 string: The base64-encoded content of the PDF file.
42-
//
43-
// Returns:
44-
//
45-
// *modelarmorpb.SanitizeUserPromptResponse: The response from screening the PDF file.
46-
// error: Any error that occurred during screening.
47-
//
48-
// Example:
49-
//
50-
// response, err := screenPDFFile(
51-
// os.Stdout,
52-
// "my-project",
53-
// "my-location",
54-
// "my-template",
55-
// "base64-encoded-pdf-content",
56-
// )
57-
// if err != nil {
58-
// log.Fatal(err)
59-
// }
60-
// fmt.Println(response)
61-
func screenPDFFile(w io.Writer, projectID, locationID, templateID, pdfContentBase64 string) (*modelarmorpb.SanitizeUserPromptResponse, error) {
35+
// w io.Writer: The writer to use for logging.
36+
// projectID string: The ID of the project.
37+
// locationID string: The ID of the location.
38+
// templateID string: The ID of the template.
39+
// pdfContentBase64 string: The base64-encoded content of the PDF file.
40+
func screenPDFFile(w io.Writer, projectID, locationID, templateID, pdfContentBase64 string) error {
6241
ctx := context.Background()
6342

43+
// Create options for Model Armor client.
44+
opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
6445
// Create the Model Armor client.
65-
client, err := modelarmor.NewClient(ctx,
66-
option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)),
67-
)
46+
client, err := modelarmor.NewClient(ctx, opts)
6847
if err != nil {
69-
return nil, fmt.Errorf("failed to create client: %v", err)
48+
return fmt.Errorf("failed to create client: %w", err)
7049
}
7150
defer client.Close()
7251

@@ -89,13 +68,13 @@ func screenPDFFile(w io.Writer, projectID, locationID, templateID, pdfContentBas
8968
// Sanitize the user prompt.
9069
response, err := client.SanitizeUserPrompt(ctx, req)
9170
if err != nil {
92-
return nil, fmt.Errorf("failed to sanitize PDF content for template %s: %v", templateID, err)
71+
return fmt.Errorf("failed to sanitize PDF content for template %s: %w", templateID, err)
9372
}
9473

9574
// Sanitization Result.
9675
fmt.Fprintf(w, "PDF screening sanitization result: %v\n", response)
9776

98-
// [END modelarmor_screen_pdf_file]
99-
100-
return response, nil
77+
return err
10178
}
79+
80+
// [END modelarmor_screen_pdf_file]

modelarmor/testdata/env/test.env

-3
This file was deleted.

0 commit comments

Comments
 (0)