test_router.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. require_once 'router.php';
  3. use webbasics\Router;
  4. use webbasics\RouteHandler;
  5. function test_handler_no_args() {
  6. return true;
  7. }
  8. function test_handler_arg(array $args) {
  9. return $args[0];
  10. }
  11. function test_handler_args(array $args) {
  12. list($arg0, $arg1) = $args;
  13. return $arg1 . $arg0;
  14. }
  15. class TestHandler implements RouteHandler {
  16. function handleRequest(array $data) {
  17. return $data[0];
  18. }
  19. }
  20. class InterfacelessHandler {
  21. function handleRequest(array $data) {}
  22. }
  23. class RouterTest extends PHPUnit_Framework_TestCase {
  24. function setUp() {
  25. $this->router = new Router(array(
  26. 'foo' => 'test_handler_no_args',
  27. '(ba[rz])' => 'test_handler_arg',
  28. '(ba[rz])(ba[rz])' => 'test_handler_args',
  29. ));
  30. }
  31. function testCallHandlerSuccess() {
  32. $this->assertEquals(true, $this->router->callHandler('foo'));
  33. $this->assertEquals('bar', $this->router->callHandler('bar'));
  34. $this->assertEquals('baz', $this->router->callHandler('baz'));
  35. $this->assertEquals('barbaz', $this->router->callHandler('bazbar'));
  36. }
  37. function testCallHandlerFailure() {
  38. $this->assertFalse($this->router->callHandler('barfoo'));
  39. }
  40. function testCallHandlerSkip() {
  41. $foo = 'foo';
  42. $bar = function() use (&$foo) { $foo = 'bar'; return false; };
  43. $baz = function() { return; };
  44. $router = new Router(array('.*' => $bar, 'baz' => $baz));
  45. $router->callHandler('baz');
  46. $this->assertEquals('bar', $foo);
  47. }
  48. function testAddRouteCallableSuccess() {
  49. $this->router->addRoute('(foobar)', 'test_handler_arg');
  50. $this->assertEquals('foobar', $this->router->callHandler('foobar'));
  51. }
  52. /**
  53. * @expectedException \InvalidArgumentException
  54. */
  55. function testAddRouteCallableFailure() {
  56. $this->router->addRoute('(foobar)', 'non_existing_function');
  57. }
  58. function testAddRouteHandlerSuccess() {
  59. $this->router->addRoute('(foobar)', 'TestHandler');
  60. $this->assertEquals('foobar', $this->router->callHandler('foobar'));
  61. }
  62. /**
  63. * @expectedException \InvalidArgumentException
  64. */
  65. function testAddRouteHandlerNoString() {
  66. $this->router->addRoute('(foobar)', new TestHandler);
  67. }
  68. /**
  69. * @expectedException \InvalidArgumentException
  70. */
  71. function testAddRouteHandlerNonExisting() {
  72. $this->router->addRoute('(foobar)', 'NonExistingHandler');
  73. }
  74. /**
  75. * @expectedException \InvalidArgumentException
  76. */
  77. function testAddRouteHandlerWithoutInterface() {
  78. $this->router->addRoute('(foobar)', 'InterfacelessHandler');
  79. }
  80. }
  81. ?>