View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.validator.routines.checkdigit;
19  
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertFalse;
22  import static org.junit.jupiter.api.Assertions.assertNotNull;
23  import static org.junit.jupiter.api.Assertions.assertThrows;
24  import static org.junit.jupiter.api.Assertions.assertTrue;
25  import static org.junit.jupiter.api.Assertions.fail;
26  import static org.junit.jupiter.api.Assumptions.assumeTrue;
27  
28  import java.io.ByteArrayInputStream;
29  import java.io.ByteArrayOutputStream;
30  import java.io.ObjectInputStream;
31  import java.io.ObjectOutputStream;
32  import java.io.Serializable;
33  import java.util.ArrayList;
34  import java.util.List;
35  
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  import org.junit.jupiter.api.AfterEach;
39  import org.junit.jupiter.api.Test;
40  
41  /**
42   * Check Digit Test.
43   */
44  public abstract class AbstractCheckDigitTest {
45  
46      private static final String POSSIBLE_CHECK_DIGITS = "0123456789 ABCDEFHIJKLMNOPQRSTUVWXYZ\tabcdefghijklmnopqrstuvwxyz!@£$%^&*()_+";
47  
48      /** Logging instance */
49      protected Log log = LogFactory.getLog(getClass());
50  
51      /** Check digit routine being tested */
52      protected int checkDigitLth = 1;
53  
54      /** Check digit routine being tested */
55      protected CheckDigit routine;
56  
57      /**
58       * Array of valid code values These must contain valid strings *including* the check digit.
59       *
60       * They are passed to: CheckDigit.isValid(expects string including checkdigit) which is expected to return true and
61       * AbstractCheckDigitTest.createInvalidCodes() which mangles the last character to check that the result is now invalid. and the truncated string is passed
62       * to CheckDigit.calculate(expects string without checkdigit) the result is compared with the last character
63       */
64      protected String[] valid;
65  
66      /**
67       * Array of invalid code values
68       *
69       * These are currently passed to both CheckDigit.calculate(expects a string without checkdigit) which is expected to throw an exception However that only
70       * applies if the string is syntactically incorrect; and CheckDigit.isValid(expects a string including checkdigit) which is expected to return false
71       *
72       * See https://issues.apache.org/jira/browse/VALIDATOR-344 for some discussion on this
73       */
74      protected String[] invalid = { "12345678A" };
75  
76      /** Code value which sums to zero */
77      protected String zeroSum = "0000000000";
78  
79      /** Prefix for error messages */
80      protected String missingMessage = "Code is missing";
81  
82      /**
83       * Returns the check digit (i.e. last character) for a code.
84       *
85       * @param code The code
86       * @return The check digit
87       */
88      protected String checkDigit(final String code) {
89          if (code == null || code.length() <= checkDigitLth) {
90              return "";
91          }
92          final int start = code.length() - checkDigitLth;
93          return code.substring(start);
94      }
95  
96      /**
97       * Returns an array of codes with invalid check digits.
98       *
99       * @param codes Codes with valid check digits
100      * @return Codes with invalid check digits
101      */
102     protected String[] createInvalidCodes(final String[] codes) {
103         final List<String> list = new ArrayList<>();
104         // create invalid check digit values
105         for (final String fullCode : codes) {
106             final String code = removeCheckDigit(fullCode);
107             final String check = checkDigit(fullCode);
108             for (int j = 0; j < POSSIBLE_CHECK_DIGITS.length(); j++) {
109                 final String curr = POSSIBLE_CHECK_DIGITS.substring(j, j + 1); // "" + Character.forDigit(j, 10);
110                 if (!curr.equals(check)) {
111                     list.add(code + curr);
112                 }
113             }
114         }
115         return list.toArray(new String[0]);
116     }
117 
118     /**
119      * Returns a code with the Check Digit (i.e. last character) removed.
120      *
121      * @param code The code
122      * @return The code without the check digit
123      */
124     protected String removeCheckDigit(final String code) {
125         if (code == null || code.length() <= checkDigitLth) {
126             return null;
127         }
128         return code.substring(0, code.length() - checkDigitLth);
129     }
130 
131     /**
132      * Tear down, clears routine and valid codes.
133      */
134     @AfterEach
135     protected void tearDown() {
136         valid = null;
137         routine = null;
138     }
139 
140     /**
141      * Test calculate() for invalid values.
142      */
143     @Test
144     void testCalculateInvalid() {
145         if (log.isDebugEnabled()) {
146             log.debug("testCalculateInvalid() for " + routine.getClass().getName());
147         }
148         // test invalid code values
149         for (int i = 0; i < invalid.length; i++) {
150             try {
151                 final String code = invalid[i];
152                 if (log.isDebugEnabled()) {
153                     log.debug("   " + i + " Testing Invalid Check Digit, Code=[" + code + "]");
154                 }
155                 final String expected = checkDigit(code);
156                 final String codeWithNoCheckDigit = removeCheckDigit(code);
157                 if (codeWithNoCheckDigit == null) {
158                     throw new CheckDigitException("Invalid Code=[" + code + "]");
159                 }
160                 final String actual = routine.calculate(codeWithNoCheckDigit);
161                 // If exception not thrown, check that the digit is incorrect instead
162                 if (expected.equals(actual)) {
163                     fail("Expected mismatch for " + code + " expected " + expected + " actual " + actual);
164                 }
165             } catch (final CheckDigitException e) {
166                 // possible failure messages:
167                 // Invalid ISBN Length ...
168                 // Invalid Character[ ...
169                 // Are there any others?
170                 assertTrue(e.getMessage().startsWith("Invalid "), "Invalid Character[" + i + "]=" + e.getMessage());
171             }
172         }
173     }
174 
175     /**
176      * Test calculate() for valid values.
177      */
178     @Test
179     void testCalculateValid() {
180         if (log.isDebugEnabled()) {
181             log.debug("testCalculateValid() for " + routine.getClass().getName());
182         }
183         // test valid values
184         for (int i = 0; i < valid.length; i++) {
185             final String code = removeCheckDigit(valid[i]);
186             final String expected = checkDigit(valid[i]);
187             try {
188                 if (log.isDebugEnabled()) {
189                     log.debug("   " + i + " Testing Valid Check Digit, Code=[" + code + "] expected=[" + expected + "]");
190                 }
191                 assertEquals(expected, routine.calculate(code), "valid[" + i + "]: " + valid[i]);
192             } catch (final Exception e) {
193                 fail("valid[" + i + "]=" + valid[i] + " threw " + e);
194             }
195         }
196     }
197 
198     /**
199      * Test isValid() for invalid values.
200      */
201     @Test
202     void testIsValidFalse() {
203         if (log.isDebugEnabled()) {
204             log.debug("testIsValidFalse() for " + routine.getClass().getName());
205         }
206         // test invalid code values
207         for (int i = 0; i < invalid.length; i++) {
208             if (log.isDebugEnabled()) {
209                 log.debug("   " + i + " Testing Invalid Code=[" + invalid[i] + "]");
210             }
211             assertFalse(routine.isValid(invalid[i]), "invalid[" + i + "]: " + invalid[i]);
212         }
213         // test invalid check digit values
214         final String[] invalidCheckDigits = createInvalidCodes(valid);
215         for (int i = 0; i < invalidCheckDigits.length; i++) {
216             if (log.isDebugEnabled()) {
217                 log.debug("   " + i + " Testing Invalid Check Digit, Code=[" + invalidCheckDigits[i] + "]");
218             }
219             assertFalse(routine.isValid(invalidCheckDigits[i]), "invalid check digit[" + i + "]: " + invalidCheckDigits[i]);
220         }
221     }
222 
223     /**
224      * Test isValid() for valid values.
225      */
226     @Test
227     void testIsValidTrue() {
228         if (log.isDebugEnabled()) {
229             log.debug("testIsValidTrue() for " + routine.getClass().getName());
230         }
231         // test valid values
232         for (int i = 0; i < valid.length; i++) {
233             if (log.isDebugEnabled()) {
234                 log.debug("   " + i + " Testing Valid Code=[" + valid[i] + "]");
235             }
236             assertTrue(routine.isValid(valid[i]), "valid[" + i + "]: " + valid[i]);
237         }
238     }
239 
240     /**
241      * Test missing code
242      */
243     @Test
244     void testMissingCode() {
245         // isValid() null
246         assertFalse(routine.isValid(null), "isValid() Null");
247         // isValid() zero length
248         assertFalse(routine.isValid(""), "isValid() Zero Length");
249         // isValid() length 1
250         // Don't use 0, because that passes for Verhoef (not sure why yet)
251         assertFalse(routine.isValid("9"), "isValid() Length 1");
252         // calculate() null
253         Exception e = assertThrows(Exception.class, () -> routine.calculate(null), "calculate() Null");
254         assertEquals(missingMessage, e.getMessage(), "calculate() Null");
255         // calculate() zero length
256         e = assertThrows(Exception.class, () -> routine.calculate(""), "calculate() Zero Length");
257         assertEquals(missingMessage, e.getMessage(), "calculate() Zero Length");
258     }
259 
260     /**
261      * Test check digit serialization.
262      */
263     @Test
264     void testSerialization() {
265         assumeTrue(routine instanceof Serializable);
266         // Serialize the check digit routine
267         final ByteArrayOutputStream baos = new ByteArrayOutputStream();
268         try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
269             oos.writeObject(routine);
270             oos.flush();
271         } catch (final Exception e) {
272             fail(routine.getClass().getName() + " error during serialization: " + e);
273         }
274         // Deserialize the test object
275         Object result = null;
276         try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
277             final ObjectInputStream ois = new ObjectInputStream(bais);
278             result = ois.readObject();
279         } catch (final Exception e) {
280             fail(routine.getClass().getName() + " error during deserialization: " + e);
281         }
282         assertNotNull(result);
283     }
284 
285     /**
286      * Test zero sum
287      */
288     @Test
289     void testZeroSum() {
290         assertFalse(routine.isValid(zeroSum), "isValid() Zero Sum");
291         final Exception e = assertThrows(Exception.class, () -> routine.calculate(zeroSum), "Zero Sum");
292         assertEquals("Invalid code, sum is zero", e.getMessage(), "isValid() Zero Sum");
293     }
294 }