1// Copyright 2019 Google Inc. All rights reserved.
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
15package main
16
17import (
18	"archive/zip"
19	"bytes"
20	"reflect"
21	"testing"
22)
23
24func bytesToZipArtifactFile(name string, data []byte) *ZipArtifactFile {
25	buf := &bytes.Buffer{}
26	w := zip.NewWriter(buf)
27	f, err := w.Create(name)
28	if err != nil {
29		panic(err)
30	}
31	_, err = f.Write(data)
32	if err != nil {
33		panic(err)
34	}
35
36	w.Close()
37
38	r, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
39	if err != nil {
40		panic(err)
41	}
42
43	return &ZipArtifactFile{r.File[0]}
44}
45
46var f1a = bytesToZipArtifactFile("dir/f1", []byte(`
47a
48foo: bar
49c
50`))
51
52var f1b = bytesToZipArtifactFile("dir/f1", []byte(`
53a
54foo: baz
55c
56`))
57
58var f2 = bytesToZipArtifactFile("dir/f2", nil)
59
60func Test_applyAllowLists(t *testing.T) {
61	type args struct {
62		diff       zipDiff
63		allowLists []allowList
64	}
65	tests := []struct {
66		name    string
67		args    args
68		want    zipDiff
69		wantErr bool
70	}{
71		{
72			name: "simple",
73			args: args{
74				diff: zipDiff{
75					onlyInA: []*ZipArtifactFile{f1a, f2},
76				},
77				allowLists: []allowList{{path: "dir/f1"}},
78			},
79			want: zipDiff{
80				onlyInA: []*ZipArtifactFile{f2},
81			},
82		},
83		{
84			name: "glob",
85			args: args{
86				diff: zipDiff{
87					onlyInA: []*ZipArtifactFile{f1a, f2},
88				},
89				allowLists: []allowList{{path: "dir/*"}},
90			},
91			want: zipDiff{},
92		},
93		{
94			name: "modified",
95			args: args{
96				diff: zipDiff{
97					modified: [][2]*ZipArtifactFile{{f1a, f1b}},
98				},
99				allowLists: []allowList{{path: "dir/*"}},
100			},
101			want: zipDiff{},
102		},
103		{
104			name: "matching lines",
105			args: args{
106				diff: zipDiff{
107					modified: [][2]*ZipArtifactFile{{f1a, f1b}},
108				},
109				allowLists: []allowList{{path: "dir/*", ignoreMatchingLines: []string{"foo: .*"}}},
110			},
111			want: zipDiff{},
112		},
113	}
114	for _, tt := range tests {
115		t.Run(tt.name, func(t *testing.T) {
116			got, err := applyAllowLists(tt.args.diff, tt.args.allowLists)
117			if (err != nil) != tt.wantErr {
118				t.Errorf("Test_applyAllowLists() error = %v, wantErr %v", err, tt.wantErr)
119				return
120			}
121			if !reflect.DeepEqual(got, tt.want) {
122				t.Errorf("Test_applyAllowLists() = %v, want %v", got, tt.want)
123			}
124		})
125	}
126}
127