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