github.com/pdfcpu/pdfcpu@v0.11.1/pkg/api/test/keyword_test.go (about) 1 /* 2 Copyright 2020 The pdf Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package test 18 19 import ( 20 "os" 21 "path/filepath" 22 "testing" 23 24 "github.com/pdfcpu/pdfcpu/pkg/api" 25 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model" 26 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/types" 27 ) 28 29 func listKeywordsFile(t *testing.T, fileName string, conf *model.Configuration) ([]string, error) { 30 t.Helper() 31 32 msg := "listKeywords" 33 34 f, err := os.Open(fileName) 35 if err != nil { 36 t.Fatalf("%s open: %v\n", msg, err) 37 } 38 defer f.Close() 39 40 return api.Keywords(f, conf) 41 } 42 43 func listKeywords(t *testing.T, msg, fileName string, want []string) []string { 44 t.Helper() 45 46 got, err := listKeywordsFile(t, fileName, nil) 47 if err != nil { 48 t.Fatalf("%s list keywords: %v\n", msg, err) 49 } 50 51 // # of keywords must be want 52 if len(got) != len(want) { 53 t.Fatalf("%s: list keywords %s: want %d got %d\n", msg, fileName, len(want), len(got)) 54 } 55 56 for _, v := range got { 57 if !types.MemberOf(v, want) { 58 t.Fatalf("%s: list keywords %s: want %v got %v\n", msg, fileName, want, got) 59 } 60 } 61 return got 62 } 63 64 func TestKeywords(t *testing.T) { 65 msg := "TestKeywords" 66 67 fileName := filepath.Join(outDir, "go.pdf") 68 if err := copyFile(t, filepath.Join(inDir, "go.pdf"), fileName); err != nil { 69 t.Fatalf("%s: copyFile: %v\n", msg, err) 70 } 71 72 // # of keywords must be 0 73 listKeywords(t, msg, fileName, nil) 74 75 keywords := []string{"Ö", "你好"} 76 if err := api.AddKeywordsFile(fileName, "", keywords, nil); err != nil { 77 t.Fatalf("%s add keywords: %v\n", msg, err) 78 } 79 listKeywords(t, msg, fileName, keywords) 80 81 keywords = []string{"world"} 82 if err := api.AddKeywordsFile(fileName, "", keywords, nil); err != nil { 83 t.Fatalf("%s add keywords: %v\n", msg, err) 84 } 85 listKeywords(t, msg, fileName, []string{"Ö", "你好", "world"}) 86 87 if err := api.RemoveKeywordsFile(fileName, "", []string{"你好"}, nil); err != nil { 88 t.Fatalf("%s remove 1 keyword: %v\n", msg, err) 89 } 90 listKeywords(t, msg, fileName, []string{"Ö", "world"}) 91 92 if err := api.RemoveKeywordsFile(fileName, "", nil, nil); err != nil { 93 t.Fatalf("%s remove all keywords: %v\n", msg, err) 94 } 95 96 // # of keywords must be 0 97 listKeywords(t, msg, fileName, nil) 98 }