diff --git a/.gitignore b/.gitignore index 9a4fa47..f96b8ee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.idea .gradle .settings .project diff --git a/CHANGELOG.md b/CHANGELOG.md index d8fa2cd..292045f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ +# 2.0.0 (April 10, 2024) + +* Retargeted at Java 17 + Gradle 8 +* No more reliance on the external BuildScripts repository to build this project +* Migrated to JUnit 5 +* Added Spotbugs code coverage to the build +* Uses of `java.util.Random` have been replaced by `ThreadLocalRandom` + +BREAKING CHANGES: + +```java +PaymentCardGenerator.generateByPrefix(int howManyOfEachPrefix, List lengths, Set prefixes) +``` +now uses a `Set` for `lengths` rather than `List` + + # 1.0.1 (May 8, 2021) There are no code changes in this release. The project has been updated to be compatible with the latest [BuildScripts](https://github.com/kloverde/BuildScripts) and Gradle 7.0. diff --git a/README.md b/README.md index 5a44033..86365dd 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ It generates random payment card numbers so that you don't have to use an actual Card numbers are generated based on the criteria defined here: * https://en.wikipedia.org/wiki/Luhn_algorithm -* https://en.wikipedia.org/wiki/Payment_card_number (as of December, 2016) +* https://en.wikipedia.org/wiki/Payment_card_number (as of April 2024) ## Features @@ -20,11 +20,21 @@ Card numbers are generated based on the criteria defined here: * Future-proof: generate numbers based on your own criteria, even if the library doesn't have knowledge of the latest card number formats -## Building +## Build Tasks -This project is known to build on Gradle 7.0. +This project is known to build on Gradle 8.4. -1. Get [BuildScripts](https://github.com/kloverde/BuildScripts) -2. Provide a value for `builtBy` in gradle.properties -3. Run `gradle build` -4. Optionally, you can publish locally using `gradle publishtomavenlocal` +| task | purpose | +|---------------------|----------------------------------------------| +| build | Builds the project | +| check | Runs the tests and code quality checks | +| clean | Removes the `build` directory | +| jars | Builds the source, javadoc and binary jars | +| publishToMavenLocal | Published the jars to your local Maven cache | + + +## Donations + +https://paypal.me/KurtisLoVerde/5 + +Thank you for your support! diff --git a/build.gradle b/build.gradle index c70dcfb..f2c5c80 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,84 @@ -apply from: buildScriptsDir + "/build_java_lib.gradle" +buildscript { + repositories { + mavenCentral() + } +} + +plugins { + id("java") + id("com.github.spotbugs") version "6.0.10" + id("maven-publish") +} +sourceCompatibility = javaSourceCompatibility +targetCompatibility = javaTargetCompatibility + +repositories { + mavenCentral() +} dependencies { - testImplementation "junit:junit:4.12" + implementation "com.github.spotbugs:spotbugs-annotations:4.8.4" + + testImplementation platform("org.junit:junit-bom:5.10.2") + testImplementation "org.junit.jupiter:junit-jupiter" + testImplementation "org.mockito:mockito-junit-jupiter:5.11.0" + testRuntimeOnly "org.junit.platform:junit-platform-launcher" +} + +def includeManifest = { + manifest { + attributes "Specification-Title": rootProject.name, + "Implementation-Version": version, + "Built-Date": new Date(), + "Built-JDK": System.getProperty("java.version"), + "Target-JDK": targetCompatibility, + "Built-Gradle": gradle.gradleVersion + } +} + +java { + withSourcesJar() + withJavadocJar() +} + +tasks.spotbugsMain { + reports.create("html") { + required = true + outputLocation = file("${project.layout.buildDirectory.get()}/reports/spotbugs.html") + setStylesheet("fancy-hist.xsl") + } } + +jar { + configure includeManifest +} + +sourcesJar { + configure includeManifest +} + +javadocJar { + configure includeManifest +} + +tasks.register("jars") { + dependsOn( + tasks.jar, + tasks.sourcesJar, + tasks.javadocJar + ) +} + +javadoc.options.addStringOption("Xdoclint:none", "-quiet") + +publishing { + publications { + mavenJava(MavenPublication) { + from project.components.java + artifacts = [ jar, javadocJar, sourcesJar ] + } + } +} + +compileJava.dependsOn clean diff --git a/gradle.properties b/gradle.properties index ecfe272..0c1ac2a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,8 +1,5 @@ -buildScriptsDir=../BuildScripts - -javaSourceCompatibility=1.8 -javaTargetCompatibility=1.8 +javaSourceCompatibility=1.17 +javaTargetCompatibility=1.17 group=org.loverde -version=1.0.1 -builtBy= +version=2.0.0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3fa8f86 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/org/loverde/paymentcard/CardType.java b/src/main/java/org/loverde/paymentcard/CardType.java index de02b05..1edc075 100644 --- a/src/main/java/org/loverde/paymentcard/CardType.java +++ b/src/main/java/org/loverde/paymentcard/CardType.java @@ -33,79 +33,90 @@ package org.loverde.paymentcard; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import static org.loverde.paymentcard.internal.Objects.failIf; + /** * Defines various payment card types, along with a known list of valid lengths and prefixes, according to * https://en.wikipedia.org/wiki/Payment_card_number - * as of December, 2016. + * as of April 2024. */ public enum CardType { - AMERICAN_EXPRESS( prefixesFromRange(new Range(34, 34), new Range(37, 37)), - list(15) ), - - VISA( prefixesFromRange(new Range(4, 4)), - list(13, 16, 19) ), + AMERICAN_EXPRESS( + prefixesFromRange( + new Range(34, 34), + new Range(37, 37)), - MASTERCARD( prefixesFromRange(new Range(51, 55), new Range(2221, 2720)), - list(16) ), + Set.of(15) + ), - DISCOVER( prefixesFromRange(new Range(65, 65), new Range(644, 649), new Range(6011, 6011), new Range(622126, 622925) ), - list(16, 19) ); + VISA( + prefixesFromRange(new Range(4, 4)), + Set.of(13, 16, 19) + ), + MASTERCARD( + prefixesFromRange( + new Range(51, 55), + new Range(2221, 2720)), - private Set prefixes; - private List lengths; + Set.of(16) + ), + DISCOVER( + prefixesFromRange( + new Range(65, 65), + new Range(644, 649), + new Range(6011, 6011), + new Range(622126, 622925)), - private CardType( final Set prefixes, final List lengths ) { - this.prefixes = prefixes; - this.lengths = lengths; - } + Set.of(16, 19) + ); - public Set getPrefixes() { - return prefixes; - } + private final Set prefixes; + private final Set lengths; - public List getLengths() { - return lengths; - } - private static Set prefixesFromRange( final Range ... ranges ) { - if( ranges == null || ranges.length == 0 ) throw new IllegalArgumentException( "Ranges is null or empty" ); + CardType(final Set prefixes, final Set lengths) { + this.prefixes = prefixes; + this.lengths = lengths; + } - final Set prefixes = new LinkedHashSet<>(); + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Spotbugs doesn't know that they're unmodifiable") + public Set getPrefixes() { + return prefixes; + } - for( final Range r : ranges ) { - if( r != null ) { - final List list = new ArrayList<>( (int)(r.getEnd() - r.getStart() + 1) ); + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Spotbugs doesn't know that they're unmodifiable") + public Set getLengths() { + return lengths; + } - for( long i = r.getStart(); i <= r.getEnd(); i++ ) { - list.add( i ); - } - - prefixes.addAll( list ); - } - } + private static Set prefixesFromRange(final Range... ranges) { + failIf(ranges == null || ranges.length == 0, () -> "Ranges is null or empty"); - return Collections.unmodifiableSet( prefixes ); - } + final Set prefixes = new LinkedHashSet<>(); - @SafeVarargs - private static List list( final T ... stuff ) { - if( stuff == null || stuff.length == 0 ) throw new IllegalArgumentException( "Null or empty vararg" ); + for (final Range r : ranges) { + if (r != null) { + final List list = new ArrayList<>((int) (r.end() - r.start() + 1)); - final List set = new ArrayList<>( stuff.length ); + for (long i = r.start(); i <= r.end(); i++) { + list.add(i); + } - for( final T t : stuff ) { - set.add( t ); - } + prefixes.addAll(list); + } + } - return Collections.unmodifiableList( set ); - } + return Collections.unmodifiableSet(prefixes); + } } diff --git a/src/main/java/org/loverde/paymentcard/PaymentCardGenerator.java b/src/main/java/org/loverde/paymentcard/PaymentCardGenerator.java index 9a03f4f..d5a1482 100644 --- a/src/main/java/org/loverde/paymentcard/PaymentCardGenerator.java +++ b/src/main/java/org/loverde/paymentcard/PaymentCardGenerator.java @@ -40,60 +40,55 @@ public interface PaymentCardGenerator { - /** - * Generates a card number for a given card type. The prefix and length are - * randomly selected from the values defined in {@linkplain CardType}. - * - * @param cardType The type of card number of generate - * - * @return A card number for the specified card type - */ - public String generateByCardType( CardType cardType ); + /** + * Generates a card number for a given card type. The prefix and length are + * randomly selected from the values defined in {@linkplain CardType}. + * + * @param cardType The type of card number of generate + * @return A card number for the specified card type + */ + String generateByCardType(CardType cardType); - /** - * Generates multiple card numbers for a given card type. The prefix and length - * are randomly selected from the values defined in {@linkplain CardType}. - * - * @param howMany How many card numbers to generate for the specified card type - * @param cardType The type of card numbers to generate - * - * @return A list of card numbers for the specified card type - */ - public List generateListByCardType( int howMany, CardType cardType ); + /** + * Generates multiple card numbers for a given card type. The prefix and length + * are randomly selected from the values defined in {@linkplain CardType}. + * + * @param howMany How many card numbers to generate for the specified card type + * @param cardType The type of card numbers to generate + * @return A list of card numbers for the specified card type + */ + List generateListByCardType(int howMany, CardType cardType); - /** - * Generates card numbers of given card types. The prefix and length are - * randomly selected from the values defined in {@linkplain CardType}. - * - * @param howManyOfEach How many card numbers to generate for each card type - * @param cardTypes Vararg of card types - * - * @return A map where the key is the card type and the value is a list of card numbers for that card type - */ - public Map> generateMapByCardTypes( int howManyOfEach, CardType ... cardTypes ); + /** + * Generates card numbers of given card types. The prefix and length are + * randomly selected from the values defined in {@linkplain CardType}. + * + * @param howManyOfEach How many card numbers to generate for each card type + * @param cardTypes Vararg of card types + * @return A map where the key is the card type and the value is a list of card numbers for that card type + */ + Map> generateMapByCardTypes(int howManyOfEach, CardType... cardTypes); - /** - * Generates numbers based on a specified prefix and length. This method does not validate the prefix - * or length arguments to determine whether they apply to a known {@linkplain CardType}. This is to - * account for the possibility that the Wikipedia articles this software is based on are incorrect, or - * that this software could be outdated. Known prefix and length options are available in the - * {@linkplain CardType} enum, if you wish to use them. Essentially, this method is a general-purpose - * Luhn number generator. - * - * @param howManyOfEachPrefix How many card numbers to generate for each prefix - * @param lengths Generated card numbers will be of lengths specified by this list - * @param prefixes Generated card numbers will start with values from this set - * - * @return A map where the key is the prefix and the value is a list of card numbers for that prefix - */ - public Map> generateByPrefix( int howManyOfEachPrefix, List lengths, Set prefixes ); + /** + * Generates numbers based on a specified prefix and length. This method does not validate the prefix + * or length arguments to determine whether they apply to a known {@linkplain CardType}. This is to + * account for the possibility that the Wikipedia articles this software is based on are incorrect, or + * that this software could be outdated. Known prefix and length options are available in the + * {@linkplain CardType} enum, if you wish to use them. Essentially, this method is a general-purpose + * Luhn number generator. + * + * @param howManyOfEachPrefix How many card numbers to generate for each prefix + * @param lengths Generated card numbers will be of lengths specified by this list + * @param prefixes Generated card numbers will start with values from this set + * @return A map where the key is the prefix and the value is a list of card numbers for that prefix + */ + Map> generateByPrefix(int howManyOfEachPrefix, Set lengths, Set prefixes); - /** - * Determines whether a number passes Luhn validation - * - * @param num A numeric string ending with a check digit - * - * @return {@code true} if the number is valid, {@code false} if not - */ - public boolean passesLuhnCheck( String num ); + /** + * Determines whether a number passes Luhn validation + * + * @param num A numeric string ending with a check digit + * @return {@code true} if the number is valid, {@code false} if not + */ + boolean passesLuhnCheck(String num); } diff --git a/src/main/java/org/loverde/paymentcard/PaymentCardGeneratorImpl.java b/src/main/java/org/loverde/paymentcard/PaymentCardGeneratorImpl.java index e16c7f7..b22870c 100644 --- a/src/main/java/org/loverde/paymentcard/PaymentCardGeneratorImpl.java +++ b/src/main/java/org/loverde/paymentcard/PaymentCardGeneratorImpl.java @@ -34,26 +34,33 @@ package org.loverde.paymentcard; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Random; import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static org.loverde.paymentcard.internal.Objects.failIf; +import static org.loverde.paymentcard.internal.Objects.randomItemFromSet; /** *

