1// Copyright 2022 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 "io/ioutil" 19 "os" 20 "path/filepath" 21 "strings" 22 "testing" 23) 24 25func Test_filesHaveSameContents(t *testing.T) { 26 27 tests := []struct { 28 name string 29 a string 30 b string 31 missingA bool 32 missingB bool 33 34 equal bool 35 }{ 36 { 37 name: "empty", 38 a: "", 39 b: "", 40 equal: true, 41 }, 42 { 43 name: "equal", 44 a: "foo", 45 b: "foo", 46 equal: true, 47 }, 48 { 49 name: "unequal", 50 a: "foo", 51 b: "bar", 52 equal: false, 53 }, 54 { 55 name: "unequal different sizes", 56 a: "foo", 57 b: "foobar", 58 equal: false, 59 }, 60 { 61 name: "equal large", 62 a: strings.Repeat("a", 2*1024*1024), 63 b: strings.Repeat("a", 2*1024*1024), 64 equal: true, 65 }, 66 { 67 name: "equal large unaligned", 68 a: strings.Repeat("a", 2*1024*1024+10), 69 b: strings.Repeat("a", 2*1024*1024+10), 70 equal: true, 71 }, 72 { 73 name: "unequal large", 74 a: strings.Repeat("a", 2*1024*1024), 75 b: strings.Repeat("a", 2*1024*1024-1) + "b", 76 equal: false, 77 }, 78 { 79 name: "unequal large unaligned", 80 a: strings.Repeat("a", 2*1024*1024+10), 81 b: strings.Repeat("a", 2*1024*1024+9) + "b", 82 equal: false, 83 }, 84 { 85 name: "missing a", 86 missingA: true, 87 b: "foo", 88 equal: false, 89 }, 90 { 91 name: "missing b", 92 a: "foo", 93 missingB: true, 94 equal: false, 95 }, 96 } 97 for _, tt := range tests { 98 t.Run(tt.name, func(t *testing.T) { 99 tempDir, err := os.MkdirTemp("", "testFilesHaveSameContents") 100 if err != nil { 101 t.Fatalf("failed to create temp dir: %s", err) 102 } 103 defer os.RemoveAll(tempDir) 104 105 fileA := filepath.Join(tempDir, "a") 106 fileB := filepath.Join(tempDir, "b") 107 108 if !tt.missingA { 109 err := ioutil.WriteFile(fileA, []byte(tt.a), 0666) 110 if err != nil { 111 t.Fatalf("failed to write %s: %s", fileA, err) 112 } 113 } 114 115 if !tt.missingB { 116 err := ioutil.WriteFile(fileB, []byte(tt.b), 0666) 117 if err != nil { 118 t.Fatalf("failed to write %s: %s", fileB, err) 119 } 120 } 121 122 if got := filesHaveSameContents(fileA, fileB); got != tt.equal { 123 t.Errorf("filesHaveSameContents() = %v, want %v", got, tt.equal) 124 } 125 }) 126 } 127} 128