2 * Copyright 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.common;
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 import junit.framework.TestCase;
29 import javax.imageio.ImageIO;
30 import java.awt.geom.AffineTransform;
31 import java.awt.image.AffineTransformOp;
32 import java.awt.image.BufferedImage;
33 import java.awt.image.BufferedImageOp;
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;
46 * @author dswitkin@google.com (Daniel Switkin)
48 public abstract class AbstractBlackBoxTestCase extends TestCase {
50 protected static final Hashtable<DecodeHintType, Object> TRY_HARDER_HINT;
52 TRY_HARDER_HINT = new Hashtable<DecodeHintType, Object>();
53 TRY_HARDER_HINT.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
56 private static final FilenameFilter IMAGE_NAME_FILTER = new FilenameFilter() {
57 public boolean accept(File dir, String name) {
58 String lowerCase = name.toLowerCase();
59 return lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") ||
60 lowerCase.endsWith(".gif") || lowerCase.endsWith(".png");
64 public static class SummaryResults {
65 private int totalFound;
66 private int totalMustPass;
67 private int totalTests;
69 public SummaryResults() {
75 public SummaryResults(int found, int mustPass, int total) {
77 totalMustPass = mustPass;
81 public void add(SummaryResults other) {
82 totalFound += other.totalFound;
83 totalMustPass += other.totalMustPass;
84 totalTests += other.totalTests;
87 public String toString() {
88 return "\nSUMMARY RESULTS:\n Decoded " + totalFound + " images out of " + totalTests +
89 " (" + (totalFound * 100 / totalTests) + "%, " + totalMustPass + " required)";
93 private static class TestResult {
94 private final int mustPassCount;
95 private final int tryHarderCount;
96 private final float rotation;
98 TestResult(int mustPassCount, int tryHarderCount, float rotation) {
99 this.mustPassCount = mustPassCount;
100 this.tryHarderCount = tryHarderCount;
101 this.rotation = rotation;
103 public int getMustPassCount() {
104 return mustPassCount;
106 public int getTryHarderCount() {
107 return tryHarderCount;
109 public float getRotation() {
114 private final File testBase;
115 private final Reader barcodeReader;
116 private final BarcodeFormat expectedFormat;
117 private final List<TestResult> testResults;
119 protected AbstractBlackBoxTestCase(String testBasePathSuffix,
120 Reader barcodeReader,
121 BarcodeFormat expectedFormat) {
122 // A little workaround to prevent aggravation in my IDE
123 File testBase = new File(testBasePathSuffix);
124 if (!testBase.exists()) {
125 // try starting with 'core' since the test base is often given as the project root
126 testBase = new File("core/" + testBasePathSuffix);
128 this.testBase = testBase;
129 this.barcodeReader = barcodeReader;
130 this.expectedFormat = expectedFormat;
131 testResults = new ArrayList<TestResult>();
135 * Adds a new test for the current directory of images.
137 * @param mustPassCount The number of images which must decode for the test to pass.
138 * @param tryHarderCount The number of images which must pass using the try harder flag.
139 * @param rotation The rotation in degrees clockwise to use for this test.
141 protected void addTest(int mustPassCount, int tryHarderCount, float rotation) {
142 testResults.add(new TestResult(mustPassCount, tryHarderCount, rotation));
145 protected File[] getImageFiles() {
146 assertTrue("Please run from the 'core' directory", testBase.exists());
147 return testBase.listFiles(IMAGE_NAME_FILTER);
150 protected Reader getReader() {
151 return barcodeReader;
154 protected Hashtable<DecodeHintType, Object> getHints() {
158 // This workaround is used because AbstractNegativeBlackBoxTestCase overrides this method but does
159 // not return SummaryResults.
160 public void testBlackBox() throws IOException {
161 testBlackBoxCountingResults(true);
164 public SummaryResults testBlackBoxCountingResults(boolean assertOnFailure) throws IOException {
165 assertFalse(testResults.isEmpty());
167 File[] imageFiles = getImageFiles();
168 int testCount = testResults.size();
169 int[] passedCounts = new int[testCount];
170 int[] tryHarderCounts = new int[testCount];
171 for (File testImage : imageFiles) {
172 System.out.println("Starting " + testImage.getAbsolutePath());
174 BufferedImage image = ImageIO.read(testImage);
176 String testImageFileName = testImage.getName();
177 File expectedTextFile = new File(testBase,
178 testImageFileName.substring(0, testImageFileName.indexOf('.')) + ".txt");
179 String expectedText = readFileAsString(expectedTextFile);
181 for (int x = 0; x < testCount; x++) {
182 float rotation = testResults.get(x).getRotation();
183 BufferedImage rotatedImage = rotateImage(image, rotation);
184 LuminanceSource source = new BufferedImageLuminanceSource(rotatedImage);
185 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
186 if (decode(bitmap, rotation, expectedText, false)) {
189 if (decode(bitmap, rotation, expectedText, true)) {
190 tryHarderCounts[x]++;
195 // Print the results of all tests first
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() +
205 totalFound += passedCounts[x];
206 totalFound += tryHarderCounts[x];
207 totalMustPass += testResults.get(x).getMustPassCount();
208 totalMustPass += testResults.get(x).getTryHarderCount();
211 int totalTests = imageFiles.length * testCount * 2;
212 System.out.println("TOTALS:\n Decoded " + totalFound + " images out of " + totalTests +
213 " (" + (totalFound * 100 / totalTests) + "%, " + totalMustPass + " required)");
214 if (totalFound > totalMustPass) {
215 System.out.println(" *** Test too lax by " + (totalFound - totalMustPass) + " images");
216 } else if (totalFound < totalMustPass) {
217 System.out.println(" *** Test failed by " + (totalMustPass - totalFound) + " images");
220 // Then run through again and assert if any failed
221 if (assertOnFailure) {
222 for (int x = 0; x < testCount; x++) {
223 assertTrue("Rotation " + testResults.get(x).getRotation() +
224 " degrees: Too many images failed",
225 passedCounts[x] >= testResults.get(x).getMustPassCount());
226 assertTrue("Try harder, Rotation " + testResults.get(x).getRotation() +
227 " degrees: Too many images failed",
228 tryHarderCounts[x] >= testResults.get(x).getTryHarderCount());
231 return new SummaryResults(totalFound, totalMustPass, totalTests);
234 private boolean decode(BinaryBitmap source, float rotation, String expectedText,
237 String suffix = " (" + (tryHarder ? "try harder, " : "") + "rotation: " + rotation + ')';
240 Hashtable<DecodeHintType, Object> hints = getHints();
243 hints = TRY_HARDER_HINT;
245 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
248 result = barcodeReader.decode(source, hints);
249 } catch (ReaderException re) {
250 System.out.println(re + suffix);
254 if (!expectedFormat.equals(result.getBarcodeFormat())) {
255 System.out.println("Format mismatch: expected '" + expectedFormat + "' but got '" +
256 result.getBarcodeFormat() + '\'' + suffix);
260 String resultText = result.getText();
261 if (!expectedText.equals(resultText)) {
262 System.out.println("Mismatch: expected '" + expectedText + "' but got '" + resultText +
269 private static String readFileAsString(File file) throws IOException {
270 StringBuilder result = new StringBuilder((int) file.length());
271 InputStreamReader reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF8"));
273 char[] buffer = new char[256];
275 while ((charsRead = reader.read(buffer)) > 0) {
276 result.append(buffer, 0, charsRead);
281 return result.toString();
284 protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
285 if (degrees == 0.0f) {
288 AffineTransform at = new AffineTransform();
289 at.rotate(Math.toRadians(degrees), original.getWidth() / 2.0, original.getHeight() / 2.0);
290 BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
291 return op.filter(original, null);