github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/app/imaging/svg_test.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package imaging 5 6 import ( 7 "fmt" 8 "io" 9 "strings" 10 "testing" 11 ) 12 13 //nolint:unparam 14 func generateSVGData(width int, height int, useViewBox bool, useDimensions bool, useAlternateFormat bool) io.Reader { 15 var ( 16 viewBoxAttribute = "" 17 widthAttribute = "" 18 heightAttribute = "" 19 ) 20 if useViewBox == true { 21 separator := " " 22 if useAlternateFormat == true { 23 separator = ", " 24 } 25 viewBoxAttribute = fmt.Sprintf(` viewBox="0%s0%s%d%s%d"`, separator, separator, width, separator, height) 26 } 27 if useDimensions == true && width > 0 && height > 0 { 28 units := "" 29 if useAlternateFormat == true { 30 units = "px" 31 } 32 widthAttribute = fmt.Sprintf(` width="%d%s"`, width, units) 33 heightAttribute = fmt.Sprintf(` height="%d%s"`, height, units) 34 } 35 svgString := fmt.Sprintf(`<svg%s%s%s></svg>`, widthAttribute, heightAttribute, viewBoxAttribute) 36 return strings.NewReader(svgString) 37 } 38 39 func TestParseValidSVGData(t *testing.T) { 40 var width, height int = 300, 300 41 validSVGs := []io.Reader{ 42 generateSVGData(width, height, true, true, false), // properly formed viewBox, width & height 43 generateSVGData(width, height, true, true, true), // properly formed viewBox, width & height; alternate format 44 generateSVGData(width, height, false, true, false), // missing viewBox, properly formed width & height 45 generateSVGData(width, height, false, true, true), // missing viewBox, properly formed width & height; alternate format 46 } 47 for index, svg := range validSVGs { 48 svgInfo, err := ParseSVG(svg) 49 if err != nil { 50 t.Errorf("Should be able to parse SVG attributes at index %d, but was not able to: err = %v", index, err) 51 } else { 52 if svgInfo.Width != width { 53 t.Errorf("Expecting a width of %d for SVG at index %d, but it was %d instead.", width, index, svgInfo.Width) 54 } 55 56 if svgInfo.Height != height { 57 t.Errorf("Expecting a height of %d for SVG at index %d, but it was %d instead.", height, index, svgInfo.Height) 58 } 59 } 60 } 61 } 62 63 func TestParseInvalidSVGData(t *testing.T) { 64 var width, height int = 300, 300 65 invalidSVGs := []io.Reader{ 66 generateSVGData(width, height, false, false, false), // missing viewBox, width & height 67 generateSVGData(width, 0, false, true, false), // missing viewBox, malformed width & height 68 generateSVGData(width, 0, false, true, false), // missing viewBox, malformed height, properly formed width 69 } 70 for index, svg := range invalidSVGs { 71 _, err := ParseSVG(svg) 72 if err == nil { 73 t.Errorf("Should not be able to parse SVG attributes at index %d, but was definitely able to!", index) 74 } 75 } 76 }