Skip to content

Commit

Permalink
feat: generate random decimals with decimal points
Browse files Browse the repository at this point in the history
  • Loading branch information
Ronald Holshausen committed Sep 20, 2020
1 parent 62bdb1e commit 6e0b293
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,23 @@ data class RandomDecimalGenerator(val digits: Int) : Generator {
return mapOf("type" to "RandomDecimal", "digits" to digits)
}

override fun generate(context: Map<String, Any?>): Any = BigDecimal(RandomStringUtils.randomNumeric(digits))
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 BigDecimal(generated)
}

companion object {
fun fromJson(json: JsonValue.Object): RandomDecimalGenerator {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package au.com.dius.pact.core.model.generators

import spock.lang.Rollup
import spock.lang.Specification

class RandomDecimalGeneratorSpec extends Specification {

@Rollup
def 'generates a value with a decimal point and only a leading zero if the point is in the second position'() {
given:
def generator = new RandomDecimalGenerator(8)

expect:
with(generator.generate([:]).toString()) {
it.length() == 9
it ==~ /^\d+\.\d+/
it[0] != '0' || (it[0] == '0' && it[1] == '.')
}

where:
_samples << (1..100).step(1)
}
}

0 comments on commit 6e0b293

Please sign in to comment.