058846acac7edb0a65b39143c4d31186ded7c450
[yaffs-website] / web / core / modules / ban / tests / src / Unit / BanMiddlewareTest.php
1 <?php
2
3 namespace Drupal\Tests\ban\Unit;
4
5 use Drupal\ban\BanMiddleware;
6 use Drupal\Tests\UnitTestCase;
7 use Symfony\Component\HttpFoundation\Request;
8 use Symfony\Component\HttpFoundation\Response;
9 use Symfony\Component\HttpKernel\HttpKernelInterface;
10
11 /**
12  * @coversDefaultClass \Drupal\ban\BanMiddleware
13  * @group ban
14  */
15 class BanMiddlewareTest extends UnitTestCase {
16
17   /**
18    * The mocked wrapped kernel.
19    *
20    * @var \Symfony\Component\HttpKernel\HttpKernelInterface|\PHPUnit_Framework_MockObject_MockObject
21    */
22   protected $kernel;
23
24   /**
25    * The mocked ban IP manager.
26    *
27    * @var \Drupal\ban\BanIpManagerInterface|\PHPUnit_Framework_MockObject_MockObject
28    */
29   protected $banManager;
30
31   /**
32    * The tested ban middleware.
33    *
34    * @var \Drupal\ban\BanMiddleware
35    */
36   protected $banMiddleware;
37
38   /**
39    * {@inheritdoc}
40    */
41   protected function setUp() {
42     parent::setUp();
43
44     $this->kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
45     $this->banManager = $this->getMock('Drupal\ban\BanIpManagerInterface');
46     $this->banMiddleware = new BanMiddleware($this->kernel, $this->banManager);
47   }
48
49   /**
50    * Tests a banned IP.
51    */
52   public function testBannedIp() {
53     $banned_ip = '17.0.0.2';
54     $this->banManager->expects($this->once())
55       ->method('isBanned')
56       ->with($banned_ip)
57       ->willReturn(TRUE);
58
59     $this->kernel->expects($this->never())
60       ->method('handle');
61
62     $request = Request::create('/test-path');
63     $request->server->set('REMOTE_ADDR', $banned_ip);
64     $response = $this->banMiddleware->handle($request);
65
66     $this->assertEquals(403, $response->getStatusCode());
67   }
68
69   /**
70    * Tests an unbanned IP.
71    */
72   public function testUnbannedIp() {
73     $unbanned_ip = '18.0.0.2';
74     $this->banManager->expects($this->once())
75       ->method('isBanned')
76       ->with($unbanned_ip)
77       ->willReturn(FALSE);
78
79     $request = Request::create('/test-path');
80     $request->server->set('REMOTE_ADDR', $unbanned_ip);
81     $expected_response = new Response(200);
82     $this->kernel->expects($this->once())
83       ->method('handle')
84       ->with($request, HttpKernelInterface::MASTER_REQUEST, TRUE)
85       ->willReturn($expected_response);
86
87     $response = $this->banMiddleware->handle($request);
88
89     $this->assertSame($expected_response, $response);
90   }
91
92 }