nur-ture/tests/wip/php/coll/CursorTest.php

113 lines
2.9 KiB
PHP

<?php
namespace nur\sery\wip\php\coll;
use Exception;
use nulib\cl;
use nulib\output\msg;
use nulib\output\std\StdMessenger;
use nulib\tests\TestCase;
use TypeError;
class CursorTest extends TestCase {
protected function setUp(): void {
msg::set_messenger(new StdMessenger());
}
const SCALARS = [0, 1, 2, 3, 4];
function generator() {
yield from self::SCALARS;
}
function testVanilla() {
$c = new Cursor(self::SCALARS);
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
$c = new Cursor($this->generator());
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
self::assertException(Exception::class, function() use ($c) {
// pas possible de rewind un générateur
return cl::all($c);
});
$c = new Cursor(null, [
"rows" => function() {
return self::SCALARS;
},
]);
self::assertError(TypeError::class, function() use ($c) {
// rows doit être un iterable, pas une fonction
return cl::all($c);
});
$c = new Cursor(null, [
"rows_func" => function() {
return self::SCALARS;
},
]);
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
$c = new Cursor(null, [
"rows_func" => $this->generator(),
]);
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
self::assertException(Exception::class, function() use ($c) {
// pas possible de rewind un générateur
return cl::all($c);
});
$c = new Cursor(null, [
"rows_func" => function() {
yield from self::SCALARS;
},
]);
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
self::assertSame([[0], [1], [2], [3], [4]], cl::all($c));
}
function testMap() {
$c = new Cursor(self::SCALARS, [
"map_func" => function(Cursor $c) {
return [$c->raw + 1];
},
]);
self::assertSame([[1], [2], [3], [4], [5]], cl::all($c));
}
function testFilter() {
$c = new Cursor(self::SCALARS, [
"filter_func" => function(Cursor $c) {
return $c->raw % 2 == 0;
},
]);
self::assertSame([[1], [3]], cl::all($c));
}
function testEach() {
$c = new Cursor(self::SCALARS, [
"filter_func" => function(Cursor $c) {
return $c->raw % 2 == 0;
},
"map_func" => function(Cursor $c) {
return [$c->raw + 1];
},
]);
$xs = [];
$xitems = [];
$oxs = [];
$kitems = [];
$c->each(function(Cursor $c) use (&$xs, &$xitems, &$oxs, &$kitems) {
$xs[] = $c->index;
$oxs[] = $c->origIndex;
$xitems[$c->index] = $c->row[0];
$kitems[$c->key] = $c->row[0];
});
self::assertSame([0, 1], $xs);
self::assertSame([2, 4], $xitems);
self::assertSame([1, 3], $oxs);
self::assertSame([1 => 2, 3 => 4], $kitems);
}
}