0b3ec6aee3f6fa07f82f5e9c7c11faafbba3b6f9
[zxing.git] / core / test / src / com / google / zxing / common / AbstractBlackBoxTestCase.java
1 /*
2  * Copyright 2008 ZXing 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 com.google.zxing.common;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.MonochromeBitmapSource;
22 import com.google.zxing.Reader;
23 import com.google.zxing.ReaderException;
24 import com.google.zxing.Result;
25 import com.google.zxing.client.j2se.BufferedImageMonochromeBitmapSource;
26
27 import junit.framework.TestCase;
28
29 import java.awt.geom.AffineTransform;
30 import java.awt.image.AffineTransformOp;
31 import java.awt.image.BufferedImage;
32 import java.awt.image.BufferedImageOp;
33 import java.io.File;
34 import java.io.FileInputStream;
35 import java.io.FilenameFilter;
36 import java.io.IOException;
37 import java.io.InputStreamReader;
38 import java.nio.charset.Charset;
39 import java.util.ArrayList;
40 import java.util.Hashtable;
41 import java.util.List;
42
43 import javax.imageio.ImageIO;
44
45 /**
46  * @author Sean Owen
47  * @author dswitkin@google.com (Daniel Switkin)
48  */
49 public abstract class AbstractBlackBoxTestCase extends TestCase {
50
51   protected static final Hashtable<DecodeHintType, Object> TRY_HARDER_HINT;
52   static {
53     TRY_HARDER_HINT = new Hashtable<DecodeHintType, Object>();
54     TRY_HARDER_HINT.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
55   }
56
57   private static final FilenameFilter IMAGE_NAME_FILTER = new FilenameFilter() {
58     public boolean accept(File dir, String name) {
59       String lowerCase = name.toLowerCase();
60       return lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") ||
61              lowerCase.endsWith(".gif") || lowerCase.endsWith(".png");
62     }
63   };
64
65   public static class SummaryResults {
66     private int totalFound;
67     private int totalMustPass;
68     private int totalTests;
69
70     public SummaryResults() {
71       totalFound = 0;
72       totalMustPass = 0;
73       totalTests = 0;
74     }
75
76     public SummaryResults(int found, int mustPass, int total) {
77       totalFound = found;
78       totalMustPass = mustPass;
79       totalTests = total;
80     }
81
82     public void add(SummaryResults other) {
83       totalFound += other.totalFound;
84       totalMustPass += other.totalMustPass;
85       totalTests += other.totalTests;
86     }
87
88     public String toString() {
89       return "\nSUMMARY RESULTS:\n  Decoded " + totalFound + " images out of " + totalTests +
90         " (" + (totalFound * 100 / totalTests) + "%, " + totalMustPass + " required)";
91     }
92   }
93
94   private static class TestResult {
95     private final int mustPassCount;
96     private final int tryHarderCount;
97     private final float rotation;
98
99     TestResult(int mustPassCount, int tryHarderCount, float rotation) {
100       this.mustPassCount = mustPassCount;
101       this.tryHarderCount = tryHarderCount;
102       this.rotation = rotation;
103     }
104     public int getMustPassCount() {
105       return mustPassCount;
106     }
107     public int getTryHarderCount() {
108       return tryHarderCount;
109     }
110     public float getRotation() {
111       return rotation;
112     }
113   }
114
115   private final File testBase;
116   private final Reader barcodeReader;
117   private final BarcodeFormat expectedFormat;
118   private final List<TestResult> testResults;
119
120   protected AbstractBlackBoxTestCase(String testBasePathSuffix,
121                                      Reader barcodeReader,
122                                      BarcodeFormat expectedFormat) {
123     // A little workaround to prevent aggravation in my IDE
124     File testBase = new File(testBasePathSuffix);
125     if (!testBase.exists()) {
126       // try starting with 'core' since the test base is often given as the project root
127       testBase = new File("core/" + testBasePathSuffix);
128     }
129     this.testBase = testBase;
130     this.barcodeReader = barcodeReader;
131     this.expectedFormat = expectedFormat;
132     testResults = new ArrayList<TestResult>();
133   }
134
135   /**
136    * Adds a new test for the current directory of images.
137    *
138    * @param mustPassCount The number of images which must decode for the test to pass.
139    * @param tryHarderCount The number of images which must pass using the try harder flag.
140    * @param rotation The rotation in degrees clockwise to use for this test.
141    */
142   protected void addTest(int mustPassCount, int tryHarderCount, float rotation) {
143     testResults.add(new TestResult(mustPassCount, tryHarderCount, rotation));
144   }
145
146   protected File[] getImageFiles() {
147     assertTrue("Please run from the 'core' directory", testBase.exists());
148     return testBase.listFiles(IMAGE_NAME_FILTER);
149   }
150
151   protected Reader getReader() {
152     return barcodeReader;
153   }
154
155   protected Hashtable<DecodeHintType, Object> getHints() {
156     return null;
157   }
158
159   // This workaround is used because AbstractNegativeBlackBoxTestCase overrides this method but does
160   // not return SummaryResults.
161   public void testBlackBox() throws IOException {
162     testBlackBoxCountingResults();
163   }
164
165   public SummaryResults testBlackBoxCountingResults() throws IOException {
166     assertFalse(testResults.isEmpty());
167
168     File[] imageFiles = getImageFiles();
169     int testCount = testResults.size();
170     int[] passedCounts = new int[testCount];
171     int[] tryHarderCounts = new int[testCount];
172     for (File testImage : imageFiles) {
173       System.out.println("Starting " + testImage.getAbsolutePath());
174
175       BufferedImage image = ImageIO.read(testImage);
176
177       String testImageFileName = testImage.getName();
178       File expectedTextFile = new File(testBase,
179           testImageFileName.substring(0, testImageFileName.indexOf('.')) + ".txt");
180       String expectedText = readFileAsString(expectedTextFile);
181
182       for (int x = 0; x < testCount; x++) {
183         float rotation = testResults.get(x).getRotation();
184         BufferedImage rotatedImage = rotateImage(image, rotation);
185         MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(rotatedImage);
186         if (decode(source, rotation, expectedText, false)) {
187           passedCounts[x]++;
188         }
189         if (decode(source, rotation, expectedText, true)) {
190           tryHarderCounts[x]++;
191         }
192       }
193     }
194
195     // Print the results of all tests first
196     int totalFound = 0;
197     int totalMustPass = 0;
198     for (int x = 0; x < testCount; x++) {
199       System.out.println("Rotation " + testResults.get(x).getRotation() + " degrees:");
200       System.out.println("  " + passedCounts[x] + " of " + imageFiles.length + " images passed ("
201           + testResults.get(x).getMustPassCount() + " required)");
202       System.out.println("  " + tryHarderCounts[x] + " of " + imageFiles.length +
203           " images passed with try harder (" + testResults.get(x).getTryHarderCount() +
204           " required)");
205       totalFound += passedCounts[x];
206       totalFound += tryHarderCounts[x];
207       totalMustPass += testResults.get(x).getMustPassCount();
208       totalMustPass += testResults.get(x).getTryHarderCount();
209     }
210
211     int totalTests = imageFiles.length * testCount * 2;
212     System.out.println("TOTALS:\n  Decoded " + totalFound + " images out of " + totalTests +
213       " (" + (totalFound * 100 / totalTests) + "%)");
214     if (totalFound > totalMustPass) {
215       System.out.println("  *** Test too lax by " + (totalFound - totalMustPass) + " images");
216     }
217
218     // Then run through again and assert if any failed
219     for (int x = 0; x < testCount; x++) {
220       assertTrue("Rotation " + testResults.get(x).getRotation() +
221           " degrees: Too many images failed",
222           passedCounts[x] >= testResults.get(x).getMustPassCount());
223       assertTrue("Try harder, Rotation " + testResults.get(x).getRotation() +
224           " degrees: Too many images failed",
225           tryHarderCounts[x] >= testResults.get(x).getTryHarderCount());
226     }
227     return new SummaryResults(totalFound, totalMustPass, totalTests);
228   }
229
230   private boolean decode(MonochromeBitmapSource source, float rotation, String expectedText,
231                          boolean tryHarder) {
232     Result result;
233     String suffix = " (" + (tryHarder ? "try harder, " : "") + "rotation: " + rotation + ')';
234
235     try {
236       Hashtable<DecodeHintType, Object> hints = getHints();
237       if (tryHarder) {
238         if (hints == null) {
239           hints = TRY_HARDER_HINT;
240         } else {
241           hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
242         }
243       }
244       result = barcodeReader.decode(source, hints);
245     } catch (ReaderException re) {
246       System.out.println(re + suffix);
247       return false;
248     }
249
250     if (!expectedFormat.equals(result.getBarcodeFormat())) {
251       System.out.println("Format mismatch: expected '" + expectedFormat + "' but got '" +
252           result.getBarcodeFormat() + '\'' + suffix);
253       return false;
254     }
255
256     String resultText = result.getText();
257     if (!expectedText.equals(resultText)) {
258       System.out.println("Mismatch: expected '" + expectedText + "' but got '" + resultText +
259           '\'' +  suffix);
260       return false;
261     }
262     return true;
263   }
264
265   private static String readFileAsString(File file) throws IOException {
266     StringBuilder result = new StringBuilder((int) file.length());
267     InputStreamReader reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF8"));
268     try {
269       char[] buffer = new char[256];
270       int charsRead;
271       while ((charsRead = reader.read(buffer)) > 0) {
272         result.append(buffer, 0, charsRead);
273       }
274     } finally {
275       reader.close();
276     }
277     return result.toString();
278   }
279
280   protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
281     if (degrees == 0.0f) {
282       return original;
283     } else {
284       AffineTransform at = new AffineTransform();
285       at.rotate(Math.toRadians(degrees), original.getWidth() / 2.0, original.getHeight() / 2.0);
286       BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
287       return op.filter(original, null);
288     }
289   }
290
291 }