Created
September 23, 2014 15:34
-
-
Save sortega/5a7d77e7f043de1789fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.scalacheck.Gen | |
import org.scalatest.{ShouldMatchers, FlatSpec} | |
import org.scalatest.prop.PropertyChecks | |
class AllocatorTest extends FlatSpec with ShouldMatchers with PropertyChecks { | |
val positives = Gen.posNum[Int] | |
val vectorOfPositives = Gen.nonEmptyContainerOf[Vector, Int](positives) | |
"A proportional distribution" should "have the same amounts as weights" in { | |
forAll (positives, vectorOfPositives) { (amount, weights) => | |
Allocator.allocate(amount, weights) should have length weights.length | |
} | |
} | |
it should "fully distribute the input amount" in { | |
forAll (positives, vectorOfPositives) { (amount, weights) => | |
Allocator.allocate(amount, weights).sum shouldBe amount | |
} | |
} | |
it should "have amounts proportional to the corresponding weight" in { | |
forAll (positives, vectorOfPositives) { (amount, weights) => | |
val amounts = Allocator.allocate(amount, weights) | |
val totalWeight = BigDecimal(weights.sum) | |
val proportions = weights.map(w => BigDecimal(w) / totalWeight) | |
for ((elem, proportion) <- amounts.zip(proportions)) { | |
val error = (proportion * BigDecimal(amount) - BigDecimal(elem)).abs | |
error should be < BigDecimal(1) | |
} | |
} | |
} | |
it should "be fair" in { | |
forAll (positives, vectorOfPositives) { (amount, weights) => | |
shouldBeAFairDistribution(weights, Allocator.allocate(amount, weights)) | |
} | |
} | |
def shouldBeAFairDistribution(weights: Vector[Int], amounts: Vector[Int]): Unit = { | |
for { | |
i <- 0 to (weights.size - 1) | |
j <- 0 to (weights.size - 1) | |
if weights(i) > weights(j) | |
} withClue(s"Comparing $i and $j of $amounts generated from weights $weights") { | |
amounts(i) should be >= amounts(j) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment