Skip to content

Commit 7dfa9ee

Browse files
committed
test: _
1 parent 5e30c00 commit 7dfa9ee

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

tests/UnderscoreTest.php

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
<?php
2+
3+
namespace Ahc\Underscore\Tests;
4+
5+
use Ahc\Underscore\Underscore as _;
6+
7+
class UnderscoreTest extends \PHPUnit_Framework_TestCase
8+
{
9+
public function test_memoize()
10+
{
11+
$memoSum = _::_()->memoize(function ($a, $b) {
12+
echo "sum $a + $b";
13+
14+
return $a + $b;
15+
});
16+
17+
// Every time the sum callback is called it echoes something.
18+
// But since it is memorized, it should only echo in the first call.
19+
ob_start();
20+
21+
// Call 3 times!
22+
$this->assertSame(1 + 2, $memoSum(1, 2));
23+
$this->assertSame(1 + 2, $memoSum(1, 2));
24+
$this->assertSame(1 + 2, $memoSum(1, 2));
25+
26+
// Call twice for different args!
27+
$this->assertSame(3 + 2, $memoSum(3, 2));
28+
$this->assertSame(3 + 2, $memoSum(3, 2));
29+
30+
$buffer = ob_get_clean();
31+
32+
$this->assertSame(1, substr_count($buffer, 'sum 1 + 2'),
33+
'Should be called only once, subsequent calls uses memo'
34+
);
35+
$this->assertSame(1, substr_count($buffer, 'sum 3 + 2'),
36+
'Should be called only once, subsequent calls uses memo'
37+
);
38+
}
39+
40+
public function test_delay()
41+
{
42+
$callback = function () {
43+
// Do nothing!
44+
};
45+
46+
// Calibrate time taken by callback!
47+
$cTime = microtime(1);
48+
$callback();
49+
$cTime = microtime(1) - $cTime;
50+
51+
// Now delay this callback by 10millis (0.01sec).
52+
$delayCall = _::_()->delay($callback, 10);
53+
54+
$time = microtime(1);
55+
$delayCall();
56+
$time = microtime(1) - $time;
57+
58+
// The overall time must be >= (cTime + 1sec).
59+
$this->assertGreaterThanOrEqual(0.01 + $cTime, $time);
60+
}
61+
62+
public function test_throttle()
63+
{
64+
$callback = function () {
65+
echo 'throttle';
66+
};
67+
68+
// Throttle the call for once per 10millis (0.01 sec)
69+
// So that for a period of 300millis it should be actually called at most 3 times.
70+
$throtCall = _::_()->throttle($callback, 10);
71+
72+
ob_start();
73+
74+
$start = microtime(1);
75+
while (microtime(1) - $start <= 0.031) {
76+
$throtCall();
77+
}
78+
79+
$buffer = ob_get_clean();
80+
81+
$this->assertLessThanOrEqual(3, substr_count($buffer, 'throttle'),
82+
'Should be called only once, subsequent calls uses memo'
83+
);
84+
}
85+
}

0 commit comments

Comments
 (0)