Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace java.util.Random with kotlin.random.Random #259

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions core/src/main/kotlin/io/github/serpro69/kfaker/FakerConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
package io.github.serpro69.kfaker

import io.github.serpro69.kfaker.provider.misc.RandomProviderConfig
import java.util.*
import kotlin.random.Random

/**
* Configuration for implementations of [AbstractFaker].
Expand Down Expand Up @@ -49,7 +49,7 @@ class FakerConfig private constructor(
@FakerDsl
class Builder internal constructor() {
var locale = "en"
var random = Random()
var random: Random = Random.Default
var randomSeed: Long? = null
var uniqueGeneratorRetryLimit = 100
private var randomProviderConfig: RandomProviderConfig? = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import java.util.regex.Matcher
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
import kotlin.random.asJavaRandom

/**
* Internal class used for resolving yaml expressions into values.
Expand Down Expand Up @@ -572,7 +573,7 @@ class FakerService {
* Returns a random string generated from this [String] receiver pattern.
*/
val String.regexify: () -> String
get() = { RgxGen.parse(this).generate(faker.config.random) }
get() = { RgxGen.parse(this).generate(faker.config.random.asJavaRandom()) }

/**
* Returns an instance of [FakeDataProvider] fetched by its [simpleClassName] (case-insensitive).
Expand Down
31 changes: 11 additions & 20 deletions core/src/main/kotlin/io/github/serpro69/kfaker/RandomService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import java.time.Duration
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.*
import java.util.Locale
import java.util.UUID
import kotlin.experimental.and
import kotlin.experimental.or
import kotlin.random.asKotlinRandom
import kotlin.random.Random

/**
* Wrapper around [Random] that also contains some additional functions not covered by [Random].
Expand Down Expand Up @@ -48,7 +49,7 @@ class RandomService internal constructor(override val config: FakerConfig) : IRa

override fun nextLetter(upper: Boolean): Char {
val source = if (upper) alphabeticUpperCharset else alphabeticLowerCharset
return source.random(config.random.asKotlinRandom())
return source.random(config.random)
}

override fun randomString(length: Int, numericalChars: Boolean): String {
Expand All @@ -57,25 +58,15 @@ class RandomService internal constructor(override val config: FakerConfig) : IRa
alphabeticLowerCharset + alphabeticUpperCharset + numericCharset
} else alphabeticLowerCharset + alphabeticUpperCharset
return (1..length)
.map { charset.random(this.random.asKotlinRandom()) }
.map { charset.random(this.random) }
.joinToString("")
}

override fun nextBoolean() = random.nextBoolean()

override fun nextLong() = random.nextLong()

override fun nextLong(bound: Long): Long {
return if (bound > 0) {
var value: Long

do {
val bits = (nextLong().shl(1)).shr(1)
value = bits % bound
} while (bits - value + (bound - 1) < 0L)
value
} else throw IllegalArgumentException("Bound bound must be greater than 0")
}
override fun nextLong(bound: Long) = random.nextLong(bound)

override fun nextLong(longRange: LongRange): Long {
val lowerBound = requireNotNull(longRange.minOrNull())
Expand All @@ -84,7 +75,7 @@ class RandomService internal constructor(override val config: FakerConfig) : IRa
return nextLong(lowerBound, upperBound)
}

override fun nextLong(min: Long, max: Long) = nextLong(max - min + 1) + min
override fun nextLong(min: Long, max: Long) = random.nextLong(min, max)

override fun nextFloat() = random.nextFloat()

Expand Down Expand Up @@ -123,7 +114,7 @@ class RandomService internal constructor(override val config: FakerConfig) : IRa
} else emptyList()
val numChars = if (numericalChars) numericCharset else emptyList()
val chars = (mainChars + auxChars + idxChars + punctChars + numChars)
return List(length) { chars.random(random.asKotlinRandom()) }.joinToString("")
return List(length) { chars.random(random) }.joinToString("")
}

override fun randomString(
Expand Down Expand Up @@ -244,14 +235,14 @@ class RandomService internal constructor(override val config: FakerConfig) : IRa

private fun <T> Collection<T>.randomFromToIndices(s: Int): Pair<Int, Int> {
val fromIndex = if (s > 0) {
(0..size - s).random(random.asKotlinRandom())
(0..size - s).random(random)
} else {
(indices).random(random.asKotlinRandom())
(indices).random(random)
}
val toIndex = if (s > 0) {
fromIndex + s
} else {
(fromIndex..size).random(random.asKotlinRandom())
(fromIndex..size).random(random)
}

return fromIndex to toIndex
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package io.github.serpro69.kfaker.provider

import java.time.LocalDate
import java.util.*
import kotlin.random.asKotlinRandom
import kotlin.random.Random

/**
* [FakeDataProvider] implementation class for functionality not covered by the standard dictionary files.
Expand Down Expand Up @@ -35,8 +35,8 @@ class Person internal constructor(private val random: Random) {
val startDate = at.minusYears(age + 1)
val endDate = startDate.plusYears(1).minusDays(1)
val startMaxDays = if (startDate.isLeapYear) 366 else 365
val lower = LocalDate.ofYearDay(startDate.year, (startDate.dayOfYear..startMaxDays).random(random.asKotlinRandom()))
val upper = LocalDate.ofYearDay(endDate.year, (1..endDate.dayOfYear).random(random.asKotlinRandom()))
val lower = LocalDate.ofYearDay(startDate.year, (startDate.dayOfYear..startMaxDays).random(random))
val upper = LocalDate.ofYearDay(endDate.year, (1..endDate.dayOfYear).random(random))
val dates = if (lower.month == at.month && lower.dayOfMonth == at.dayOfMonth) {
lower.plusDays(1) to upper
} else if (upper.month == at.month && upper.dayOfMonth == at.dayOfMonth) {
Expand All @@ -45,5 +45,5 @@ class Person internal constructor(private val random: Random) {
return dates.random()
}

private fun Pair<LocalDate, LocalDate>.random() = listOf(first, second).random(random.asKotlinRandom())
private fun Pair<LocalDate, LocalDate>.random() = listOf(first, second).random(random)
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import org.junit.jupiter.api.Test;

import java.util.Random;
import kotlin.random.Random;

import static io.github.serpro69.kfaker.FunctionalUtil.fromConsumer;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
Expand All @@ -13,7 +13,7 @@ class FakerConfigTestJava {
void testConfiguringFakerInJava() {
FakerConfig fakerConfig = FakerConfigBuilder.fakerConfig(fromConsumer(builder -> {
builder.setLocale("en-AU");
builder.setRandom(new Random(42));
builder.setRandom(Random.Default);
}));

String name = new Faker(fakerConfig).getName().name();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
import java.util.*
import kotlin.random.Random

class FakerConfigTest : DescribeSpec() {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package io.github.serpro69.kfaker
import io.kotest.assertions.assertSoftly
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
import java.util.*
import kotlin.random.Random

@Suppress("UNCHECKED_CAST")
class FakerTest : DescribeSpec({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.*
import kotlin.random.Random

internal class RandomServiceTest : DescribeSpec({
describe("RandomService instance") {
val config = fakerConfig { random = Random() }
val config = fakerConfig { random = Random.Default }
val randomService = RandomService(config)

context("nextInt(bound) fun") {
Expand Down Expand Up @@ -142,11 +143,15 @@ internal class RandomServiceTest : DescribeSpec({
}

context("nextLong(min, max) fun") {
val values = List(100) { randomService.nextLong(6L, 8L) }

it("return value should be within specified range") {
val values = List(100) { randomService.nextLong(6L, 8L) }
values.all { it in 6L..8L } shouldBe true
}

it("should return positive values with Long.MAX_VALUE upper bound") {
val values = List(100) { randomService.nextLong(1L, Long.MAX_VALUE) }
values.all { it > 0L } shouldBe true
}
}

context("nextLong(longRange) fun") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
import java.time.LocalDate
import java.time.temporal.ChronoUnit
import java.util.*
import kotlin.random.Random

class PersonTest : DescribeSpec({
describe("Person provider") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ import io.kotest.matchers.string.shouldHaveLength
import io.kotest.matchers.types.instanceOf
import io.kotest.matchers.types.shouldNotBeSameInstanceAs
import org.junit.jupiter.api.assertThrows
import java.util.Random
import java.util.UUID
import kotlin.random.Random
import kotlin.reflect.full.declaredMemberProperties

@Suppress("unused")
class RandomClassProviderTest : DescribeSpec({
assertSoftly = true

val config = fakerConfig { random = Random() }
val config = fakerConfig { random = Random.Default }
val randomProvider = RandomClassProvider(config)

describe("a TestClass with an empty constructor") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.kotest.matchers.types.beInstanceOf
import java.util.*
import kotlin.random.Random

class RandomProviderTest : DescribeSpec({
describe("RandomProvider instance") {
val fakerService = FakerService(faker {
fakerConfig {
random = Random()
random = Random.Default
uniqueGeneratorRetryLimit = 1000
}
})
Expand Down
Loading