67 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			67 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
| <?php
 | |
| namespace nulib\cache;
 | |
| 
 | |
| use nulib\db\Capacitor;
 | |
| use nulib\db\sqlite\Sqlite;
 | |
| use nulib\db\sqlite\SqliteStorage;
 | |
| use nulib\output\msg;
 | |
| use nulib\output\std\StdMessenger;
 | |
| use nulib\tests\TestCase;
 | |
| use Traversable;
 | |
| 
 | |
| class SourceTest extends TestCase {
 | |
|   static function setUpBeforeClass(): void {
 | |
|     msg::set_messenger_class(StdMessenger::class);
 | |
|   }
 | |
| 
 | |
|   /** @param Traversable|iterable $dest */
 | |
|   protected static function assertSource($dest): void {
 | |
|     self::assertSame([
 | |
|       ["pk" => 1, "s" => null, "i" => null, "b" => null],
 | |
|       ["pk" => 2, "s" => "false", "i" => 0, "b" => 0],
 | |
|       ["pk" => 3, "s" => "first", "i" => 1, "b" => 1],
 | |
|       ["pk" => 4, "s" => "second", "i" => 2, "b" => 1],
 | |
|     ], iterator_to_array($dest));
 | |
|   }
 | |
| 
 | |
|   function testDirect() {
 | |
|     $destStorage = new SqliteStorage(new Sqlite(__DIR__.'/dest.db'));
 | |
|     new Capacitor($destStorage, $dest = new CursorChannel("source"));
 | |
| 
 | |
|     $sourceDb = new SourceDb();
 | |
|     $dest->rechargeAll($sourceDb->all("select * from source"));
 | |
| 
 | |
|     $this->assertSource($dest);
 | |
|   }
 | |
| 
 | |
|   function testCache() {
 | |
|     $getSource = function() {
 | |
|       $db = new SourceDb();
 | |
|       msg::info("query source");
 | |
|       yield from $db->all("select * from source");
 | |
|     };
 | |
| 
 | |
|     $params = [
 | |
|       "duration" => 2,
 | |
|       "override_duration" => true,
 | |
|     ];
 | |
| 
 | |
|     msg::info("initial");
 | |
|     cache::nc();
 | |
|     $dest = cache::all("source", $getSource(), $params);
 | |
|     $this->assertSource($dest);
 | |
| 
 | |
|     msg::info("cached");
 | |
|     $dest = cache::all("source", $getSource(), $params);
 | |
|     $this->assertSource($dest);
 | |
| 
 | |
|     sleep(4);
 | |
|     msg::info("expired");
 | |
|     $dest = cache::all("source", $getSource(), $params);
 | |
|     $this->assertSource($dest);
 | |
| 
 | |
|     sleep(4);
 | |
|     msg::info("end");
 | |
|   }
 | |
| }
 |