Skip to content

Commit

Permalink
chore: handle edge cases with RandomDecimalGenerator
Browse files Browse the repository at this point in the history
  • Loading branch information
Ronald Holshausen committed Sep 20, 2020
1 parent 6e0b293 commit 2a1cdf5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -127,21 +127,28 @@ data class RandomDecimalGenerator(val digits: Int) : Generator {
}

override fun generate(context: Map<String, Any?>): Any {
val sampleDigits = RandomStringUtils.randomNumeric(digits + 1)
val pos = RandomUtils.nextInt(1, digits - 1)
val selectedDigits = if (sampleDigits.startsWith("00")) {
RandomUtils.nextInt(1, 9).toString() + sampleDigits.substring(1, digits)
} else if (pos != 1 && sampleDigits.startsWith('0')) {
sampleDigits.substring(1)
} else {
sampleDigits.substring(0, digits)
}
val generated = "${selectedDigits.substring(0, pos)}.${selectedDigits.substring(pos)}"
logger.trace {
"RandomDecimalGenerator: sampleDigits=[$sampleDigits], pos=$pos, selectedDigits=[$selectedDigits], " +
"generated=[$generated]"
return when {
digits < 1 -> throw UnsupportedOperationException("RandomDecimalGenerator digits must be > 0, got $digits")
digits == 1 -> BigDecimal(RandomUtils.nextInt(0, 9))
digits == 2 -> BigDecimal("${RandomUtils.nextInt(0, 9)}.${RandomUtils.nextInt(0, 9)}")
else -> {
val sampleDigits = RandomStringUtils.randomNumeric(digits + 1)
val pos = RandomUtils.nextInt(1, digits - 1)
val selectedDigits = if (sampleDigits.startsWith("00")) {
RandomUtils.nextInt(1, 9).toString() + sampleDigits.substring(1, digits)
} else if (pos != 1 && sampleDigits.startsWith('0')) {
sampleDigits.substring(1)
} else {
sampleDigits.substring(0, digits)
}
val generated = "${selectedDigits.substring(0, pos)}.${selectedDigits.substring(pos)}"
logger.trace {
"RandomDecimalGenerator: sampleDigits=[$sampleDigits], pos=$pos, selectedDigits=[$selectedDigits], " +
"generated=[$generated]"
}
BigDecimal(generated)
}
}
return BigDecimal(generated)
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,14 @@ class RandomDecimalGeneratorSpec extends Specification {
where:
_samples << (1..100).step(1)
}

def 'handle edge case when digits == 1'() {
expect:
new RandomDecimalGenerator(1).generate([:]).toString() ==~ /^\d/
}

def 'handle edge case when digits == 2'() {
expect:
new RandomDecimalGenerator(2).generate([:]).toString() ==~ /^\d\.\d/
}
}

0 comments on commit 2a1cdf5

Please sign in to comment.