format: fix render_bytes with CLIFormatter
[pve-common.git] / test / convert_size_test.pl
1 #!/usr/bin/perl
2
3 use lib '../src';
4 use strict;
5 use warnings;
6 use Data::Dumper;
7 use Test::More;
8
9 use PVE::Tools;
10
11 my $tests = [
12 [
13 1, # input value
14 'gb', # from
15 'kb', # to
16 undef, # no_round_up
17 1*1024*1024, # result
18 undef, # error string
19 ],
20 [ -1, 'gb', 'kb', undef, 1*1024*1024, "value '-1' is not a valid, positive number" ],
21 [ 1.5, 'gb', 'kb', undef, 1.5*1024*1024 ],
22 [ 0.0005, 'gb', 'mb', undef, 1 ],
23 [ 0.0005, 'gb', 'mb', 1, 0 ],
24 [ '.5', 'gb', 'kb', undef, .5*1024*1024 ],
25 [ '1.', 'gb', 'kb', undef, 1.*1024*1024 ],
26 [ 0.5, 'mb', 'gb', undef, 1, ],
27 [ 0.5, 'mb', 'gb', 1, 0, ],
28 [ '.', 'gb', 'kb', undef, 0, "value '.' is not a valid, positive number" ],
29 [ '', 'gb', 'kb', undef, 0, "no value given" ],
30 [ '1.1.', 'gb', 'kb', undef, 0, "value '1.1.' is not a valid, positive number" ],
31 [ 500, 'kb', 'kb', undef, 500, ],
32 [ 500000, 'b', 'kb', undef, 489, ],
33 [ 500000, 'b', 'kb', 0, 489, ],
34 [ 500000, 'b', 'kb', 1, 488, ],
35 [ 128*1024 - 1, 'b', 'kb', 0, 128, ],
36 [ 128*1024 - 1, 'b', 'kb', 1, 127, ],
37 [ "abcdef", 'b', 'kb', 0, 0, "value 'abcdef' is not a valid, positive number" ],
38 [ undef, 'b', 'kb', 0, 0, "no value given" ],
39 [ 0, 'b', 'pb', 0, 0, ],
40 [ 0, 'b', 'yb', 0, 0, "unknown 'from' and/or 'to' units (b => yb)"],
41 [ 0, 'b', undef, 0, 0, "unknown 'from' and/or 'to' units (b => )"],
42 ];
43
44 foreach my $test (@$tests) {
45 my ($input, $from, $to, $no_round_up, $expect, $error) = @$test;
46
47 my $result = eval { PVE::Tools::convert_size($input, $from, $to, $no_round_up); };
48 my $err = $@;
49 $input = $input // "";
50 $from = $from // "";
51 $to = $to // "";
52 if ($error) {
53 like($err, qr/^\Q$error\E/, "expected error for $input $from -> $to: $error");
54 } else {
55 my $round = $no_round_up ? 'floor' : 'ceil';
56 is($result, $expect, "$input $from converts to $expect $to ($round)");
57 }
58 };
59
60 done_testing();