images_test.go (2729B)
1 // Copyright 2017 The Hugo 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 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package images 15 16 import ( 17 "bytes" 18 "image" 19 "image/color" 20 "image/png" 21 "path/filepath" 22 "testing" 23 24 qt "github.com/frankban/quicktest" 25 "github.com/gohugoio/hugo/config" 26 "github.com/gohugoio/hugo/deps" 27 "github.com/gohugoio/hugo/hugofs" 28 "github.com/spf13/afero" 29 "github.com/spf13/cast" 30 ) 31 32 type tstNoStringer struct{} 33 34 var configTests = []struct { 35 path any 36 input []byte 37 expect any 38 }{ 39 { 40 path: "a.png", 41 input: blankImage(10, 10), 42 expect: image.Config{ 43 Width: 10, 44 Height: 10, 45 ColorModel: color.NRGBAModel, 46 }, 47 }, 48 { 49 path: "a.png", 50 input: blankImage(10, 10), 51 expect: image.Config{ 52 Width: 10, 53 Height: 10, 54 ColorModel: color.NRGBAModel, 55 }, 56 }, 57 { 58 path: "b.png", 59 input: blankImage(20, 15), 60 expect: image.Config{ 61 Width: 20, 62 Height: 15, 63 ColorModel: color.NRGBAModel, 64 }, 65 }, 66 { 67 path: "a.png", 68 input: blankImage(20, 15), 69 expect: image.Config{ 70 Width: 10, 71 Height: 10, 72 ColorModel: color.NRGBAModel, 73 }, 74 }, 75 // errors 76 {path: tstNoStringer{}, expect: false}, 77 {path: "non-existent.png", expect: false}, 78 {path: "", expect: false}, 79 } 80 81 func TestNSConfig(t *testing.T) { 82 t.Parallel() 83 c := qt.New(t) 84 85 v := config.NewWithTestDefaults() 86 v.Set("workingDir", "/a/b") 87 88 ns := New(&deps.Deps{Fs: hugofs.NewMem(v)}) 89 90 for _, test := range configTests { 91 92 // check for expected errors early to avoid writing files 93 if b, ok := test.expect.(bool); ok && !b { 94 _, err := ns.Config(test.path) 95 c.Assert(err, qt.Not(qt.IsNil)) 96 continue 97 } 98 99 // cast path to string for afero.WriteFile 100 sp, err := cast.ToStringE(test.path) 101 c.Assert(err, qt.IsNil) 102 afero.WriteFile(ns.deps.Fs.Source, filepath.Join(v.GetString("workingDir"), sp), test.input, 0755) 103 104 result, err := ns.Config(test.path) 105 106 c.Assert(err, qt.IsNil) 107 c.Assert(result, qt.Equals, test.expect) 108 c.Assert(len(ns.cache), qt.Not(qt.Equals), 0) 109 } 110 } 111 112 func blankImage(width, height int) []byte { 113 var buf bytes.Buffer 114 img := image.NewRGBA(image.Rect(0, 0, width, height)) 115 if err := png.Encode(&buf, img); err != nil { 116 panic(err) 117 } 118 return buf.Bytes() 119 }