summaryrefslogtreecommitdiffstats
path: root/tests/ControllerTest.php
blob: 625fa30b2b19e0e13bc98a0b89de90dd21344a40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php

use Jasny\Controller;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

class ControllerTest extends PHPUnit_Framework_TestCase
{
    /**
     * Test running controller
     */
    public function testInvoke()
    {
        $controller = $this->getController();
        list($request, $response) = $this->getRequests();

        $controller->expects($this->once())->method('run')->will($this->returnValue($response));

        $result = $controller($request, $response);

        $this->assertEquals($response, $result, "Invoking controller should return 'ResponseInterface' instance");
        $this->assertEquals($response, $controller->getResponse(), "Can not get 'ResponseInterface' instance from controller");
        $this->assertEquals($request, $controller->getRequest(), "Can not get 'ServerRequestInterface' instance from controller");
    }

    /**
     * Test response status functions if response object is not set
     */
    public function testResponseStatusEmptyResponse()
    {
        $controller = $this->getController();   
        $data = $this->getStatusCodesMap(null);

        foreach ($data as $func => $value) {
            $this->assertEquals($value, $controller->$func(), "Method '$func' returns incorrect value");
        }
    }

    /**
     * Test functions that check response status code
     *
     * @dataProvider responseStatusProvider
     * @param int $statusCode
     */
    public function testResponseStatus($code)
    {
        $controller = $this->getController();
        list($request, $response) = $this->getRequests();
        $response->method('getStatusCode')->will($this->returnValue($code));

        $controller($request, $response);                

        $data = $this->getStatusCodesMap($code);

        foreach ($data as $func => $value) {
            $this->assertEquals($value, $controller->$func(), "Method '$func' returns incorrect value");
        }

        $this->assertEquals($data['isClientError'] || $data['isServerError'], $controller->isError(), "Method 'isError' returns incorrect value");
    }

    /**
     * Provide data for testing status methods
     *
     * @return array
     */
    public function responseStatusProvider()
    {
        return [
            [null], [199],
            [200], [201], [299],
            [300], [304], [399],
            [400], [403], [499],
            [500], [503]
        ];
    }

    /**
     * Test encodeData method, positive tests
     *
     * @dataProvider encodeDataPositiveProvider
     * @param mixed $data
     * @param string $contentType 
     * @param string $type 
     * @param string $callback  Callback name for testing jsonp request
     */
    public function testEncodeDataPositive($data, $contentType, $type, $callback = '')
    {
        $controller = $this->getController(['getRequest', 'getResponse']);
        list($request, $response) = $this->getRequests();

        $response->method('getHeaderLine')->with($this->equalTo('Content-Type'))->will($this->returnValue($contentType));
        if ($type === 'jsonp') {
            $request->method('getQueryParams')->will($this->returnValue(['callback' => $callback]));
        }

        $controller->method('getRequest')->will($this->returnValue($request));
        $controller->method('getResponse')->will($this->returnValue($response));

        $result = $controller->encodeData($data);
        $expect = null;

        if ($type === 'json') {
            $expect = json_encode($data);
        } elseif ($type === 'jsonp') {
            $expect = $callback . '(' . json_encode($data) . ')';
        } else {
            $expect = $data->asXML();
        }

        $this->assertNotEmpty($result, "Result should not be empty");
        $this->assertEquals($expect, $result, "Data was not encoded correctly");
    }

    /**
     * Provide data for testing encodeData method
     *
     * @return array
     */
    public function encodeDataPositiveProvider()
    {
        $xml = simplexml_load_string(
            "<?xml version='1.0'?> 
             <document>
                 <tag1>Test tag</tag1>
                 <tag2>Test</tag2>
            </document>"
        );

        return [
            [['testKey' => 'testValue'], 'application/json', 'json'],
            [['testKey' => 'testValue'], 'application/json', 'jsonp', 'test_callback'],
            ['', 'application/json', 'json'],
            ['', 'application/json', 'jsonp', 'test_callback'],
            [$xml, 'text/xml', 'xml'],            
            [$xml, 'application/xml', 'xml']
        ];
    }

    /**
     * Test encodeData method, negative tests
     *
     * @dataProvider encodeDataNegativeProvider
     * @param mixed $data
     * @param string $contentType 
     * @param string $type 
     * @param string $callback  Callback name for testing jsonp request
     */
    public function testEncodeDataNegative($data, $contentType, $type, $callback = '', $exception = true)
    {
        $controller = $this->getController(['getRequest', 'getResponse']);
        list($request, $response) = $this->getRequests();

        $response->method('getHeaderLine')->with($this->equalTo('Content-Type'))->will($this->returnValue($contentType));
        if ($type === 'jsonp') {
            $request->method('getQueryParams')->will($this->returnValue(['callback' => $callback]));
        }

        $controller->method('getRequest')->will($this->returnValue($request));
        $controller->method('getResponse')->will($this->returnValue($response));

        if ($exception) $this->expectException(\RuntimeException::class);

        $result = $controller->encodeData($data);
        $expect = null;

        if ($type === 'json') {
            $expect = json_encode($data);
        } elseif ($type === 'jsonp') {
            $expect = $callback . '(' . json_encode($data) . ')';
        } else {
            $expect = $data->asXML();
        }

        $this->assertNotEquals($expect, $result, "Data should not be encoded correctly here");
    }

    /**
     * Provide data for testing encodeData method
     *
     * @return array
     */
    public function encodeDataNegativeProvider()
    {
        $xml = simplexml_load_string(
            "<?xml version='1.0'?> 
             <document>
                 <tag1>Test tag</tag1>
                 <tag2>Test</tag2>
            </document>"
        );

        return [
            [['testKey' => 'testValue'], '', 'json'],
            [['testKey' => 'testValue'], 'json', 'json'],
            [['testKey' => 'testValue'], 'application/json', 'jsonp', '', false],
            [['testKey' => 'testValue'], 'application/jsonp', 'jsonp', 'test_callback'],
            [$xml, '', 'xml'],            
            [$xml, 'xml', 'xml']
        ];
    }

    /**
     * Test encoding data when response is not set
     */
    public function testEncodeDataNoResponse()
    {
        $controller = $this->getController();
        
        $this->expectException(\RuntimeException::class);

        $result = $controller->encodeData(['test' => 'test']);
    }

    /**
     * Get mock for controller
     *
     * @param array $methods  Methods to mock
     * @return Controller
     */
    public function getController($methods = [])
    {
        $builder = $this->getMockBuilder(Controller::class)->disableOriginalConstructor();
        if ($methods) {
            $builder->setMethods($methods);
        }

        return $builder->getMockForAbstractClass();
    }

    /**
     * Get map of status codes to states
     *
     * @param int $code
     * @return []
     */
    public function getStatusCodesMap($code)
    {
        return [
            'isSuccessful' => !$code || ($code >= 200 && $code < 300),
            'isRedirection' => $code >= 300 && $code < 400,
            'isClientError' => $code >= 400 && $code < 500,
            'isServerError' => $code >= 500            
        ];
    }

    /**
     * Get request and response instances
     *
     * @return array
     */
    public function getRequests()
    {
        return [
            $this->createMock(ServerRequestInterface::class),
            $this->createMock(ResponseInterface::class)            
        ];
    }
}