|
| 1 | +package svg |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "regexp" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/imgproxy/imgproxy/v3/config" |
| 10 | + "github.com/imgproxy/imgproxy/v3/imagedata" |
| 11 | + "github.com/imgproxy/imgproxy/v3/imagetype" |
| 12 | + "github.com/stretchr/testify/require" |
| 13 | + "github.com/stretchr/testify/suite" |
| 14 | +) |
| 15 | + |
| 16 | +type SvgTestSuite struct { |
| 17 | + suite.Suite |
| 18 | +} |
| 19 | + |
| 20 | +func (s *SvgTestSuite) SetupSuite() { |
| 21 | + config.Reset() |
| 22 | + |
| 23 | + err := imagedata.Init() |
| 24 | + require.Nil(s.T(), err) |
| 25 | +} |
| 26 | + |
| 27 | +func (s *SvgTestSuite) readTestFile(name string) *imagedata.ImageData { |
| 28 | + wd, err := os.Getwd() |
| 29 | + require.Nil(s.T(), err) |
| 30 | + |
| 31 | + data, err := os.ReadFile(filepath.Join(wd, "..", "testdata", name)) |
| 32 | + require.Nil(s.T(), err) |
| 33 | + |
| 34 | + return &imagedata.ImageData{ |
| 35 | + Type: imagetype.SVG, |
| 36 | + Data: data, |
| 37 | + Headers: map[string]string{ |
| 38 | + "Content-Type": "image/svg+xml", |
| 39 | + "Cache-Control": "public, max-age=12345", |
| 40 | + }, |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func (s *SvgTestSuite) TestSanitize() { |
| 45 | + origin := s.readTestFile("test1.svg") |
| 46 | + expected := s.readTestFile("test1.sanitized.svg") |
| 47 | + |
| 48 | + actual, err := Sanitize(origin) |
| 49 | + |
| 50 | + require.Nil(s.T(), err) |
| 51 | + require.Equal(s.T(), string(expected.Data), string(actual.Data)) |
| 52 | + require.Equal(s.T(), origin.Headers, actual.Headers) |
| 53 | +} |
| 54 | + |
| 55 | +func (s *SvgTestSuite) TestFixUnsupportedDropShadow() { |
| 56 | + origin := s.readTestFile("test1.drop-shadow.svg") |
| 57 | + expected := s.readTestFile("test1.drop-shadow.fixed.svg") |
| 58 | + |
| 59 | + actual, changed, err := FixUnsupported(origin) |
| 60 | + |
| 61 | + // `FixUnsupported` generates random IDs, we need to replace them for the test |
| 62 | + re := regexp.MustCompile(`"ds(in|of)-.+?"`) |
| 63 | + actualData := re.ReplaceAllString(string(actual.Data), `"ds$1-test"`) |
| 64 | + |
| 65 | + require.Nil(s.T(), err) |
| 66 | + require.True(s.T(), changed) |
| 67 | + require.Equal(s.T(), string(expected.Data), actualData) |
| 68 | + require.Equal(s.T(), origin.Headers, actual.Headers) |
| 69 | +} |
| 70 | + |
| 71 | +func (s *SvgTestSuite) TestFixUnsupportedNothingChanged() { |
| 72 | + origin := s.readTestFile("test1.svg") |
| 73 | + |
| 74 | + actual, changed, err := FixUnsupported(origin) |
| 75 | + |
| 76 | + require.Nil(s.T(), err) |
| 77 | + require.False(s.T(), changed) |
| 78 | + require.Equal(s.T(), origin, actual) |
| 79 | +} |
| 80 | + |
| 81 | +func TestSvg(t *testing.T) { |
| 82 | + suite.Run(t, new(SvgTestSuite)) |
| 83 | +} |
0 commit comments