HttpClientCacheTest.php
67 lines
| 1 | <?php |
| 2 | /** |
| 3 | * HttpClientCacheTest.php |
| 4 | * |
| 5 | * @package Tests |
| 6 | * @author Michael Pratt <yo@michael-pratt.com> |
| 7 | * @link http://www.michael-pratt.com/ |
| 8 | * |
| 9 | * For the full copyright and license information, please view the LICENSE |
| 10 | * file that was distributed with this source code. |
| 11 | */ |
| 12 | namespace Embera\Http; |
| 13 | |
| 14 | use PHPUnit\Framework\TestCase; |
| 15 | use Embera\Cache\Filesystem; |
| 16 | |
| 17 | class HttpClientCacheTest extends TestCase |
| 18 | { |
| 19 | public function testHttpRequestHit() |
| 20 | { |
| 21 | $cache = new Filesystem(sys_get_temp_dir(), mt_rand(1, 5)); |
| 22 | $cache->clear(); |
| 23 | |
| 24 | $params = []; |
| 25 | $url = 'https://httpbin.org/user-agent'; |
| 26 | $ua = 'PHP/Embera Test - ' . date('Y-m-d'); |
| 27 | $key = md5(serialize([ 'url' => $url, 'params' => $params ])); |
| 28 | |
| 29 | $httpCache = new HttpClientCache(new HttpClient()); |
| 30 | $httpCache->setconfig([ |
| 31 | 'use_curl' => true, |
| 32 | 'user_agent' => $ua, |
| 33 | ]); |
| 34 | |
| 35 | $httpCache->setCachingEngine($cache); |
| 36 | |
| 37 | $response = $httpCache->fetch($url); |
| 38 | $responseJson = json_decode($response, true); |
| 39 | $this->assertEquals($ua, $responseJson['user-agent']); |
| 40 | |
| 41 | $this->assertTrue($cache->has($key)); |
| 42 | $this->assertEquals($cache->get($key), $response); |
| 43 | |
| 44 | // Use Cache |
| 45 | $response = $httpCache->fetch($url); |
| 46 | $this->assertTrue($cache->has($key)); |
| 47 | $this->assertEquals($cache->get($key), $response); |
| 48 | $this->assertTrue($cache->delete($key)); |
| 49 | } |
| 50 | |
| 51 | public function testHttpRequestFailed() |
| 52 | { |
| 53 | $cache = new Filesystem(sys_get_temp_dir(), mt_rand(1, 5)); |
| 54 | $cache->clear(); |
| 55 | |
| 56 | $httpClientStub = $this->createMock(HttpClient::class); |
| 57 | $httpClientStub->method('fetch')->willReturn(false); |
| 58 | |
| 59 | $httpCache = new HttpClientCache($httpClientStub); |
| 60 | $httpCache->setCachingEngine($cache); |
| 61 | |
| 62 | $response = $httpCache->fetch('http://host.com/test'); |
| 63 | $this->assertFalse($response); |
| 64 | } |
| 65 | |
| 66 | } |
| 67 |