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