Commit | Line | Data |
---|---|---|
ac5f2ccd TO |
1 | <?php |
2 | require_once 'CiviTest/CiviUnitTestCase.php'; | |
aba1cd8b EM |
3 | |
4 | /** | |
5 | * Class CRM_Utils_NumberTest | |
6 | */ | |
ac5f2ccd TO |
7 | class CRM_Utils_NumberTest extends CiviUnitTestCase { |
8 | ||
aba1cd8b EM |
9 | /** |
10 | * @return array | |
11 | */ | |
ac5f2ccd TO |
12 | function randomDecimalCases() { |
13 | $cases = array(); | |
14 | // array(array $precision, int $expectedMinInclusive, int $expectedMaxExclusive) | |
15 | $cases[] = array(array(1, 0), 0, 10); | |
16 | $cases[] = array(array(5, 2), 0, 1000); | |
17 | $cases[] = array(array(10, 8), 0, 100); | |
18 | return $cases; | |
19 | } | |
20 | ||
21 | /** | |
22 | * @param array $precision | |
23 | * @param int $expectedMinInclusive | |
24 | * @param int $expectedMaxExclusive | |
25 | * @dataProvider randomDecimalCases | |
26 | */ | |
27 | function testCreateRandomDecimal($precision, $expectedMinInclusive, $expectedMaxExclusive) { | |
28 | list ($sigFigs, $decFigs) = $precision; | |
29 | for ($i = 0; $i < 10; $i++) { | |
30 | $decimal = CRM_Utils_Number::createRandomDecimal($precision); | |
31 | // print "Assert $decimal between $expectedMinInclusive and $expectedMaxExclusive\n"; | |
32 | $this->assertTrue(($expectedMinInclusive <= $decimal) && ($decimal < $expectedMaxExclusive), "Assert $decimal between $expectedMinInclusive and $expectedMaxExclusive"); | |
33 | if (strpos($decimal, '.') === FALSE) { | |
34 | $decimal .= '.'; | |
35 | } | |
36 | list ($before, $after) = explode('.', $decimal); | |
37 | $this->assertTrue(strlen($before) + strlen($after) <= $sigFigs, "Assert $decimal [$before;$after] has <= $sigFigs sigFigs"); | |
38 | $this->assertTrue(strlen($after) <= $decFigs, "Assert $decimal [$before;$after] has <= $decFigs decFigs"); | |
39 | } | |
40 | } | |
41 | ||
4cbe18b8 EM |
42 | /** |
43 | * @return array | |
44 | */ | |
ac5f2ccd TO |
45 | function truncDecimalCases() { |
46 | $cases = array(); | |
47 | // array($value, $precision, $expectedValue) | |
48 | $cases[] = array(523, array(1,0), 5); | |
49 | $cases[] = array(523, array(5,2), 523); | |
50 | $cases[] = array(523, array(10,8), 52.3); | |
51 | $cases[] = array(12345, array(3,3), 0.123); | |
52 | $cases[] = array(0.12345, array(10,0), 12345); | |
53 | $cases[] = array(-123.45, array(4,2), -12.34); | |
54 | return $cases; | |
55 | } | |
56 | ||
57 | /** | |
58 | * @param $value | |
59 | * @param $precision | |
60 | * @param $expectedValue | |
61 | * @dataProvider truncDecimalCases | |
62 | */ | |
63 | function testCreateTruncatedDecimal($value, $precision, $expectedValue) { | |
64 | list ($sigFigs, $decFigs) = $precision; | |
65 | $this->assertEquals($expectedValue, CRM_Utils_Number::createTruncatedDecimal($value, $precision), | |
66 | "assert createTruncatedValue($value, ($sigFigs,$decFigs)) == $expectedValue" | |
67 | ); | |
68 | } | |
4cbe18b8 | 69 | } |