826369d08e46df54d76fdc50a53ef543fdd5267f
[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 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.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.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   protected static final Hashtable<DecodeHintType, Object> TRY_HARDER_HINT;
48   static {
49     TRY_HARDER_HINT = new Hashtable<DecodeHintType, Object>();
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     }
59   };
60
61   private static class TestResult {
62     private final int mustPassCount;
63     private final int tryHarderCount;
64     private final float rotation;
65
66     TestResult(int mustPassCount, int tryHarderCount, float rotation) {
67       this.mustPassCount = mustPassCount;
68       this.tryHarderCount = tryHarderCount;
69       this.rotation = rotation;
70     }
71     public int getMustPassCount() {
72       return mustPassCount;
73     }
74     public int getTryHarderCount() {
75       return tryHarderCount;
76     }
77     public float getRotation() {
78       return rotation;
79     }
80   }
81
82   private final File testBase;
83   private final Reader barcodeReader;
84   private final BarcodeFormat expectedFormat;
85   private Vector<TestResult> testResults;
86
87   protected AbstractBlackBoxTestCase(File testBase,
88                                      Reader barcodeReader,
89                                      BarcodeFormat expectedFormat) {
90     this.testBase = testBase;
91     this.barcodeReader = barcodeReader;
92     this.expectedFormat = expectedFormat;
93     testResults = new Vector<TestResult>();
94   }
95
96   /**
97    * Adds a new test for the current directory of images.
98    *
99    * @param mustPassCount The number of images which must decode for the test to pass.
100    * @param tryHarderCount The number of images which must pass using the try harder flag.
101    * @param rotation The rotation in degrees clockwise to use for this test.
102    */
103   protected void addTest(int mustPassCount, int tryHarderCount, float rotation) {
104     testResults.add(new TestResult(mustPassCount, tryHarderCount, rotation));
105   }
106
107   protected File[] getImageFiles() {
108     assertTrue("Please run from the 'core' directory", testBase.exists());
109     return testBase.listFiles(IMAGE_NAME_FILTER);
110   }
111
112   protected Reader getReader() {
113     return barcodeReader;
114   }
115
116   public void testBlackBox() throws IOException {
117     assertFalse(testResults.isEmpty());
118
119     File[] imageFiles = getImageFiles();
120     int testCount = testResults.size();
121     int[] passedCounts = new int[testCount];
122     int[] tryHarderCounts = new int[testCount];
123     for (File testImage : imageFiles) {
124       System.out.println("Starting " + testImage.getAbsolutePath());
125
126       BufferedImage image = ImageIO.read(testImage);
127
128       String testImageFileName = testImage.getName();
129       File expectedTextFile = new File(testBase,
130           testImageFileName.substring(0, testImageFileName.indexOf('.')) + ".txt");
131       String expectedText = readFileAsString(expectedTextFile);
132
133       for (int x = 0; x < testCount; x++) {
134         float rotation = testResults.get(x).getRotation();
135         BufferedImage rotatedImage = rotateImage(image, rotation);
136         MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(rotatedImage);
137         if (decode(source, rotation, expectedText, false)) {
138           passedCounts[x]++;
139         }
140         if (decode(source, rotation, expectedText, true)) {
141           tryHarderCounts[x]++;
142         }
143       }
144     }
145
146     // Print the results of all tests first
147     for (int x = 0; x < testCount; x++) {
148       System.out.println("Rotation " + testResults.get(x).getRotation() + " degrees:");
149       System.out.println("  " + passedCounts[x] + " of " + imageFiles.length + " images passed ("
150           + testResults.get(x).getMustPassCount() + " required)");
151       System.out.println("  " + tryHarderCounts[x] + " of " + imageFiles.length +
152           " images passed with try harder (" + testResults.get(x).getTryHarderCount() +
153           " required)");
154     }
155
156     // Then run through again and assert if any failed
157     for (int x = 0; x < testCount; x++) {
158       assertTrue("Rotation " + testResults.get(x).getRotation() +
159           " degrees: Too many images failed",
160           passedCounts[x] >= testResults.get(x).getMustPassCount());
161       assertTrue("Try harder, Rotation " + testResults.get(x).getRotation() +
162           " degrees: Too many images failed",
163           tryHarderCounts[x] >= testResults.get(x).getTryHarderCount());
164     }
165   }
166
167   private boolean decode(MonochromeBitmapSource source, float rotation, String expectedText,
168                          boolean tryHarder) {
169     Result result;
170     String suffix = " (" + (tryHarder ? "try harder, " : "") + "rotation: " + rotation + ')';
171
172     try {
173       result = barcodeReader.decode(source, tryHarder ? TRY_HARDER_HINT : null);
174     } catch (ReaderException re) {
175       System.out.println(re + suffix);
176       return false;
177     }
178
179     if (!expectedFormat.equals(result.getBarcodeFormat())) {
180       System.out.println("Format mismatch: expected '" + expectedFormat + "' but got '" +
181           result.getBarcodeFormat() + "'" + suffix);
182       return false;
183     }
184
185     String resultText = result.getText();
186     if (!expectedText.equals(resultText)) {
187       System.out.println("Mismatch: expected '" + expectedText + "' but got '" + resultText +
188           "'" +  suffix);
189       return false;
190     }
191     return true;
192   }
193
194   private static String readFileAsString(File file) throws IOException {
195     StringBuilder result = new StringBuilder((int) file.length());
196     InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF8");
197     try {
198       char[] buffer = new char[256];
199       int charsRead;
200       while ((charsRead = reader.read(buffer)) > 0) {
201         result.append(buffer, 0, charsRead);
202       }
203     } finally {
204       reader.close();
205     }
206     return result.toString();
207   }
208
209   protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
210     if (degrees == 0.0f) {
211       return original;
212     } else {
213       AffineTransform at = new AffineTransform();
214       at.rotate(Math.toRadians(degrees), original.getWidth() / 2.0f, original.getHeight() / 2.0f);
215       BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
216       return op.filter(original, null);
217     }
218   }
219
220 }