Clover icon

Magnolia Imaging Module 3.4.2-SUPPORT-10161

  1. Project Clover database Tue Jul 16 2019 23:33:19 EEST
  2. Package info.magnolia.imaging

File AbstractImagingTest.java

 

Coverage histogram

../../../img/srcFileCovDistChart9.png
42% of files have more coverage

Code metrics

12
85
18
2
288
188
27
0.32
4.72
9
1.5

Classes

Class Line # Actions
AbstractImagingTest 83 84 0% 26 19
0.831858483.2%
AbstractImagingTest.SampleImageStreamer 263 1 0% 1 0
1.0100%
 

Contributing tests

No tests hitting this source file were found.

Source view

1    /**
2    * This file Copyright (c) 2009-2018 Magnolia International
3    * Ltd. (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10    * This file is distributed in the hope that it will be
11    * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12    * implied warranty of MERCHANTABILITY or FITNESS FOR A
13    * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14    * Redistribution, except as permitted by whichever of the GPL
15    * or MNA you select, is prohibited.
16    *
17    * 1. For the GPL license (GPL), you can redistribute and/or
18    * modify this file under the terms of the GNU General
19    * Public License, Version 3, as published by the Free Software
20    * Foundation. You should have received a copy of the GNU
21    * General Public License, Version 3 along with this program;
22    * if not, write to the Free Software Foundation, Inc., 51
23    * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24    *
25    * 2. For the Magnolia Network Agreement (MNA), this file
26    * and the accompanying materials are made available under the
27    * terms of the MNA which accompanies this distribution, and
28    * is available at http://www.magnolia-cms.com/mna.html
29    *
30    * Any modifications to this file must keep this entire header
31    * intact.
32    *
33    */
34    package info.magnolia.imaging;
35   
36    import static org.junit.Assert.assertEquals;
37    import info.magnolia.cms.beans.config.MIMEMapping;
38    import info.magnolia.context.MgnlContext;
39    import info.magnolia.context.SystemContext;
40    import info.magnolia.imaging.operations.load.ClasspathImageLoader;
41    import info.magnolia.imaging.operations.load.DefaultImageIOImageDecoder;
42    import info.magnolia.imaging.operations.load.ImageDecoder;
43    import info.magnolia.imaging.util.ImageUtil;
44    import info.magnolia.repository.RepositoryConstants;
45    import info.magnolia.test.ComponentsTestUtil;
46    import info.magnolia.test.mock.MockUtil;
47    import info.magnolia.test.mock.jcr.SessionTestUtil;
48   
49    import java.awt.BasicStroke;
50    import java.awt.Color;
51    import java.awt.Graphics2D;
52    import java.awt.Rectangle;
53    import java.awt.image.BufferedImage;
54    import java.io.File;
55    import java.io.FileOutputStream;
56    import java.io.IOException;
57    import java.io.OutputStream;
58    import java.nio.file.Files;
59    import java.util.HashSet;
60    import java.util.Set;
61   
62    import javax.imageio.ImageIO;
63    import javax.jcr.Session;
64   
65    import org.junit.After;
66    import org.junit.Before;
67    import org.junit.Rule;
68    import org.junit.rules.TestName;
69   
70    import com.jhlabs.image.FlipFilter;
71   
72    /**
73    * Provides utility/convenience methods to load and write images.
74    * Also provides well known source images for tests.
75    *
76    * Some of these methods are using the imaging framework itself,
77    * so they might not be appropriate for all testing situations !
78    *
79    * The write methods also keep track of generated images, so that one
80    * can open them easily after all tests have run, if human verification
81    * is necessary.
82    */
 
