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.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;
27 import junit.framework.TestCase;
29 import java.awt.geom.AffineTransform;
30 import java.awt.image.AffineTransformOp;
31 import java.awt.image.BufferedImage;
32 import java.awt.image.BufferedImageOp;
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;
43 import javax.imageio.ImageIO;
47 * @author dswitkin@google.com (Daniel Switkin)
49 public abstract class AbstractBlackBoxTestCase extends TestCase {
51 protected static final Hashtable<DecodeHintType, Object> TRY_HARDER_HINT;
53 TRY_HARDER_HINT = new Hashtable<DecodeHintType, Object>();
54 TRY_HARDER_HINT.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
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");
65 public static class SummaryResults {
66 private int totalFound;
67 private int totalMustPass;
68 private int totalTests;
70 public SummaryResults() {
76 public SummaryResults(int found, int mustPass, int total) {
78 totalMustPass = mustPass;
82 public void add(SummaryResults other) {
83 totalFound += other.totalFound;
84 totalMustPass += other.totalMustPass;
85 totalTests += other.totalTests;
88 public String toString() {
89 return "\nSUMMARY RESULTS:\n Decoded " + totalFound + " images out of " + totalTests +
90 " (" + (totalFound * 100 / totalTests) + "%, " + totalMustPass + " required)";
94 private static class TestResult {
95 private final int mustPassCount;
96 private final int tryHarderCount;
97 private final float rotation;
99 TestResult(int mustPassCount, int tryHarderCount, float rotation) {
100 this.mustPassCount = mustPassCount;
101 this.tryHarderCount = tryHarderCount;
102 this.rotation = rotation;
104 public int getMustPassCount() {
105 return mustPassCount;
107 public int getTryHarderCount() {
108 return tryHarderCount;
110 public float getRotation() {
115 private final File testBase;
116 private final Reader barcodeReader;
117 private final BarcodeFormat expectedFormat;
118 private final List<TestResult> testResults;
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);
129 this.testBase = testBase;
130 this.barcodeReader = barcodeReader;
131 this.expectedFormat = expectedFormat;
132 testResults = new ArrayList<TestResult>();
136 * Adds a new test for the current directory of images.
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.
142 protected void addTest(int mustPassCount, int tryHarderCount, float rotation) {
143 testResults.add(new TestResult(mustPassCount, tryHarderCount, rotation));
146 protected File[] getImageFiles() {
147 assertTrue("Please run from the 'core' directory", testBase.exists());
148 return testBase.listFiles(IMAGE_NAME_FILTER);
151 protected Reader getReader() {
152 return barcodeReader;
155 protected Hashtable<DecodeHintType, Object> getHints() {
159 // This workaround is used because AbstractNegativeBlackBoxTestCase overrides this method but does
160 // not return SummaryResults.
161 public void testBlackBox() throws IOException {
162 testBlackBoxCountingResults();
165 public SummaryResults testBlackBoxCountingResults() throws IOException {
166 assertFalse(testResults.isEmpty());
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());
175 BufferedImage image = ImageIO.read(testImage);
177 String testImageFileName = testImage.getName();
178 File expectedTextFile = new File(testBase,
179 testImageFileName.substring(0, testImageFileName.indexOf('.')) + ".txt");
180 String expectedText = readFileAsString(expectedTextFile);
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)) {
189 if (decode(source, 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) + "%)");
214 if (totalFound > totalMustPass) {
215 System.out.println(" *** Test too lax by " + (totalFound - totalMustPass) + " images");
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());
227 return new SummaryResults(totalFound, totalMustPass, totalTests);
230 private boolean decode(MonochromeBitmapSource source, float rotation, String expectedText,
233 String suffix = " (" + (tryHarder ? "try harder, " : "") + "rotation: " + rotation + ')';
236 Hashtable<DecodeHintType, Object> hints = getHints();
239 hints = TRY_HARDER_HINT;
241 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
244 result = barcodeReader.decode(source, hints);
245 } catch (ReaderException re) {
246 System.out.println(re + suffix);
250 if (!expectedFormat.equals(result.getBarcodeFormat())) {
251 System.out.println("Format mismatch: expected '" + expectedFormat + "' but got '" +
252 result.getBarcodeFormat() + '\'' + suffix);
256 String resultText = result.getText();
257 if (!expectedText.equals(resultText)) {
258 System.out.println("Mismatch: expected '" + expectedText + "' but got '" + resultText +
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"));
269 char[] buffer = new char[256];
271 while ((charsRead = reader.read(buffer)) > 0) {
272 result.append(buffer, 0, charsRead);
277 return result.toString();
280 protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
281 if (degrees == 0.0f) {
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);