- Added support for rotation in our blackbox test framework, and refactored the ways...
[zxing.git] / core / test / src / com / google / zxing / common / AbstractBlackBoxTestCase.java
1 /*
2  * Copyright 2008 Google Inc.
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 import junit.framework.TestCase;
27
28 import javax.imageio.ImageIO;
29 import java.awt.geom.AffineTransform;
30 import java.awt.image.AffineTransformOp;
31 import java.awt.image.BufferedImage;
32 import java.io.File;
33 import java.io.FileInputStream;
34 import java.io.FilenameFilter;
35 import java.io.IOException;
36 import java.io.InputStreamReader;
37 import java.net.URL;
38 import java.util.Hashtable;
39 import java.util.Vector;
40
41 /**
42  * @author srowen@google.com (Sean Owen)
43  * @author dswitkin@google.com (Daniel Switkin)
44  */
45 public abstract class AbstractBlackBoxTestCase extends TestCase {
46
47   private static final Hashtable TRY_HARDER_HINT;
48   static {
49     TRY_HARDER_HINT = new Hashtable();
50     TRY_HARDER_HINT.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
51   }
52
53   private static final FilenameFilter IMAGE_NAME_FILTER = new FilenameFilter() {
54     public boolean accept(File dir, String name) {
55       String lowerCase = name.toLowerCase();
56       return lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") ||
57               lowerCase.endsWith(".gif") || lowerCase.endsWith(".png") ||
58               lowerCase.endsWith(".url");
59     }
60   };
61
62   private class TestResult {
63     public int mustPassCount;
64     public float rotation;
65
66     TestResult(int mustPassCount, float rotation) {
67       this.mustPassCount = mustPassCount;
68       this.rotation = rotation;
69     }
70   }
71
72   private final File testBase;
73   private final Reader barcodeReader;
74   private final BarcodeFormat expectedFormat;
75   private Vector<TestResult> testResults;
76
77   protected AbstractBlackBoxTestCase(File testBase,
78                                      Reader barcodeReader,
79                                      BarcodeFormat expectedFormat) {
80     this.testBase = testBase;
81     this.barcodeReader = barcodeReader;
82     this.expectedFormat = expectedFormat;
83     testResults = new Vector<TestResult>();
84   }
85
86   /**
87    * Adds a new test for the current directory of images.
88    *
89    * @param mustPassCount The number of images which must decode for the test to pass.
90    * @param rotation The rotation in degrees clockwise to use for this test.
91    */
92   protected void addTest(int mustPassCount, float rotation) {
93     testResults.add(new TestResult(mustPassCount, rotation));
94   }
95
96   public void testBlackBox() throws IOException {
97     assertTrue(testResults.size() > 0);
98     assertTrue("Please run from the 'core' directory", testBase.exists());
99
100     File[] imageFiles = testBase.listFiles(IMAGE_NAME_FILTER);
101     int[] passedCounts = new int[testResults.size()];
102     for (File testImage : imageFiles) {
103       System.out.println("Starting " + testImage.getAbsolutePath());
104
105       BufferedImage image;
106       if (testImage.getName().endsWith(".url")) {
107         String urlString = readFileAsString(testImage);
108         image = ImageIO.read(new URL(urlString));
109       } else {
110         image = ImageIO.read(testImage);
111       }
112
113       String testImageFileName = testImage.getName();
114       File expectedTextFile = new File(testBase,
115           testImageFileName.substring(0, testImageFileName.indexOf('.')) + ".txt");
116       String expectedText = readFileAsString(expectedTextFile);
117
118       for (int x = 0; x < testResults.size(); x++) {
119         if (testOneImage(image, testResults.get(x).rotation, expectedText)) {
120           passedCounts[x]++;
121         }
122       }
123     }
124
125     for (int x = 0; x < testResults.size(); x++) {
126       System.out.println("Rotation " + testResults.get(x).rotation + " degrees: " + passedCounts[x] +
127           " of " + imageFiles.length + " images passed (" + testResults.get(x).mustPassCount +
128           " required)");
129       assertTrue("Rotation " + testResults.get(x).rotation + " degrees: Too many images failed",
130           passedCounts[x] >= testResults.get(x).mustPassCount);
131     }
132   }
133
134   private boolean testOneImage(BufferedImage image, float rotationInDegrees, String expectedText) {
135     BufferedImage rotatedImage = rotateImage(image, rotationInDegrees);
136     MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(rotatedImage);
137     Result result;
138     try {
139       result = barcodeReader.decode(source);
140     } catch (ReaderException re) {
141       System.out.println(re);
142       return false;
143     }
144
145     if (expectedFormat != result.getBarcodeFormat()) {
146       System.out.println("Format mismatch: expected '" + expectedFormat + "' but got '" +
147           result.getBarcodeFormat() + "' (rotation: " + rotationInDegrees + ")");
148       return false;
149     }
150
151     String resultText = result.getText();
152     if (!expectedText.equals(resultText)) {
153       System.out.println("Mismatch: expected '" + expectedText + "' but got '" + resultText +
154           "' (rotation: " + rotationInDegrees + ")");
155       return false;
156     }
157
158     // Try "try harder" mode
159     try {
160       result = barcodeReader.decode(source, TRY_HARDER_HINT);
161     } catch (ReaderException re) {
162       fail("Normal mode succeeded but \"try harder\" failed");
163       return false;
164     }
165     if (expectedFormat != result.getBarcodeFormat()) {
166       System.out.println("Try Harder Format mismatch: expected '" + expectedFormat + "' but got '" +
167           result.getBarcodeFormat() + "' (rotation: " + rotationInDegrees + ")");
168     } else if (!expectedText.equals(resultText)) {
169       System.out.println("Try Harder Mismatch: expected '" + expectedText + "' but got '" +
170           resultText + "' (rotation: " + rotationInDegrees + ")");
171     }
172     return true;
173   }
174
175   private static String readFileAsString(File file) throws IOException {
176     StringBuilder result = new StringBuilder();
177     InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
178     try {
179       char[] buffer = new char[256];
180       int charsRead;
181       while ((charsRead = reader.read(buffer)) > 0) {
182         result.append(buffer, 0, charsRead);
183       }
184     } finally {
185       reader.close();
186     }
187     return result.toString();
188   }
189
190   private static BufferedImage rotateImage(BufferedImage original, float degrees) {
191     if (degrees != 0.0f) {
192       AffineTransform at = new AffineTransform();
193       at.rotate(Math.toRadians(degrees), original.getWidth() / 2, original.getHeight() / 2);
194       AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
195       return op.filter(original, null);
196     } else {
197       return original;
198     }
199   }
200
201 }