File: sum.phpt

package info (click to toggle)
php-decimal 1.5.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 456 kB
  • sloc: ansic: 1,928; xml: 102; makefile: 2
file content (78 lines) | stat: -rw-r--r-- 2,111 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
--TEST--
Decimal::sum
--SKIPIF--
<?php
if (!extension_loaded("decimal") || PHP_VERSION_ID < 80000) echo "skip";
?>
--FILE--
<?php
use Decimal\Decimal;

/**
 * Shortcut to construct a new decimal.
 */
function decimal(...$args) { return new Decimal(...$args); }

/**
 * Proxy iterator.
 */
function iterator(...$values) { yield from $values; }

/**
 * (values [, prec]), Expected Result, Expected Precision
 */
$tests = [
    [[[],   ], "0", 28],
    [[[], 30], "0", 30],

    [[[1, 2, 3],   ], "6", 28],
    [[[1, 2, 3], 10], "6", 10],

    [[array(decimal("0.1", 4), decimal("0.2", 5), decimal("0.3", 6)),  ], "0.6", 28],
    [[array(decimal("0.1", 4), decimal("0.2", 5), decimal("0.3", 6)), 4], "0.6",  6],
    [[array(decimal("0.1", 4), decimal("0.2", 5), "0.3"),              ], "0.6", 28],

    [[iterator(decimal("0.1", 4), decimal("0.2", 5), decimal("0.3", 6)),  ], "0.6", 28],
    [[iterator(decimal("0.1", 4), decimal("0.2", 5), decimal("0.3", 6)), 4], "0.6",  6],
    [[iterator(decimal("0.1", 4), decimal("0.2", 5), "0.3"),              ], "0.6", 28],

    [[array('-2.3', '4.1'),   ], "1.8", 28],
    [[array('-2.3', '4.1'), 10], "1.8", 10],
    [[array('-2.3', '4.1'), 30], "1.8", 30],
];

foreach ($tests as $index => $test) {
    list($args, $expect, $precision) = $test;

    $result = Decimal::sum(...$args);

    if ([(string) $result, $result->precision()] !== [$expect, $precision]) {
        print_r(compact("index", "args", "result", "expect", "precision"));
    }
}

/* Test non-traversable */
try {
    Decimal::sum("abc");
} catch (TypeError $e) {
    printf("%s\n", $e->getMessage());
}

/* Test non-integer precision */
try {
    Decimal::sum([], 'a');
} catch (TypeError $e) {
    printf("%s\n", $e->getMessage());
}

/* Test bad types */
try {
    Decimal::sum([1, 2, "abc"]);
} catch (DomainException $e) {
    printf("%s\n", $e->getMessage());
}
?>
--EXPECTF--
Decimal\Decimal::sum() expected parameter 1 to be an array or traversable object, string given
Decimal\Decimal::sum(): Argument #2 ($precision) must be of type int, string given
Failed to parse string as decimal: "abc"