Improve test coverage

This commit is contained in:
Sean Owen 2020-12-09 11:29:07 -06:00
parent e7ed6aee2f
commit fd364d9338
14 changed files with 292 additions and 21 deletions

View file

@ -0,0 +1,39 @@
/*
* Copyright 2020 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing;
import org.junit.Assert;
import org.junit.Test;
import java.awt.image.BufferedImage;
/**
* Tests {@link InvertedLuminanceSource}.
*/
public final class InvertedLuminanceSourceTestCase extends Assert {
@Test
public void testInverted() {
BufferedImage image = new BufferedImage(2, 1, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, 0xFFFFFF);
LuminanceSource source = new BufferedImageLuminanceSource(image);
assertArrayEquals(new byte[] { (byte) 0xFF, 0 }, source.getRow(0, null));
LuminanceSource inverted = new InvertedLuminanceSource(source);
assertArrayEquals(new byte[] { 0, (byte) 0xFF }, inverted.getRow(0, null));
}
}

View file

@ -19,6 +19,8 @@ package com.google.zxing.common;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
/**
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
@ -226,6 +228,25 @@ public final class BitMatrixTestCase extends Assert {
assertEquals(centerMatrix, BitMatrix.parse(centerMatrix.toString("x", "."), "x", "."));
}
@Test
public void testParseBoolean() {
BitMatrix emptyMatrix = new BitMatrix(3, 3);
BitMatrix fullMatrix = new BitMatrix(3, 3);
fullMatrix.setRegion(0, 0, 3, 3);
BitMatrix centerMatrix = new BitMatrix(3, 3);
centerMatrix.setRegion(1, 1, 1, 1);
BitMatrix emptyMatrix24 = new BitMatrix(2, 4);
boolean[][] matrix = new boolean[3][3];
assertEquals(emptyMatrix, BitMatrix.parse(matrix));
matrix[1][1] = true;
assertEquals(centerMatrix, BitMatrix.parse(matrix));
for (boolean[] arr : matrix) {
Arrays.fill(arr, true);
}
assertEquals(fullMatrix, BitMatrix.parse(matrix));
}
@Test
public void testUnset() {
BitMatrix emptyMatrix = new BitMatrix(3, 3);

View file

@ -19,14 +19,23 @@ package com.google.zxing.common;
import org.junit.Assert;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Random;
/**
* Tests {@link StringUtils}.
*/
public final class StringUtilsTestCase extends Assert {
@Test
public void testRandom() {
Random r = new Random(1234L);
byte[] bytes = new byte[1000];
r.nextBytes(bytes);
assertEquals(Charset.defaultCharset(), StringUtils.guessCharset(bytes, null));
}
@Test
public void testShortShiftJIS1() {
// 金魚

View file

@ -52,16 +52,18 @@ import java.util.regex.Pattern;
* as a comma-separated list. Specify "all" for language to try to translate for all existing translations.
* Each argument after this is the name of a file to translate; if the first one is "all", all files will
* be translated.</p>
*
*
* <p>Usage: {@code HtmlAssetTranslator android/assets/ (all|lang1[,lang2 ...]) (all|file1.html[ file2.html ...])}</p>
*
* <p>{@code android/assets/ es all} will translate .html files in subdirectory html-en to
* directory html-es, for example. Note that only text nodes in the HTML document are translated.
* Any text that is a child of a node with {@code class="notranslate"} will not be translated. It will
* <p>{@code android/assets/ es all} will translate .html files in subdirectory html-en to
* directory html-es, for example. Note that only text nodes in the HTML document are translated.
* Any text that is a child of a node with {@code class="notranslate"} will not be translated. It will
* also add a note at the end of the translated page that indicates it was automatically translated.</p>
*
* @author Sean Owen
* @deprecated without replacement since 3.4.2
*/
@Deprecated
public final class HtmlAssetTranslator {
private static final Pattern COMMA = Pattern.compile(",");

View file

@ -49,7 +49,9 @@ import java.util.regex.Pattern;
* <p>You must set your Google Translate API key into the environment with -DtranslateAPI.key=...</p>
*
* @author Sean Owen
* @deprecated without replacement since 3.4.2
*/
@Deprecated
public final class StringsResourceTranslator {
private static final String API_KEY = System.getProperty("translateAPI.key");
@ -58,7 +60,7 @@ public final class StringsResourceTranslator {
throw new IllegalArgumentException("translateAPI.key is not specified");
}
}
private static final Pattern ENTRY_PATTERN = Pattern.compile("<string name=\"([^\"]+)\".*>([^<]+)</string>");
private static final Pattern STRINGS_FILE_NAME_PATTERN = Pattern.compile("values-(.+)");
private static final Pattern TRANSLATE_RESPONSE_PATTERN = Pattern.compile("translatedText\":\\s*\"([^\"]+)\"");

View file

@ -26,7 +26,8 @@ public final class CommandLineRunnerTestCase extends Assert {
@Test
public void testCommandLineRunner() throws Exception {
String[] args = { "--pure_barcode", DecodeWorkerTestCase.IMAGE_DATA_URI };
String[] args = { "--pure_barcode", "--try_harder",
DecodeWorkerTestCase.IMAGE_DATA_URI, DecodeWorkerTestCase.IMAGE_NOBARCODE_DATA_URI };
// Not a lot to do here but make sure it runs
CommandLineRunner.main(args);
}

View file

@ -36,6 +36,25 @@ public final class DecodeWorkerTestCase extends Assert {
"988HQPUfPVaqA0XKz%2BgD9bIk1AP1fgwvB7KlS9VBdqXbA82PT9AH2fiaH2SXGdDM71fDgeIfhIvKsbkTTAIAKYVr0N" +
"z5IloAAAAASUVORK5CYII=";
static final String IMAGE_NOBARCODE_DATA_URI =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAACE1BMVEUAAAAYsPIXsPL//+" +
"2J6/CI6vB74/Alt/IXr/LL/++M7PD//+UZsPIXr/ISrfIRrPIXsPIYsPIYsPIKqfIQrPITrvIZsfImt/IouPImt/IZsf" +
"IXr/IXsPIbsfIWr/IcsvInuPImuPIvvPJt3PB54vBt3PAasfIXsPIXr/IUrvIYsPIwvfJx3vB54vCE6PCS7/B64/Bt3P" +
"AktvIXr/IYsPIYsPIasfIlt/IwvPKJ6/CM7PCW8fCQ7vCB5vAmt/IXr/IYsPIYsPIXsPKI6vCI6vCI6vAYsfMYsPIYsP" +
"KI6vCI6vCI6vAYrO0YsPGI6vCI6v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jiuWUT2yhXBW5DlwWA3PktPNo8RN8sZN3MT1RwFtrMO0FNaCoXzVDyTper8WVF17IO" +
"OWaUsLTDWsTfIyc+eXr6EuWS+oM/shX9CWhKmGeVPRtHxcMtqIbIqpOmNKAxnaS1/E+migDR3nJGnR0GDR+A23fMFDA8" +
"6WRQAAAABJRU5ErkJggg==";
@Test
public void testWorker() throws Exception {
@ -46,5 +65,5 @@ public final class DecodeWorkerTestCase extends Assert {
DecodeWorker worker = new DecodeWorker(config, inputs);
assertEquals(1, worker.call().intValue());
}
}

View file

@ -467,6 +467,7 @@
<exclude>**/*.properties</exclude>
<exclude>**/*.cfg</exclude>
<exclude>**/*.config</exclude>
<exclude>**/*.yml</exclude>
<exclude>**/*.yaml</exclude>
<exclude>**/gen/**</exclude>
<exclude>**/resources/**</exclude>

View file

@ -49,7 +49,13 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.1</version>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -66,6 +72,10 @@
<version>3.4.2-SNAPSHOT</version>
</parent>
<properties>
<spring.version>5.3.1</spring.version>
</properties>
<build>
<plugins>
<plugin>

View file

@ -114,7 +114,7 @@ public final class ChartServlet extends HttpServlet {
} else {
imageFormat = "PNG";
}
String contentType;
switch (imageFormat) {
case "PNG":
@ -129,7 +129,7 @@ public final class ChartServlet extends HttpServlet {
default:
throw new IllegalArgumentException("Unknown format " + imageFormat);
}
ByteArrayOutputStream imageOut = new ByteArrayOutputStream(1024);
MatrixToImageWriter.writeToStream(matrix, imageFormat, imageOut);
byte[] imageData = imageOut.toByteArray();
@ -143,7 +143,8 @@ public final class ChartServlet extends HttpServlet {
private static ChartServletRequestParameters doParseParameters(ServletRequest request, boolean readBody)
throws IOException {
Preconditions.checkArgument("qr".equals(request.getParameter("cht")), "Bad type");
String chartType = request.getParameter("cht");
Preconditions.checkArgument(chartType == null || "qr".equals(chartType), "Bad type");
String widthXHeight = request.getParameter("chs");
Preconditions.checkNotNull(widthXHeight, "No size");
@ -156,8 +157,10 @@ public final class ChartServlet extends HttpServlet {
Preconditions.checkArgument(width <= MAX_DIMENSION && height <= MAX_DIMENSION, "Bad size");
String outputEncodingName = request.getParameter("choe");
Charset outputEncoding = StandardCharsets.UTF_8;
if (outputEncodingName != null) {
Charset outputEncoding;
if (outputEncodingName == null) {
outputEncoding = StandardCharsets.UTF_8;
} else {
outputEncoding = Charset.forName(outputEncodingName);
Preconditions.checkArgument(SUPPORTED_OUTPUT_ENCODINGS.contains(outputEncoding), "Bad output encoding");
}

View file

@ -18,7 +18,7 @@ package com.google.zxing.web;
/**
* Utility functions for {@code decoderesult.jspx}.
*
*
* @author Sean Owen
*/
public final class OutputUtils {
@ -42,17 +42,14 @@ public final class OutputUtils {
} else if (i % HALF_BYTES_PER_LINE == 0) {
result.append(" ");
} else {
result.append(' ');
result.append(' ');
}
}
return result.toString();
}
private static char hexChar(int value) {
if (value < 0 || value > 15) {
throw new IllegalArgumentException("Bad hex digit value " + value);
}
return (char) (value < 10 ? ('0' + value) : ('a' + (value - 10)));
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright 2020 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.web;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
/**
* Tests {@link ChartServlet}.
*/
public final class ChartServletTestCase extends Assert {
@Test
public void testChart() throws Exception {
ChartServlet servlet = new ChartServlet();
for (String contentType : new String[] { "png", "jpeg", "gif"}) {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("image." + contentType);
Map<String, String> params = new HashMap<>();
params.put("chl", "foo");
params.put("chs", "100x100");
params.put("chld", "M");
request.setParameters(params);
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.doGet(request, response);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
assertEquals("image/" + contentType, response.getContentType());
assertTrue(response.getContentAsByteArray().length > 0);
}
servlet.destroy();
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright 2020 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.web;
import com.google.common.net.MediaType;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
/**
* Tests {@link DecodeServlet}.
*/
public final class DecodeServletTestCase extends Assert {
private static final String IMAGE_DATA_URI =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAhAQAAAAB/n//CAAAAkklEQVR42mP4DwQNDJjkB4" +
"E77A0M369N/d7A8CV6rjiQjPMFkWG1QPL7RVGg%2BAfREKCa/5/vA9V/nFSQ3sDwb7/KdiDJqX4dSH4pXN/A8DfyDVD2" +
"988HQPUfPVaqA0XKz%2BgD9bIk1AP1fgwvB7KlS9VBdqXbA82PT9AH2fiaH2SXGdDM71fDgeIfhIvKsbkTTAIAKYVr0N" +
"z5IloAAAAASUVORK5CYII=";
@Test
public void testDataURI() throws Exception {
MockServletConfig config = new MockServletConfig();
config.addInitParameter("maxAccessPerTime", "100");
config.addInitParameter("accessTimeSec", "100");
config.addInitParameter("maxEntries", "100");
DecodeServlet servlet = new DecodeServlet();
servlet.init(config);
MockHttpServletRequest request = new MockHttpServletRequest();
Map<String, String> params = new HashMap<>();
params.put("u", IMAGE_DATA_URI);
params.put("full", "false");
request.setParameters(params);
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.doGet(request, response);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
assertEquals(MediaType.PLAIN_TEXT_UTF_8.toString(), response.getContentType());
assertEquals("--error-correction_level\n", response.getContentAsString());
servlet.destroy();
}
}

View file

@ -0,0 +1,41 @@
/*
* Copyright 2020 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.web;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockServletContext;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* Tests {@link ServletContextLogHandler}.
*/
public final class ServletContextLogHandlerTestCase extends Assert {
@Test
public void testLogHandler() {
// Can't test much here
MockServletContext context = new MockServletContext();
ServletContextLogHandler handler = new ServletContextLogHandler(context);
handler.publish(new LogRecord(Level.INFO, "test log message"));
handler.flush();
handler.close();
}
}