]> git.mjollnir.org Git - moodle.git/commitdiff
Adding percent_to_value() helper + its unittests
authorDavid Mudrak <david.mudrak@gmail.com>
Mon, 4 Jan 2010 18:10:18 +0000 (18:10 +0000)
committerDavid Mudrak <david.mudrak@gmail.com>
Mon, 4 Jan 2010 18:10:18 +0000 (18:10 +0000)
mod/workshop/locallib.php
mod/workshop/simpletest/testworkshopapi.php

index 8ec9d595ed48a30a4f787918e85ea8c094864cc7..08e6fbdc5dc66807a19f242f2b38818ad81038c3 100644 (file)
@@ -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                                                               //
     ////////////////////////////////////////////////////////////////////////////////
index a85100fc914a73fdcba20f13d73f9c72fe6a2997..b165485daf73af3627f4ad683ba5606b7fa4d502 100644 (file)
@@ -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);
+    }
+
 }