From: David Mudrak Date: Mon, 4 Jan 2010 18:10:18 +0000 (+0000) Subject: Adding percent_to_value() helper + its unittests X-Git-Url: http://git.mjollnir.org/gw?a=commitdiff_plain;h=61b737a51c3e41eab42bff08d8c4e79c967df8dd;p=moodle.git Adding percent_to_value() helper + its unittests --- diff --git a/mod/workshop/locallib.php b/mod/workshop/locallib.php index 8ec9d595ed..08e6fbdc5d 100644 --- a/mod/workshop/locallib.php +++ b/mod/workshop/locallib.php @@ -132,6 +132,21 @@ class workshop { 'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0); } + /** + * Given the percent and the total, returns the number + * + * @param float $percent from 0 to 100 + * @param float $total the 100% value + * @return float + */ + public static function percent_to_value($percent, $total) { + if ($percent < 0 or $percent > 100) { + throw new coding_exception('The percent can not be less than 0 or higher than 100'); + } + + return $total * $percent / 100; + } + //////////////////////////////////////////////////////////////////////////////// // Workshop API // //////////////////////////////////////////////////////////////////////////////// diff --git a/mod/workshop/simpletest/testworkshopapi.php b/mod/workshop/simpletest/testworkshopapi.php index a85100fc91..b165485daf 100644 --- a/mod/workshop/simpletest/testworkshopapi.php +++ b/mod/workshop/simpletest/testworkshopapi.php @@ -56,4 +56,34 @@ class workshop_internal_api_test extends UnitTestCase { $this->workshop = null; } + public function test_percent_to_value() { + // fixture setup + $total = 185; + $percent = 56.6543; + // exercise SUT + $part = workshop::percent_to_value($percent, $total); + // verify + $this->assertEqual($part, $total * $percent / 100); + } + + public function test_percent_to_value_negative() { + // fixture setup + $total = 185; + $percent = -7.098; + // set expectation + $this->expectException('coding_exception'); + // exercise SUT + $part = workshop::percent_to_value($percent, $total); + } + + public function test_percent_to_value_over_hundred() { + // fixture setup + $total = 185; + $percent = 121.08; + // set expectation + $this->expectException('coding_exception'); + // exercise SUT + $part = workshop::percent_to_value($percent, $total); + } + }