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

DnsRecordResolverTest: Use seeded random number generator for deterministic test result #1306

Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import org.xbill.DNS.Name
import org.xbill.DNS.SRVRecord
import org.xbill.DNS.TXTRecord
import javax.inject.Inject
import kotlin.random.Random

@HiltAndroidTest
class DnsRecordResolverTest {
Expand Down Expand Up @@ -69,8 +70,9 @@ class DnsRecordResolverTest {
// entries are selected randomly (for load balancing)
// run 1000 times to get a good distribution
val counts = IntArray(2)
val seededRandom = Random(0) // Seed of 0 ensures 100% deterministic non-failing results
sunkup marked this conversation as resolved.
Show resolved Hide resolved
for (i in 0 until 1000) {
val result = dnsRecordResolver.bestSRVRecord(arrayOf(dns1010, dns1020))
val result = dnsRecordResolver.bestSRVRecord(arrayOf(dns1010, dns1020), seededRandom)

when (result) {
dns1010 -> counts[0]++
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import java.util.LinkedList
import java.util.TreeMap
import java.util.logging.Logger
import javax.inject.Inject
import kotlin.random.Random

/**
* Allows to resolve SRV/TXT records. Chooses the correct resolver, DNS servers etc.
Expand Down Expand Up @@ -102,7 +103,14 @@ class DnsRecordResolver @Inject constructor(

// record selection

fun bestSRVRecord(records: Array<out Record>): SRVRecord? {
/**
* Selects the best SRV record from a list of records, based on algorithm from RFC 2782.
*
* @param records the records to choose from
* @param randomGenerator a random number generator to use for random selection
* @return the best SRV record, or `null` if no SRV record is available
*/
fun bestSRVRecord(records: Array<out Record>, randomGenerator: Random = Random.Default): SRVRecord? {
val srvRecords = records.filterIsInstance<SRVRecord>()
if (srvRecords.size <= 1)
return srvRecords.firstOrNull()
Expand Down Expand Up @@ -141,7 +149,7 @@ class DnsRecordResolver @Inject constructor(
map[runningWeight] = record
}

val selector = (0..runningWeight).random()
val selector = (0..runningWeight).random(randomGenerator)
return map.ceilingEntry(selector)!!.value
}

Expand Down