| 1 | <?php |
| 2 | |
| 3 | namespace Liuch\DmarcSrg; |
| 4 | |
| 5 | use Liuch\DmarcSrg\Users\DbUser; |
| 6 | use Liuch\DmarcSrg\Users\UserList; |
| 7 | use Liuch\DmarcSrg\Users\AdminUser; |
| 8 | use Liuch\DmarcSrg\Exception\SoftException; |
| 9 | use Liuch\DmarcSrg\Database\DatabaseController; |
| 10 | use Liuch\DmarcSrg\Database\UserMapperInterface; |
| 11 | |
| 12 | class UserListTest extends \PHPUnit\Framework\TestCase |
| 13 | { |
| 14 | public function testGetList(): void |
| 15 | { |
| 16 | $res = (new UserList($this->getDatabaseMapperOnce( |
| 17 | 'list', |
| 18 | [ |
| 19 | [ 'id' => 1, 'name' => 'user1' ], |
| 20 | [ 'id' => 2, 'name' => 'user2' ] |
| 21 | ] |
| 22 | )))->getList(); |
| 23 | $this->assertIsArray($res); |
| 24 | $this->assertArrayHasKey('more', $res); |
| 25 | $this->assertArrayHasKey('users', $res); |
| 26 | $this->assertIsBool($res['more']); |
| 27 | $this->assertIsArray($res['users']); |
| 28 | $this->assertCount(2, $res['users']); |
| 29 | $idx = 1; |
| 30 | foreach ($res['users'] as $user) { |
| 31 | $this->assertInstanceOf(DbUser::class, $user); |
| 32 | $this->assertSame($idx, $user->id()); |
| 33 | $this->assertSame("user{$idx}", $user->name()); |
| 34 | ++$idx; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | public function testGetUserByName(): void |
| 39 | { |
| 40 | $this->assertInstanceOf( |
| 41 | AdminUser::class, |
| 42 | UserList::getUserByName('admin', $this->getCore()) |
| 43 | ); |
| 44 | $this->assertInstanceOf( |
| 45 | DbUser::class, |
| 46 | UserList::getUserByName('user1', $this->getCoreWithDatabaseMapperOnce('exists', true)) |
| 47 | ); |
| 48 | $this->expectException(SoftException::class); |
| 49 | UserList::getUserByName('unknown', $this->getCoreWithDatabaseMapperOnce('exists', false)); |
| 50 | } |
| 51 | |
| 52 | private function getCore(): object |
| 53 | { |
| 54 | return $this->getMockBuilder(Core::class)->disableOriginalConstructor()->getMock(); |
| 55 | } |
| 56 | |
| 57 | private function getDatabaseMapperOnce(string $method, $value): object |
| 58 | { |
| 59 | $mapper = $this->getMockBuilder(UserMapperInterface::class) |
| 60 | ->disableOriginalConstructor() |
| 61 | ->getMock(); |
| 62 | $mapper->expects($this->once()) |
| 63 | ->method($method) |
| 64 | ->willReturn($value); |
| 65 | |
| 66 | $db = $this->getMockBuilder(DatabaseController::class) |
| 67 | ->disableOriginalConstructor() |
| 68 | ->onlyMethods([ 'getMapper' ]) |
| 69 | ->getMock(); |
| 70 | $db->expects($this->once()) |
| 71 | ->method('getMapper') |
| 72 | ->with('user') |
| 73 | ->willReturn($mapper); |
| 74 | return $db; |
| 75 | } |
| 76 | |
| 77 | private function getCoreWithDatabaseMapperOnce(string $method, $value): object |
| 78 | { |
| 79 | $db = $this->getDatabaseMapperOnce($method, $value); |
| 80 | $core = $this->getCore(); |
| 81 | $core->expects($this->once()) |
| 82 | ->method('database') |
| 83 | ->willReturn($db); |
| 84 | return $core; |
| 85 | } |
| 86 | } |