83    public abstract class AbstractImagingTest {
84    private static final boolean KEEP_GENERATED_FILES_FOR_INSPECTION = false;
85    private static final boolean OPEN_GENERATED_FILES_FOR_INSPECTION = false;
86   
87    protected static final OutputFormat BASIC_JPEG = new OutputFormat("jpeg", false, 80, null, false);
88    private static final Set<String> generatedFiles = new HashSet<String>();
89   
90    @Rule
91    public TestName name = new TestName();
92   
 
93  46 toggle @Before
94    public void setUp() throws Exception {
95    // this is set via the module descriptor (imaging.xml)
96  46 ComponentsTestUtil.setImplementation(ImageDecoder.class, DefaultImageIOImageDecoder.class);
97  46 MockUtil.initMockContext();
98  46 ComponentsTestUtil.setInstance(SystemContext.class, MockUtil.getMockContext());
99  46 Session session = SessionTestUtil.createSession(RepositoryConstants.CONFIG,
100    "/server/MIMEMapping/png.extension=png\n" +
101    "/server/MIMEMapping/png.mime-type=image/png\n" +
102    "/server/MIMEMapping/jpg.extension=jpg\n" +
103    "/server/MIMEMapping/jpg.mime-type=image/jpeg");
104  46 MockUtil.getMockContext().addSession(RepositoryConstants.CONFIG, session);
105  46 MIMEMapping.init();
106    }
107   
 
108  46 toggle @After
109    public void tearDown() throws Exception {
110  46 ComponentsTestUtil.clear();
111  46 MgnlContext.setInstance(null);
112    }
113   
 
114  6 toggle protected BufferedImage loadFromResource(String source) throws ImagingException {
115  6 final ClasspathImageLoader loader = new ClasspathImageLoader(source);
116  6 return loader.apply(null, null);
117    }
118   
 
119  11 toggle protected void write(BufferedImage res) throws Exception {
120  11 write(res, BASIC_JPEG);
121    }
122   
 
123  19 toggle protected void write(BufferedImage res, OutputFormat outputFormat) throws Exception {
124  19 write(null, res, outputFormat);
125    }
126   
 
127  34 toggle protected void write(String filenameSuffix, BufferedImage res, OutputFormat outputFormat) throws Exception {
128  34 final SampleImageStreamer streamer = new SampleImageStreamer();
129  34 final String extension = outputFormat.getFormatName();
130  34 final File f = newOutputFile(filenameSuffix, extension);
131  34 final FileOutputStream outputStream = new FileOutputStream(f);
132  34 streamer.write(res, outputStream, outputFormat);
133    }
134   
 
135  46 toggle protected File newOutputFile(String suffix, String extension) throws Exception {
136  46 return newOutputFile(getClass().getSimpleName() + "-" + name.getMethodName(), suffix, extension);
137    }
138   
 
139  58 toggle public static File newOutputFile(String prefix, String suffix, String extension) throws Exception {
140  58 final StringBuilder filename = new StringBuilder();
141  58 filename.append(prefix);
142  58 if (suffix != null) {
143  39 filename.append("-");
144  39 filename.append(suffix);
145    }
146  58 filename.append(".").append(extension);
147   
148  58 final File dir = getTestOutputDirectory();
149   
150  58 final File file = new File(dir, filename.toString());
151  58 if (file.exists()) {
152  0 throw new IllegalStateException(file + " already exists");
153    }
154  58 generatedFiles.add(file.getAbsolutePath());
155   
156  58 if (!KEEP_GENERATED_FILES_FOR_INSPECTION) {
157  58 file.deleteOnExit();
158    }
159  58 return file;
160    }
161   
 
162  58 toggle public static File getTestOutputDirectory() throws Exception {
163  58 String outputDir = System.getProperty("magnolia.test.output.folder");
164  58 if (outputDir == null) {
165  0 if (new File("target").exists()) {
166  0 outputDir = "target/test-output";
167    } else {
168  0 outputDir = "test-output";
169    }
170    }
171  58 final File dir = new File(outputDir);
172  58 Files.createDirectories(dir.toPath());
173  58 return dir;
174    }
175   
176    // having these images as static constants is a mediocre attempt at making the tests run faster (AutoCropAndResizeTest was using around 7 seconds...)
177    private static final BufferedImage horizontalImage;
178    private static final BufferedImage verticalImage;
179    private static final BufferedImage squareImage;
180    private static final BufferedImage smallImage;
181   
182    // preload images for this test
183   
 
184  1 toggle static {
185  1 try {
186  1 final FlipFilter f = new FlipFilter(FlipFilter.FLIP_90CW);
187  1 squareImage = ImageIO.read(AbstractImagingTest.class.getResource("/IMG_4995.JPG"));
188  1 horizontalImage = ImageIO.read(AbstractImagingTest.class.getResource("/IMG_2463.JPG"));
189  1 verticalImage = f.filter(horizontalImage, null);
190  1 smallImage = ImageIO.read(AbstractImagingTest.class.getResource("/magnolia-logo.png"));
191   
192    } catch (IOException e) {
193  0 throw new RuntimeException(e);
194    }
195    }
196   
197    /**
198    * Gets a well-known image, ensuring its dimensions haven't changed since the test was written and started.
199    */
 
200  16 toggle protected BufferedImage getHorizontalTestImage() throws Exception {
201  16 assertEquals(1600, horizontalImage.getWidth());
202  16 assertEquals(1200, horizontalImage.getHeight());
203  16 return horizontalImage;
204    }
205   
206    /**
207    * Gets a well-known image, ensuring its dimensions haven't changed since the test was written and started.
208    */
 
209  8 toggle protected BufferedImage getVerticalTestImage() throws Exception {
210  8 assertEquals(1200, verticalImage.getWidth());
211  8 assertEquals(1600, verticalImage.getHeight());
212  8 return verticalImage;
213    }
214   
215    /**
216    * Gets a well-known image, ensuring its dimensions haven't changed since the test was written and started.
217    */
 
218  2 toggle protected BufferedImage getSquareTestImage() throws Exception {
219  2 assertEquals(500, squareImage.getWidth());
220  2 assertEquals(500, squareImage.getHeight());
221  2 return squareImage;
222    }
223   
224    /**
225    * Gets a well-known image, ensuring its dimensions haven't changed since the test was written and started.
226    */
 
227  2 toggle protected BufferedImage getSmallTestImage() throws Exception {
228  2 assertEquals(202, smallImage.getWidth());
229  2 assertEquals(51, smallImage.getHeight());
230  2 return smallImage;
231    }
232   
233    /**
234    * Generates an image of arbitrary width and height. Re-generated for every call.
235    */
 
236  4 toggle protected BufferedImage generateArbitraryTestImage(final int width, final int height) {
237  4 final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
238  4 final Graphics2D g = img.createGraphics();
239    // background
240  4 g.setColor(Color.green);
241  4 g.fill(new Rectangle(0, 0, width, height));
242    // dashed diagonals
243  4 g.setColor(Color.darkGray);
244  4 g.setStroke(new BasicStroke(3, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 1f, new float[]{10, 10}, 0));
245  4 g.drawLine(0, 0, width, height);
246  4 g.drawLine(0, height, width, 0);
247    // small square in each corner
248  4 g.setColor(Color.red);
249  4 g.fill(new Rectangle(10, 10, 30, 30));
250  4 g.setColor(Color.blue);
251  4 g.fill(new Rectangle(width - 40, height - 40, 30, 30));
252  4 g.setColor(Color.yellow);
253  4 g.fill(new Rectangle(width - 40, 10, 30, 30));
254  4 g.setColor(Color.white);
255  4 g.fill(new Rectangle(10, height - 40, 30, 30));
256  4 return ImageUtil.flattenTransparentImageForOpaqueFormat(img, BASIC_JPEG);
257    }
258   
259    /**
260    * This inner class exists for the sole purpose of being able to call
261    * info.magnolia.imaging.DefaultImageStreamer#write
262    */
 
263    private static class SampleImageStreamer extends DefaultImageStreamer {
 
264  34 toggle @Override
265    protected void write(BufferedImage img, OutputStream out, OutputFormat outputFormat) throws IOException {
266  34 super.write(img, out, outputFormat);
267    }
268    }
269   
 
270  1 toggle static {
271  1 if (KEEP_GENERATED_FILES_FOR_INSPECTION && OPEN_GENERATED_FILES_FOR_INSPECTION) {
272  0 Runtime.getRuntime().addShutdownHook(new Thread() {
 
273  0 toggle @Override
274    public void run() {
275  0 final StringBuilder command = new StringBuilder("open");
276  0 for (String file : generatedFiles) {
277  0 command.append(" ").append(file);
278    }
279  0 try {
280  0 Runtime.getRuntime().exec(command.toString());
281    } catch (IOException e) {
282  0 throw new IllegalStateException("Could run open command with generated files... ", e);
283    }
284    }
285    });
286    }
287    }
288    }