1// Copyright 2018 The Bazel Authors. 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 compile 16 17import ( 18 "io/ioutil" 19 "os" 20 "path/filepath" 21 "reflect" 22 "sort" 23 "strings" 24 "testing" 25) 26 27func TestDirReplacer(t *testing.T) { 28 29 qualified := []string{ 30 "res/values-en-rGB/strings.xml", 31 "res/values-es-rMX/strings.xml", 32 "res/values-sr-rLatn/strings.xml", 33 "res/values-sr-rLatn-xhdpi/strings.xml", 34 "res/values-es-419/strings.xml", 35 "res/values-es-419-xhdpi/strings.xml"} 36 37 expected := []string{ 38 "res/values-en-rGB/strings.xml", 39 "res/values-es-rMX/strings.xml", 40 "res/values-b+sr+Latn/strings.xml", 41 "res/values-b+sr+Latn-xhdpi/strings.xml", 42 "res/values-b+es+419/strings.xml", 43 "res/values-b+es+419-xhdpi/strings.xml"} 44 45 var actual []string 46 for _, d := range qualified { 47 actual = append(actual, dirReplacer.Replace(d)) 48 } 49 50 if !reflect.DeepEqual(expected, actual) { 51 t.Errorf("dirReplacer.Replace(%v) = %v want %v", qualified, actual, expected) 52 } 53} 54 55func TestSanitizeDirs(t *testing.T) { 56 base, err := ioutil.TempDir("", "res-") 57 dirs := []string{ 58 "values", 59 "values-bas-foo", 60 "values-foo-rNOTGOOD", 61 "values-foo-rNOBUENO-baz", 62 } 63 for _, dir := range dirs { 64 if err := os.Mkdir(filepath.Join(base, dir), 0777); err != nil { 65 t.Fatal(err) 66 } 67 } 68 69 var expected sort.StringSlice 70 expected = append(expected, []string{ 71 "values", 72 "values-bas-foo", 73 "values-foo-rVERY-GOOD", 74 "values-foo-rMUCHO-BUENO-baz"}...) 75 76 r := strings.NewReplacer("NOTGOOD", "VERY-GOOD", "NOBUENO", "MUCHO-BUENO") 77 if err := sanitizeDirs(base, r); err != nil { 78 t.Fatalf("sanitizeDirs(%s, %v) failed %v", base, r, err) 79 } 80 81 src, err := os.Open(base) 82 if err != nil { 83 t.Fatal(err) 84 } 85 defer src.Close() 86 87 fs, err := src.Readdir(-1) 88 if err != nil { 89 t.Fatal(err) 90 } 91 92 actual := make(map[string]bool) 93 for _, f := range fs { 94 actual[f.Name()] = true 95 } 96 97 for _, dir := range dirs { 98 expected := r.Replace(dir) 99 if expected != dir && actual[dir] { 100 t.Errorf("sanitizeDirs(%s) = %v got invalid dir %s. Expected %s ", base, actual, dir, expected) 101 } 102 if _, ok := actual[expected]; !ok { 103 t.Errorf("sanitizeDirs(%s) = %v missing dir %s", base, actual, expected) 104 } 105 } 106 107} 108