- * This software aids in testing payment card processing systems by generating random payment card - * numbers which are mathematically valid, so that you don't have to use an actual card. - * - * This class generates payment card numbers based on the criteria defined here: + * This software aids in testing payment card processing systems by generating random payment card + * numbers which are mathematically valid, so that you don't have to use an actual card. + *

+ * This class generates payment card numbers based on the criteria defined here: *

* * * *

@@ -73,172 +80,131 @@ */ public class PaymentCardGeneratorImpl implements PaymentCardGenerator { - @Override - public String generateByCardType( final CardType cardType ) { - if( cardType == null ) throw new IllegalArgumentException( "Card type is null" ); - - return generateCardNumber( cardType ); - } - - @Override - public List generateListByCardType( final int howMany, final CardType cardType ) { - if( howMany <= 0 ) throw new IllegalArgumentException( "How many must be greater than zero" ); - if( cardType == null ) throw new IllegalArgumentException( "Card type is null" ); - - final List cardNums = new ArrayList<>( howMany ); - - for( int i = 0; i < howMany; i++ ) { - cardNums.add( generateCardNumber(cardType) ); - } - - return cardNums; - } - - @Override - public Map> generateMapByCardTypes( final int howManyOfEach, final CardType ... cardTypes ) { - if( howManyOfEach <= 0 ) throw new IllegalArgumentException( "How many of each must be greater than zero" ); - if( cardTypes == null || cardTypes.length < 1 ) throw new IllegalArgumentException( "Card types is null or empty" ); + @Override + public String generateByCardType(final CardType cardType) { + failIf(cardType == null, () -> "Card type is null"); + return generateCardNumber(cardType); + } - final Set condensedCardTypes = removeVarargDuplicates( cardTypes ); - final Map> cardNums = new HashMap<>( cardTypes.length ); + @Override + public List generateListByCardType(final int howMany, final CardType cardType) { + failIf(howMany <= 0, () -> "How many must be greater than zero"); + failIf(cardType == null, () -> "Card type is null"); - for( final CardType cardType : condensedCardTypes ) { - cardNums.put( cardType, generateListByCardType(howManyOfEach, cardType) ); - } + return IntStream.range(0, howMany).mapToObj(i -> generateCardNumber(cardType)).collect(Collectors.toList()); + } - return cardNums; - } + @Override + public Map> generateMapByCardTypes(final int howManyOfEach, final CardType... cardTypes) { + failIf(howManyOfEach <= 0, () -> "How many of each must be greater than zero"); + failIf(cardTypes == null || cardTypes.length < 1, () -> "Card types is null or empty"); - @Override - public Map> generateByPrefix( final int howManyOfEachPrefix, final List lengths, final Set prefixes) { - final Map> cardNums; - final Random random; + final Map> cardNums = new HashMap<>(cardTypes.length); - if( howManyOfEachPrefix <= 0 ) throw new IllegalArgumentException( "How many of each must be greater than zero" ); - if( lengths == null || lengths.size() == 0 ) throw new IllegalArgumentException( "No lengths were specified" ); - if( prefixes == null || prefixes.size() == 0 ) throw new IllegalArgumentException( "No prefixes were specified" ); + removeVarargDuplicates(cardTypes).forEach(cardType -> cardNums.put(cardType, generateListByCardType(howManyOfEach, cardType))); - for( final Integer length : lengths ) { - if( length == null || length < 2 ) throw new IllegalArgumentException( "Invalid length: " + length ); + return cardNums; + } - for( final Long prefix : prefixes ) { - if( prefix.toString().length() > length ) throw new IllegalArgumentException( String.format("Prefix (%s) is longer than length (%d)", prefix.toString(), length) ); - if( prefix < 1 ) throw new IllegalArgumentException( String.format("Prefix (%s): prefixes must be positive numbers", prefix.toString()) ); - } - } + @Override + public Map> generateByPrefix(final int howManyOfEachPrefix, final Set lengths, final Set prefixes) { + failIf(howManyOfEachPrefix <= 0, () -> "How many of each must be greater than zero"); + failIf(lengths == null || lengths.isEmpty(), () -> "No lengths were specified"); + failIf(prefixes == null || prefixes.isEmpty(), () -> "No prefixes were specified"); - cardNums = new HashMap<>( prefixes.size() ); - random = new Random(); + for (final Integer length : lengths) { + failIf(length == null || length < 2, () -> "Invalid length: " + length); - for( final Long prefix : prefixes ) { - final List cardNumsForPrefix = new ArrayList<>( howManyOfEachPrefix ); - - for( int i = 0; i < howManyOfEachPrefix; i++ ) { - cardNumsForPrefix.add( generateCardNumber(prefix, lengths.get(random.nextInt(lengths.size()))) ); - } - - cardNums.put( prefix, cardNumsForPrefix ); - } - - return cardNums; - } + for (final Long prefix : prefixes) { + failIf(prefix.toString().length() > length, () -> "Prefix (%s) is longer than length (%d)".formatted(prefix.toString(), length)); + failIf(prefix < 1, () -> "Prefix (%s): prefixes must be positive numbers".formatted(prefix.toString())); + } + } - @Override - public boolean passesLuhnCheck( final String num ) { - if( num == null || num.isEmpty() ) throw new IllegalArgumentException( "Number is null or empty" ); + final Map> cardNums = new HashMap<>(prefixes.size()); - final int sum = calculateLuhnSum( num, true ); - final int checkDigit = calculateCheckDigit( sum ); + for (final Long prefix : prefixes) { + final List cardNumsForPrefix = new ArrayList<>(howManyOfEachPrefix); - return (sum + checkDigit) % 10 == 0 && Integer.parseInt( num.substring(num.length() - 1) ) == checkDigit; - } + for (int i = 0; i < howManyOfEachPrefix; i++) { + cardNumsForPrefix.add(generateCardNumber(prefix, randomItemFromSet(lengths))); + } - private static String generateCardNumber( final CardType cardType ) { - final String cardNum = generateCardNumber( randomFromSet(cardType.getPrefixes()), - cardType.getLengths().get(new Random().nextInt(cardType.getLengths().size())) ); - return cardNum; - } + cardNums.put(prefix, cardNumsForPrefix); + } - private static String generateCardNumber( final Long prefix, final int length ) { - final StringBuffer num = new StringBuffer( prefix.toString() ); + return cardNums; + } - final int howManyMore = length - num.toString().length() - 1; - final Random random = new Random(); + @Override + public boolean passesLuhnCheck(final String num) { + failIf(num == null || num.isEmpty(), () -> "Number is null or empty"); - for( int i = 0; i < howManyMore; i++ ) { - num.append( Integer.valueOf(random.nextInt(9)) ); - } + final int sum = calculateLuhnSum(num, true); + final int checkDigit = calculateCheckDigit(sum); - num.append( calculateCheckDigit(num.toString()) ); + return (sum + checkDigit) % 10 == 0 && Integer.parseInt(num.substring(num.length() - 1)) == checkDigit; + } - return num.toString(); - } + private static String generateCardNumber(final CardType cardType) { + return generateCardNumber( + randomItemFromSet(cardType.getPrefixes()), + randomItemFromSet(cardType.getLengths())); + } - private static int calculateCheckDigit( final String str ) { - final int sum = calculateLuhnSum( str, false ); - final int checkDigit = calculateCheckDigit( sum ); + private static String generateCardNumber(final Long prefix, final int length) { + final StringBuilder num = new StringBuilder(prefix.toString()); - return checkDigit; - } + final int howManyMore = length - num.toString().length() - 1; + final Random random = ThreadLocalRandom.current(); - private static int calculateCheckDigit( final int luhnSum ) { - final int checkDigit = (luhnSum * 9) % 10; - return checkDigit; - } + for (int i = 0; i < howManyMore; i++) { + num.append(Integer.valueOf(random.nextInt(9))); + } - private static int calculateLuhnSum( final String str, final boolean hasCheckDigit ) { - final int luhnNums[] = new int[str.length()]; - final int start = str.length() - (hasCheckDigit ? 2 : 1); - int sum = 0; + num.append(calculateCheckDigit(num.toString())); - boolean doubleMe = true; + return num.toString(); + } - for( int i = start; i >= 0; i-- ) { - final int num = Integer.parseInt( str.substring(i, i + 1) ); + private static int calculateCheckDigit(final String str) { + final int sum = calculateLuhnSum(str, false); + return calculateCheckDigit(sum); + } - if( doubleMe ) { - int x2 = num * 2; - luhnNums[i] = x2 > 9 ? x2 - 9 : x2; - } else { - luhnNums[i] = num; - } + private static int calculateCheckDigit(final int luhnSum) { + return (luhnSum * 9) % 10; + } - sum += luhnNums[i]; - doubleMe = !doubleMe; - } + private static int calculateLuhnSum(final String str, final boolean hasCheckDigit) { + final int[] luhnNums = new int[str.length()]; + final int start = str.length() - (hasCheckDigit ? 2 : 1); + int sum = 0; - return sum; - } + boolean doubleMe = true; - @SafeVarargs - private static Set removeVarargDuplicates( final T ... stuff ) { - final Set set = new HashSet<>(); + for (int i = start; i >= 0; i--) { + final int num = Integer.parseInt(str.substring(i, i + 1)); - if( stuff != null ) { - for( final T cardType : stuff ) { - if( cardType != null ) { - set.add( cardType ); + if (doubleMe) { + int x2 = num * 2; + luhnNums[i] = x2 > 9 ? x2 - 9 : x2; + } else { + luhnNums[i] = num; } - } - } - - return set; - } - - private static T randomFromSet( final Set set ) { - T item = null; - int random; - - if( set == null || set.size() < 1 ) throw new IllegalArgumentException( "Set is null or empty" ); - - random = new Random().nextInt( set.size() ); - final Iterator iterator = set.iterator(); + sum += luhnNums[i]; + doubleMe = !doubleMe; + } - for( int i = 0; i <= random; i++ ) { - item = iterator.next(); - } + return sum; + } - return item; - } + @SafeVarargs + private static Set removeVarargDuplicates(final T... stuff) { + return Stream.ofNullable(stuff) + .flatMap(Arrays::stream) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + } } diff --git a/src/main/java/org/loverde/paymentcard/Range.java b/src/main/java/org/loverde/paymentcard/Range.java index b8f542f..895fbce 100644 --- a/src/main/java/org/loverde/paymentcard/Range.java +++ b/src/main/java/org/loverde/paymentcard/Range.java @@ -34,26 +34,16 @@ package org.loverde.paymentcard; -public class Range { - private long start, - end; +import static org.loverde.paymentcard.internal.Objects.failIf; - public Range( final long start, final long end ) { - if( start > end ) throw new IllegalArgumentException( "Start cannot be greater than end" ); - this.start = start; - this.end = end; - } +public record Range (long start, long end) { - public long getStart() { - return start; - } + public Range { + failIf(start > end, () -> "Start cannot be greater than end"); + } - public long getEnd() { - return end; - } - - public long size() { - return Math.abs( getEnd() - getStart() ) + 1; - } + public long size() { + return Math.abs(end() - start()) + 1; + } } diff --git a/src/main/java/org/loverde/paymentcard/internal/Objects.java b/src/main/java/org/loverde/paymentcard/internal/Objects.java new file mode 100644 index 0000000..696d7c3 --- /dev/null +++ b/src/main/java/org/loverde/paymentcard/internal/Objects.java @@ -0,0 +1,42 @@ +package org.loverde.paymentcard.internal; + +import java.util.Iterator; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Supplier; + + +public class Objects { + + /** + * Shorthand for IF statements that throw IllegalArgumentException + * @param isFailed The result of the check + * @param iaeMessage Exception message + */ + public static void failIf(final boolean isFailed, final Supplier iaeMessage) { + if (isFailed) { + throw new IllegalArgumentException(iaeMessage.get()); + } + } + + /** + * Return a random item from a set. + * @param set The set to pull from + * @return Random item from the set, or null if the set is empty + * @param Parameterized type of the set + */ + public static T randomItemFromSet(final Set set) { + failIf(set == null, () -> "Set is null"); + + T t = null; + Iterator iter = set.iterator(); + + final int stopAt = ThreadLocalRandom.current().nextInt(set.size()); + + for (int i = 0; i <= stopAt; i++) { + t = iter.next(); + } + + return t; + } +} diff --git a/src/test/java/org/loverde/paymentcard/CardTypeTest.java b/src/test/java/org/loverde/paymentcard/CardTypeTest.java index 386df9c..a1cc201 100644 --- a/src/test/java/org/loverde/paymentcard/CardTypeTest.java +++ b/src/test/java/org/loverde/paymentcard/CardTypeTest.java @@ -33,193 +33,28 @@ package org.loverde.paymentcard; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; /** - * These tests verify that the {@linkplain CardType} enum is built properly. Validation criteria is based on - * https://en.wikipedia.org/wiki/Payment_card_number - * as of December, 2016. + * These tests verify that the {@linkplain CardType} enum is built properly. */ -public class CardTypeTest { - - /** - * If this test fails, the results of the other tests cannot be trusted - */ - @Test - public void sanityCheck_inRange() { - final Range range_1_2 = new Range( 1, 2 ); - final Range range_3 = new Range( 3, 3 ); - - final Set prefix1 = new HashSet<>(); - prefix1.add( 1L ); - - assertPrefixesWithinRange( prefix1, range_1_2 ); - - final Set prefix2 = new HashSet<>(); - prefix2.add( 2L ); - - assertPrefixesWithinRange( prefix2, range_1_2 ); - - final Set prefix3 = new HashSet<>(); - prefix3.add( 3L ); - - assertPrefixesWithinRange( prefix3, range_3 ); - - final Set prefixAll = new HashSet<>(); - prefixAll.addAll( prefix1 ); - prefixAll.addAll( prefix2 ); - prefixAll.addAll( prefix3 ); - - assertPrefixesWithinRange( prefix3, range_1_2, range_3 ); - } - - /** - * If this test fails, the results of the other tests cannot be trusted - */ - @Test( expected = AssertionError.class ) - public void sanityCheck_notInRange() { - final Set prefix = new HashSet<>(); - final Range range = new Range( 2, 3 ); - - prefix.add( 1L ); - prefix.add( 4L ); - - assertPrefixesWithinRange( prefix, range ); - } - - @Test - public void amex() { - final CardType type = CardType.AMERICAN_EXPRESS; - final List lengths = type.getLengths(); - final Set prefixes = type.getPrefixes(); - - assertEquals( 1, lengths.size() ); - assertTrue( lengths.contains(15) ); - - assertEquals( 2, prefixes.size() ); - assertTrue( prefixes.contains(34L) ); - assertTrue( prefixes.contains(37L) ); - } - - @Test - public void visa() { - final CardType type = CardType.VISA; - final List lengths = type.getLengths(); - final Set prefixes = type.getPrefixes(); - - assertEquals( 3, lengths.size() ); - assertTrue( lengths.contains(13) ); - assertTrue( lengths.contains(16) ); - assertTrue( lengths.contains(19) ); - - assertEquals( 1, prefixes.size() ); - assertTrue( prefixes.contains(4L) ); - } - - @Test - public void mastercard() { - final CardType type = CardType.MASTERCARD; - final List lengths = type.getLengths(); - final Set prefixes = type.getPrefixes(); - - assertEquals( 1, lengths.size() ); - assertTrue( lengths.contains(16) ); - - final Range prefixRange_51_55 = new Range(51, 55), - prefixRange_2221_2720 = new Range( 2221, 2720 ); - - assertEquals( prefixRange_51_55.size() + prefixRange_2221_2720.size(), - prefixes.size() ); - - assertPrefixesWithinRange( prefixes, prefixRange_51_55, prefixRange_2221_2720 ); - } - - @Test - public void discover() { - final CardType type = CardType.DISCOVER; - final List lengths = type.getLengths(); - final Set prefixes = type.getPrefixes(); - - assertEquals( 2, lengths.size() ); - assertTrue( lengths.contains(16) ); - assertTrue( lengths.contains(19) ); - - final Range prefixRange_65_65 = new Range( 65, 65 ), - prefixRange_644_649 = new Range( 644, 649 ), - prefixRange_6011_6011 = new Range( 6011, 6011 ), - prefixRange_622126_622925 = new Range( 622126, 622925 ); - - assertEquals( prefixRange_65_65.size() + - prefixRange_644_649.size() + - prefixRange_6011_6011.size() + - prefixRange_622126_622925.size() - , prefixes.size() ); - - assertPrefixesWithinRange( prefixes, prefixRange_65_65, prefixRange_644_649, prefixRange_6011_6011, prefixRange_622126_622925 ); - } - - @Test( expected = UnsupportedOperationException.class ) - public void alterPrefixes_add() { - CardType.AMERICAN_EXPRESS.getPrefixes().add( 14352L ); - } - - @Test( expected = UnsupportedOperationException.class ) - public void alterPrefixes_clear() { - CardType.DISCOVER.getPrefixes().clear(); - } - - @Test( expected = UnsupportedOperationException.class ) - public void alterPrefixes_remove() { - final Iterator iterator = CardType.MASTERCARD.getPrefixes().iterator(); - iterator.next(); - iterator.remove(); - } - - @Test( expected = UnsupportedOperationException.class ) - public void alterLengths_add() { - CardType.AMERICAN_EXPRESS.getLengths().add( 12 ); - } - - @Test( expected = UnsupportedOperationException.class ) - public void alterLengths_clear() { - CardType.DISCOVER.getLengths().clear(); - } - - @Test( expected = UnsupportedOperationException.class ) - public void alterLengths_remove() { - final Iterator iterator = CardType.MASTERCARD.getLengths().iterator(); - iterator.next(); - iterator.remove(); - } - - - private static void assertPrefixesWithinRange( final Set prefixes, final Range ... ranges ) { - if( prefixes == null || prefixes.size() < 1 ) throw new IllegalArgumentException( "No prefixes provided" ); - if( ranges == null || ranges.length < 1 ) throw new IllegalArgumentException( "No range provided" ); - - for( final Long prefix : prefixes ) { - boolean found = false; - - for( final Range range : ranges ) { - for( long rangeElement = range.getStart(); rangeElement <= range.getEnd(); rangeElement++ ) { - if( prefix.longValue() == rangeElement ) { - found = true; - break; - } - } - - } - - assertTrue( "Didn't find prefix " + prefix, found ); - } - } +class CardTypeTest { + + @ParameterizedTest(name = "CardStatus.{0} prefixes cannot be modified at run time") + @EnumSource(CardType.class) + void cardTypeEnumIsUnmodifiable_prefixes() { + assertThrows(UnsupportedOperationException.class, () -> Arrays.stream(CardType.values()).forEach(cardType -> cardType.getLengths().clear())); + } + + @ParameterizedTest(name = "CardStatus.{0} lengths cannot be modified at run time") + @EnumSource(CardType.class) + void cardTypeEnumIsUnmodifiable_lengths() { + assertThrows(UnsupportedOperationException.class, () -> Arrays.stream(CardType.values()).forEach(cardType -> cardType.getLengths().clear())); + } } diff --git a/src/test/java/org/loverde/paymentcard/PaymentCardGeneratorTest.java b/src/test/java/org/loverde/paymentcard/PaymentCardGeneratorTest.java index 57c480d..08ee219 100644 --- a/src/test/java/org/loverde/paymentcard/PaymentCardGeneratorTest.java +++ b/src/test/java/org/loverde/paymentcard/PaymentCardGeneratorTest.java @@ -33,341 +33,326 @@ package org.loverde.paymentcard; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class PaymentCardGeneratorTest { +class PaymentCardGeneratorTest { - private static final int HOW_MANY_OF_EACH = 30; + private static final int HOW_MANY_OF_EACH = 30; - private PaymentCardGenerator generator = new PaymentCardGeneratorImpl(); + private final PaymentCardGenerator generator = new PaymentCardGeneratorImpl(); - @Test( expected = IllegalArgumentException.class ) - public void generateByCardType_null() { - generator.generateByCardType( null ); - } + @Test + void generateByCardType_null() { + assertThrows(IllegalArgumentException.class, () -> generator.generateByCardType(null)); + } - @Test - public void generateByCardType_amex() { - final CardType cardType = CardType.AMERICAN_EXPRESS; - final String cardNum = generator.generateByCardType( cardType ); + @Test + void generateByCardType_amex() { + final CardType cardType = CardType.AMERICAN_EXPRESS; + final String cardNum = generator.generateByCardType(cardType); - validateCardNumber( cardType, cardNum ); - } + validateCardNumber(cardType, cardNum); + } - @Test - public void generateByCardType_visa() { - final CardType cardType = CardType.VISA; - final String cardNum = generator.generateByCardType( cardType ); + @Test + void generateByCardType_visa() { + final CardType cardType = CardType.VISA; + final String cardNum = generator.generateByCardType(cardType); - validateCardNumber( cardType, cardNum ); - } + validateCardNumber(cardType, cardNum); + } - @Test - public void generateByCardType_mastercard() { - final CardType cardType = CardType.MASTERCARD; - final String cardNum = generator.generateByCardType( cardType ); + @Test + void generateByCardType_mastercard() { + final CardType cardType = CardType.MASTERCARD; + final String cardNum = generator.generateByCardType(cardType); - validateCardNumber( cardType, cardNum ); - } + validateCardNumber(cardType, cardNum); + } - @Test - public void generateByCardType_discover() { - final CardType cardType = CardType.DISCOVER; - final String cardNum = generator.generateByCardType( cardType ); + @Test + void generateByCardType_discover() { + final CardType cardType = CardType.DISCOVER; + final String cardNum = generator.generateByCardType(cardType); - validateCardNumber( cardType, cardNum ); - } + validateCardNumber(cardType, cardNum); + } - @Test( expected = IllegalArgumentException.class ) - public void generateListByCardType_null() { - generator.generateListByCardType( 2, null ); - } + @Test + void generateListByCardType_null() { + assertThrows(IllegalArgumentException.class, () -> generator.generateListByCardType(2, null)); + } - @Test( expected = IllegalArgumentException.class ) - public void generateListByCardType_zero() { - generator.generateListByCardType( 0, CardType.AMERICAN_EXPRESS ); - } + @Test + void generateListByCardType_zero() { + assertThrows(IllegalArgumentException.class, () -> generator.generateListByCardType(0, CardType.AMERICAN_EXPRESS)); + } - @Test( expected = IllegalArgumentException.class ) - public void generateListByCardType_negative() { - generator.generateListByCardType( -1, CardType.DISCOVER ); - } + @Test + void generateListByCardType_negative() { + assertThrows(IllegalArgumentException.class, () -> generator.generateListByCardType(-1, CardType.DISCOVER)); + } - @Test - public void generateListByCardType_amex() { - final CardType cardType = CardType.AMERICAN_EXPRESS; - final List cardNums = generator.generateListByCardType( HOW_MANY_OF_EACH, cardType ); + @Test + void generateListByCardType_amex() { + final CardType cardType = CardType.AMERICAN_EXPRESS; + final List cardNums = generator.generateListByCardType(HOW_MANY_OF_EACH, cardType); - generateListByCardType_validate( cardType, cardNums ); - } + generateListByCardType_validate(cardType, cardNums); + } - @Test - public void generateListByCardType_visa() { - final CardType cardType = CardType.VISA; - final List cardNums = generator.generateListByCardType( HOW_MANY_OF_EACH, cardType ); + @Test + void generateListByCardType_visa() { + final CardType cardType = CardType.VISA; + final List cardNums = generator.generateListByCardType(HOW_MANY_OF_EACH, cardType); - generateListByCardType_validate( cardType, cardNums ); - } + generateListByCardType_validate(cardType, cardNums); + } - @Test - public void generateListByCardType_mastercard() { - final CardType cardType = CardType.MASTERCARD; - final List cardNums = generator.generateListByCardType( HOW_MANY_OF_EACH, cardType ); + @Test + void generateListByCardType_mastercard() { + final CardType cardType = CardType.MASTERCARD; + final List cardNums = generator.generateListByCardType(HOW_MANY_OF_EACH, cardType); - generateListByCardType_validate( cardType, cardNums ); - } + generateListByCardType_validate(cardType, cardNums); + } - @Test - public void generateListByCardType_discover() { - final CardType cardType = CardType.DISCOVER; - final List cardNums = generator.generateListByCardType( HOW_MANY_OF_EACH, cardType ); + @Test + void generateListByCardType_discover() { + final CardType cardType = CardType.DISCOVER; + final List cardNums = generator.generateListByCardType(HOW_MANY_OF_EACH, cardType); - generateListByCardType_validate( cardType, cardNums ); - } + generateListByCardType_validate(cardType, cardNums); + } - private void generateListByCardType_validate( final CardType cardType, final List cards ) { - assertEquals( HOW_MANY_OF_EACH, cards.size() ); + private void generateListByCardType_validate(final CardType cardType, final List cards) { + assertEquals(HOW_MANY_OF_EACH, cards.size()); - for( final String cardNum : cards ) { - validateCardNumber( cardType, cardNum ); - } - } + for (final String cardNum : cards) { + validateCardNumber(cardType, cardNum); + } + } - @Test( expected = IllegalArgumentException.class ) - public void generateMapByCardTypes_nullCardTypes() { - CardType cardTypes[] = null; - generator.generateMapByCardTypes( 2, cardTypes ); - } - - @Test( expected = IllegalArgumentException.class ) - public void generateMapByCardTypes_emptyCardTypes() { - generator.generateMapByCardTypes( 2, new CardType[]{} ); - } - - @Test( expected = IllegalArgumentException.class ) - public void generateMapByCardTypes_zero() { - generator.generateMapByCardTypes( 0, CardType.AMERICAN_EXPRESS ); - } - - @Test( expected = IllegalArgumentException.class ) - public void generateMapByCardTypes_negative() { - generator.generateMapByCardTypes( -1, CardType.AMERICAN_EXPRESS ); - } - - @Test - public void generateMapByCardTypes() { - final Map> cardMap = generator.generateMapByCardTypes( HOW_MANY_OF_EACH, CardType.values() ); - - assertEquals( "Didn't generate all of the specified card types", CardType.values().length, cardMap.size() ); - - int howManyCards = 0; - - for( final List list : cardMap.values() ) { - howManyCards += list.size(); - } - - assertEquals( "Didn't generate the correct number of cards", HOW_MANY_OF_EACH * CardType.values().length, howManyCards ); - - for( final Entry> entry : cardMap.entrySet() ) { - final List cardNumbers = entry.getValue(); - - for( final String num : cardNumbers ) { - validateCardNumber( entry.getKey(), num ); - } - } - } - - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_makeZero() { - generator.generateByPrefix( 0, CardType.AMERICAN_EXPRESS.getLengths(), CardType.AMERICAN_EXPRESS.getPrefixes() ); - } - - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_makeNegative() { - generator.generateByPrefix( -1, CardType.AMERICAN_EXPRESS.getLengths(), CardType.AMERICAN_EXPRESS.getPrefixes() ); - } - - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_nullLengths() { - generator.generateByPrefix( 1, null, CardType.AMERICAN_EXPRESS.getPrefixes() ); - } - - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_emptyLengths() { - generator.generateByPrefix( 1, new ArrayList(), CardType.AMERICAN_EXPRESS.getPrefixes() ); - } - - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_invalidLengths_zero() { - final List lengths = new ArrayList(); - lengths.addAll( CardType.AMERICAN_EXPRESS.getLengths() ); - lengths.add( 0 ); + @Test + void generateMapByCardTypes_nullCardTypes() { + assertThrows(IllegalArgumentException.class, () -> generator.generateMapByCardTypes(2, (CardType[]) null)); + } + + @Test + void generateMapByCardTypes_emptyCardTypes() { + assertThrows(IllegalArgumentException.class, () -> generator.generateMapByCardTypes(2, new CardType[]{})); + } + + @Test + void generateMapByCardTypes_zero() { + assertThrows(IllegalArgumentException.class, () -> generator.generateMapByCardTypes(0, CardType.AMERICAN_EXPRESS)); + } + + @Test + void generateMapByCardTypes_negative() { + assertThrows(IllegalArgumentException.class, () -> generator.generateMapByCardTypes(-1, CardType.AMERICAN_EXPRESS)); + } + + @Test + void generateMapByCardTypes() { + final Map> cardMap = generator.generateMapByCardTypes(HOW_MANY_OF_EACH, CardType.values()); + + assertEquals(CardType.values().length, cardMap.size(), "Didn't generate all of the specified card types"); + + int howManyCards = 0; + + for (final List list : cardMap.values()) { + howManyCards += list.size(); + } + + assertEquals(HOW_MANY_OF_EACH * CardType.values().length, howManyCards, "Didn't generate the correct number of cards"); + + for (final Entry> entry : cardMap.entrySet()) { + final List cardNumbers = entry.getValue(); + + for (final String num : cardNumbers) { + validateCardNumber(entry.getKey(), num); + } + } + } + + @Test + void generateByPrefix_makeZero() { + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(0, CardType.AMERICAN_EXPRESS.getLengths(), CardType.AMERICAN_EXPRESS.getPrefixes())); + } + + @Test + void generateByPrefix_makeNegative() { + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(-1, CardType.AMERICAN_EXPRESS.getLengths(), CardType.AMERICAN_EXPRESS.getPrefixes())); + } + + @Test + void generateByPrefix_nullLengths() { + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, null, CardType.AMERICAN_EXPRESS.getPrefixes())); + } - generator.generateByPrefix( 1, lengths, CardType.AMERICAN_EXPRESS.getPrefixes() ); - } + @Test + void generateByPrefix_emptyLengths() { + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, Set.of(), CardType.AMERICAN_EXPRESS.getPrefixes())); + } - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_invalidLengths_negative() { - final List lengths = new ArrayList(); - lengths.addAll( CardType.AMERICAN_EXPRESS.getLengths() ); - lengths.add( -1 ); + @Test + void generateByPrefix_invalidLengths_zero() { + final Set lengths = Set.of(0); + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, lengths, CardType.AMERICAN_EXPRESS.getPrefixes())); + } - generator.generateByPrefix( 1, lengths, CardType.AMERICAN_EXPRESS.getPrefixes() ); - } + @Test + void generateByPrefix_invalidLengths_negative() { + final Set lengths = Set.of(-1); + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, lengths, CardType.AMERICAN_EXPRESS.getPrefixes())); + } - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_invalidLengths_lessThan2() { - final List lengths = new ArrayList(); - lengths.addAll( CardType.AMERICAN_EXPRESS.getLengths() ); - lengths.add( 1 ); + @Test + void generateByPrefix_invalidLengths_lessThan2() { + final Set lengths = Set.of(1); - // Ensure that we hit the correct validation failure: the prefix is not longer than the length - final Set prefixes = new HashSet<>(); - prefixes.add( 1L ); + // Ensure that we hit the correct validation failure: the prefix is not longer than the length + final Set prefixes = new HashSet<>(); + prefixes.add(1L); - generator.generateByPrefix( 1, lengths, prefixes ); - } + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, lengths, prefixes)); + } - @Test - public void generateByPrefix_minimumLengthOf2() { - final List lengths = new ArrayList(); - lengths.add( 2 ); + @Test + void generateByPrefix_minimumLengthOf2() { + final Set lengths = Set.of(2); - final Set prefixes = new HashSet<>(); - prefixes.add( 1L ); + final Set prefixes = new HashSet<>(); + prefixes.add(1L); + + generator.generateByPrefix(1, lengths, prefixes); + } + + @Test + void generateByPrefix_nullPrefixes() { + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, CardType.AMERICAN_EXPRESS.getLengths(), null)); + } - generator.generateByPrefix( 1, lengths, prefixes ); - } + @Test + void generateByPrefix_emptyPrefixes() { + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, CardType.AMERICAN_EXPRESS.getLengths(), new HashSet<>())); + } + + @Test + void generateByPrefix_prefixIsLongerThanLength() { + final Set lengths = Set.of(4); - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_nullPrefixes() { - generator.generateByPrefix( 1, CardType.AMERICAN_EXPRESS.getLengths(), null ); - } + final Set prefixes = new HashSet<>(); + prefixes.add(12345L); - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_emptyPrefixes() { - generator.generateByPrefix( 1, CardType.AMERICAN_EXPRESS.getLengths(), new HashSet() ); - } + assertThrows(IllegalArgumentException.class, () -> generator.generateByPrefix(1, lengths, prefixes)); + } - @Test( expected = IllegalArgumentException.class ) - public void generateByPrefix_prefixIsLongerThanLength() { - final List lengths = new ArrayList<>(); - lengths.add( 4 ); + @Test + void generateByPrefix_amex() { + final CardType cardType = CardType.AMERICAN_EXPRESS; + final Map> cards = generator.generateByPrefix(HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes()); - final Set prefixes = new HashSet(); - prefixes.add( 12345L ); + generateByPrefix_validate(HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards); + } - generator.generateByPrefix( 1, lengths, prefixes ); - } + @Test + void generateByPrefix_visa() { + final CardType cardType = CardType.VISA; + final Map> cards = generator.generateByPrefix(HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes()); + + generateByPrefix_validate(HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards); + } - @Test - public void generateByPrefix_amex() { - final CardType cardType = CardType.AMERICAN_EXPRESS; - final Map> cards = generator.generateByPrefix( HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes() ); + @Test + void generateByPrefix_mastercard() { + final CardType cardType = CardType.MASTERCARD; + final Map> cards = generator.generateByPrefix(HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes()); + + generateByPrefix_validate(HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards); + } + + @Test + void generateByPrefix_discover() { + final CardType cardType = CardType.AMERICAN_EXPRESS; + final Map> cards = generator.generateByPrefix(HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes()); + + generateByPrefix_validate(HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards); + } - generateByPrefix_validate( HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards ); - } + @Test + void generateByPrefix_someFutureFormat() { + final Set lengths = Set.of(15, 17); + final Set prefixes = new HashSet<>(); - @Test - public void generateByPrefix_visa() { - final CardType cardType = CardType.VISA; - final Map> cards = generator.generateByPrefix( HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes() ); - - generateByPrefix_validate( HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards ); - } + prefixes.add(987L); - @Test - public void generateByPrefix_mastercard() { - final CardType cardType = CardType.MASTERCARD; - final Map> cards = generator.generateByPrefix( HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes() ); + final Map> cards = generator.generateByPrefix(HOW_MANY_OF_EACH, lengths, prefixes); - generateByPrefix_validate( HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards ); - } + generateByPrefix_validate(HOW_MANY_OF_EACH, lengths, prefixes, cards); + } - @Test - public void generateByPrefix_discover() { - final CardType cardType = CardType.AMERICAN_EXPRESS; - final Map> cards = generator.generateByPrefix( HOW_MANY_OF_EACH, cardType.getLengths(), cardType.getPrefixes() ); + private void generateByPrefix_validate(final int expectedCards, final Set validLengths, final Set validPrefixes, final Map> cardsMap) { + int howManyCards = 0; - generateByPrefix_validate( HOW_MANY_OF_EACH * cardType.getPrefixes().size(), cardType.getLengths(), cardType.getPrefixes(), cards ); - } + for (final List list : cardsMap.values()) { + howManyCards += list.size(); + } - @Test - public void generateByPrefix_someFutureFormat() { - final List lengths = new ArrayList<>(); + assertEquals(expectedCards, howManyCards, "Didn't generate the correct number of cards"); - lengths.add( 15 ); - lengths.add( 17 ); + for (final Entry> entry : cardsMap.entrySet()) { + final List cardNumbers = entry.getValue(); - final Set prefixes = new HashSet<>(); + for (final String num : cardNumbers) { + assertTrue(num.startsWith(entry.getKey().toString()), "Card number " + num + " was put in the bucket for prefix " + entry.getKey()); + validateCardNumber(validLengths, validPrefixes, num); + } + } + } - prefixes.add( 987L ); + @Test + void passesLuhnCheck() { + assertTrue(generator.passesLuhnCheck("378282246310005")); + assertTrue(generator.passesLuhnCheck("4111111111111111")); + assertTrue(generator.passesLuhnCheck("5105105105105100")); + assertTrue(generator.passesLuhnCheck("6011111111111117")); - final Map> cards = generator.generateByPrefix( HOW_MANY_OF_EACH, lengths, prefixes ); + assertFalse(generator.passesLuhnCheck("378282246310004")); + assertFalse(generator.passesLuhnCheck("411111111111111")); + } - generateByPrefix_validate( HOW_MANY_OF_EACH, lengths, prefixes, cards ); - } + private void validateCardNumber(final CardType cardType, final String cardNum) { + validateCardNumber(cardType.getLengths(), cardType.getPrefixes(), cardNum); + } - private void generateByPrefix_validate( final int expectedCards, final List validLengths, final Set validPrefixes, final Map> cardsMap ) { - int howManyCards = 0; + private void validateCardNumber(final Set validLengths, final Set validPrefixes, final String cardNum) { + assertTrue(validLengths.contains(cardNum.length()), "Card number " + cardNum + " has an invalid length"); + assertTrue(generator.passesLuhnCheck(cardNum), "Card number " + cardNum + " doesn't pass Luhn validation"); - for( final List list : cardsMap.values() ) { - howManyCards += list.size(); - } + boolean validPrefix = false; - assertEquals( "Didn't generate the correct number of cards", expectedCards, howManyCards ); + for (final Long prefix : validPrefixes) { + if (cardNum.startsWith(prefix.toString())) { + validPrefix = true; + break; + } + } - for( final Entry> entry : cardsMap.entrySet() ) { - final List cardNumbers = entry.getValue(); - - for( final String num : cardNumbers ) { - assertTrue( "Card number " + num + " was put in the bucket for prefix " + entry.getKey(), num.startsWith(entry.getKey().toString()) ); - validateCardNumber( validLengths, validPrefixes, num ); - } - } - } - - @Test - public void passesLuhnCheck() { - assertTrue( generator.passesLuhnCheck("378282246310005") ); - assertTrue( generator.passesLuhnCheck("4111111111111111") ); - assertTrue( generator.passesLuhnCheck("5105105105105100") ); - assertTrue( generator.passesLuhnCheck("6011111111111117") ); - - assertFalse( generator.passesLuhnCheck("378282246310004") ); - assertFalse( generator.passesLuhnCheck("411111111111111") ); - } - - private void validateCardNumber( final CardType cardType, final String cardNum ) { - validateCardNumber( cardType.getLengths(), cardType.getPrefixes(), cardNum ); - } - - private void validateCardNumber( final List validLengths, final Set validPrefixes, final String cardNum ) { - assertTrue( "Card number " + cardNum + " has an invalid length", validLengths.contains(cardNum.length()) ); - assertTrue( "Card number " + cardNum + " doesn't pass Luhn validation", generator.passesLuhnCheck(cardNum) ); - - boolean validPrefix = false; - - for( final Long prefix : validPrefixes ) { - if( cardNum.startsWith(prefix.toString()) ) { - validPrefix = true; - break; - } - } - - assertTrue( "Card number " + cardNum + " has an invalid prefix", validPrefix ); - } + assertTrue(validPrefix, "Card number " + cardNum + " has an invalid prefix"); + } } diff --git a/src/test/java/org/loverde/paymentcard/RangeTest.java b/src/test/java/org/loverde/paymentcard/RangeTest.java index a9deb97..cfebbb9 100644 --- a/src/test/java/org/loverde/paymentcard/RangeTest.java +++ b/src/test/java/org/loverde/paymentcard/RangeTest.java @@ -33,33 +33,26 @@ package org.loverde.paymentcard; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class RangeTest { +class RangeTest { - @Test - public void size_startEndSame() { - assertEquals( 1, new Range(100, 100).size() ); - } + @Test + void size_startEndSame() { + assertEquals(1, new Range(100, 100).size()); + } - @Test - public void size_startEndDifferent() { - assertEquals( 3, new Range(100, 102).size() ); - } + @Test + void size_startEndDifferent() { + assertEquals(3, new Range(100, 102).size()); + } - @Test( expected = IllegalArgumentException.class ) - public void size_startGreaterThanEnd() { - new Range( 2, 1 ); - } - - @Test - public void getters() { - final Range range = new Range( 1, 2 ); - - assertEquals( 1, range.getStart() ); - assertEquals( 2, range.getEnd() ); - } + @Test + void size_startGreaterThanEnd() { + assertThrows(IllegalArgumentException.class, () -> new Range(2, 1)); + } }