This repository has been archived by the owner on Aug 20, 2018. It is now read-only.
/
TPresenter.php
409 lines (375 loc) · 13.6 KB
/
TPresenter.php
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
<?php
namespace Testbench;
use Tester\Assert;
use Tester\Dumper;
trait TPresenter
{
/** @var \Nette\Application\IPresenter */
private $__testbench_presenter;
private $__testbench_httpCode;
private $__testbench_exception;
private $__testbench_ajaxMode = FALSE;
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param array $params provided to the presenter usually via URL
* @param array $post provided to the presenter via POST
*
* @return \Nette\Application\IResponse
* @throws \Exception
*/
protected function check($destination, $params = [], $post = [])
{
$destination = ltrim($destination, ':');
$pos = strrpos($destination, ':');
$presenter = substr($destination, 0, $pos);
$action = substr($destination, $pos + 1) ?: 'default';
$container = \Testbench\ContainerFactory::create(FALSE);
$container->removeService('httpRequest');
$headers = $this->__testbench_ajaxMode ? ['X-Requested-With' => 'XMLHttpRequest'] : [];
$url = new \Nette\Http\UrlScript($container->parameters['testbench']['url']);
$container->addService('httpRequest', new Mocks\HttpRequestMock($url, $params, $post, [], [], $headers));
$presenterFactory = $container->getByType('Nette\Application\IPresenterFactory');
$this->__testbench_presenter = $presenterFactory->createPresenter($presenter);
$this->__testbench_presenter->autoCanonicalize = FALSE;
$this->__testbench_presenter->invalidLinkMode = \Nette\Application\UI\Presenter::INVALID_LINK_EXCEPTION;
$postCopy = $post;
if (isset($params['do'])) {
foreach ($post as $key => $field) {
if (is_array($field) && array_key_exists(\Nette\Forms\Form::REQUIRED, $field)) {
$post[$key] = $field[0];
}
}
}
/** @var \Kdyby\FakeSession\Session $session */
$session = $this->__testbench_presenter->getSession();
$session->setFakeId('testbench.fakeId');
$session->getSection('Nette\Forms\Controls\CsrfProtection')->token = 'testbench.fakeToken';
$post = $post + ['_token_' => 'goVdCQ1jk0UQuVArz15RzkW6vpDU9YqTRILjE=']; //CSRF magic! ¯\_(ツ)_/¯
$request = new Mocks\ApplicationRequestMock(
$presenter,
$post ? 'POST' : 'GET',
['action' => $action] + $params,
$post
);
try {
$this->__testbench_httpCode = 200;
$this->__testbench_exception = NULL;
$response = $this->__testbench_presenter->run($request);
if (isset($params['do'])) {
if (preg_match('~(.+)-submit$~', $params['do'], $matches)) {
/** @var \Nette\Application\UI\Form $form */
$form = $this->__testbench_presenter->getComponent($matches[1]);
foreach ($form->getControls() as $control) {
if (array_key_exists($control->getName(), $postCopy)) {
$subvalues = $postCopy[$control->getName()];
$rq = \Nette\Forms\Form::REQUIRED;
if (is_array($subvalues) && array_key_exists($rq, $subvalues) && $subvalues[$rq]) {
if ($control->isRequired() !== TRUE) {
Assert::fail("field '{$control->name}' should be defined as required, but it's not");
}
}
}
if ($control->hasErrors()) {
$errors = '';
$counter = 1;
foreach ($control->getErrors() as $error) {
$errors .= " - $error\n";
$counter++;
}
Assert::fail("field '{$control->name}' returned this error(s):\n$errors");
}
}
foreach ($form->getErrors() as $error) {
Assert::fail($error);
}
}
}
return $response;
} catch (\Exception $exc) {
$this->__testbench_exception = $exc;
$this->__testbench_httpCode = $exc->getCode();
throw $exc;
}
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param array $params provided to the presenter usually via URL
* @param array $post provided to the presenter via POST
*
* @return \Nette\Application\Responses\TextResponse
* @throws \Exception
*/
protected function checkAction($destination, $params = [], $post = [])
{
/** @var \Nette\Application\Responses\TextResponse $response */
$response = $this->check($destination, $params, $post);
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\TextResponse', $response);
Assert::type('Nette\Application\UI\ITemplate', $response->getSource());
$html = (string)$response->getSource();
//DOMDocument doesn't handle HTML tags inside of script tags very well
$html = preg_replace('~<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>~', '', $html); //http://stackoverflow.com/a/6660315/3135248
$dom = @\Tester\DomQuery::fromHtml($html);
Assert::true($dom->has('html'), "missing 'html' tag");
Assert::true($dom->has('title'), "missing 'title' tag");
Assert::true($dom->has('body'), "missing 'body' tag");
}
return $response;
}
/**
* @param string $destination
* @param string $signal
* @param array $params
* @param array $post
*
* @return \Nette\Application\IResponse
*/
protected function checkSignal($destination, $signal, $params = [], $post = [])
{
return $this->checkRedirect($destination, FALSE, [
'do' => $signal,
] + $params, $post);
}
protected function checkAjaxSignal($destination, $signal, $params = [], $post = [])
{
$this->__testbench_ajaxMode = TRUE;
$response = $this->check($destination, [
'do' => $signal,
] + $params, $post);
Assert::true($this->__testbench_presenter->isAjax());
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\JsonResponse', $response);
}
$this->__testbench_ajaxMode = FALSE;
return $response;
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param string $path
* @param array $params provided to the presenter usually via URL
* @param array $post provided to the presenter via POST
*
* @return \Nette\Application\Responses\RedirectResponse
* @throws \Exception
*/
protected function checkRedirect($destination, $path = '/', $params = [], $post = [])
{
/** @var \Nette\Application\Responses\RedirectResponse $response */
$response = $this->check($destination, $params, $post);
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\RedirectResponse', $response);
Assert::same(302, $response->getCode());
if ($path) {
if (!\Tester\Assert::isMatching("~^https?://test\.bench{$path}(?(?=\?).+)$~", $response->getUrl())) {
$path = Dumper::color('yellow') . Dumper::toLine($path) . Dumper::color('white');
$url = Dumper::color('yellow') . Dumper::toLine($response->getUrl()) . Dumper::color('white');
$originalUrl = new \Nette\Http\Url($response->getUrl());
Assert::fail(
str_repeat(' ', strlen($originalUrl->getHostUrl()) - 13) // strlen('Failed: path ') = 13
. "path $path doesn't match\n$url\nafter redirect"
);
}
}
}
return $response;
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param array $params provided to the presenter usually via URL
* @param array $post provided to the presenter via POST
*
* @return \Nette\Application\Responses\JsonResponse
* @throws \Exception
*/
protected function checkJson($destination, $params = [], $post = [])
{
/** @var \Nette\Application\Responses\JsonResponse $response */
$response = $this->check($destination, $params, $post);
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\JsonResponse', $response);
Assert::same('application/json', $response->getContentType());
}
return $response;
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param array $scheme what is expected
* @param array $params provided to the presenter usually via URL
* @param array $post provided to the presenter via POST
*/
public function checkJsonScheme($destination, array $scheme, $params = [], $post = [])
{
$response = $this->checkJson($destination, $params, $post);
Assert::same($scheme, $response->getPayload());
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param string $formName
* @param array $post provided to the presenter via POST
* @param string|boolean $path Path after redirect or FALSE if it's form without redirect
*
* @return \Nette\Application\Responses\RedirectResponse
* @throws \Tester\AssertException
*/
protected function checkForm($destination, $formName, $post = [], $path = '/')
{
if (is_string($path)) {
return $this->checkRedirect($destination, $path, [
'do' => $formName . '-submit',
], $post);
} elseif (is_bool($path)) {
/** @var \Nette\Application\Responses\RedirectResponse $response */
$response = $this->check($destination, [
'do' => $formName . '-submit',
], $post);
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\TextResponse', $response);
}
return $response;
} else {
\Tester\Assert::fail('Path should be string or boolean (probably FALSE).');
}
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param $formName
* @param array $post provided to the presenter via POST
* @param string|bool $path
*
* @return \Nette\Application\IResponse
* @throws \Exception
*/
protected function checkAjaxForm($destination, $formName, $post = [], $path = FALSE)
{
if (is_string($path)) {
$this->checkForm($destination, $formName, $post, $path);
Assert::false($this->__testbench_presenter->isAjax());
}
$this->__testbench_presenter = NULL; //FIXME: not very nice, but performance first
$this->__testbench_ajaxMode = TRUE;
$response = $this->check($destination, [
'do' => $formName . '-submit',
], $post);
Assert::true($this->__testbench_presenter->isAjax());
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\JsonResponse', $response);
}
$this->__testbench_presenter = NULL;
$this->__testbench_ajaxMode = FALSE;
return $response;
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param array $params provided to the presenter usually via URL
* @param array $post provided to the presenter via POST
*
* @return \Nette\Application\Responses\TextResponse
* @throws \Exception
*/
protected function checkRss($destination, $params = [], $post = [])
{
/** @var \Nette\Application\Responses\TextResponse $response */
$response = $this->check($destination, $params, $post);
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\TextResponse', $response);
Assert::type('Nette\Application\UI\ITemplate', $response->getSource());
$dom = \Tester\DomQuery::fromXml($response->getSource());
Assert::true($dom->has('rss'), "missing 'rss' element");
Assert::true($dom->has('channel'), "missing 'channel' element");
Assert::true($dom->has('title'), "missing 'title' element");
Assert::true($dom->has('link'), "missing 'link' element");
Assert::true($dom->has('item'), "missing 'item' element");
}
return $response;
}
/**
* @param string $destination fully qualified presenter name (module:module:presenter)
* @param array $params provided to the presenter usually via URL
* @param array $post provided to the presenter via POST
*
* @return \Nette\Application\Responses\TextResponse
* @throws \Exception
*/
protected function checkSitemap($destination, $params = [], $post = [])
{
/** @var \Nette\Application\Responses\TextResponse $response */
$response = $this->check($destination, $params, $post);
if (!$this->__testbench_exception) {
Assert::same(200, $this->getReturnCode());
Assert::type('Nette\Application\Responses\TextResponse', $response);
Assert::type('Nette\Application\UI\ITemplate', $response->getSource());
$xml = \Tester\DomQuery::fromXml($response->getSource());
Assert::same('urlset', $xml->getName(), 'root element is');
$url = $xml->children();
Assert::same('url', $url->getName(), "child of 'urlset'");
Assert::same('loc', $url->children()->getName(), "child of 'url'");
}
return $response;
}
/**
* @param \Nette\Security\IIdentity|integer $id
* @param array|null $roles
* @param array|null $data
*
* @return \Nette\Security\User
*/
protected function logIn($id = 1, $roles = NULL, $data = NULL)
{
if ($id instanceof \Nette\Security\IIdentity) {
$identity = $id;
} else {
$identity = new \Nette\Security\Identity($id, $roles, $data);
}
/** @var \Nette\Security\User $user */
$user = \Testbench\ContainerFactory::create(FALSE)->getByType('Nette\Security\User');
$user->login($identity);
return $user;
}
/**
* @return \Nette\Security\User
*/
protected function logOut()
{
/** @var \Nette\Security\User $user */
$user = \Testbench\ContainerFactory::create(FALSE)->getByType('Nette\Security\User');
$user->logout();
return $user;
}
/**
* @return bool
*/
protected function isUserLoggedIn()
{
/** @var \Nette\Security\User $user */
$user = \Testbench\ContainerFactory::create(FALSE)->getByType('Nette\Security\User');
return $user->isLoggedIn();
}
/**
* @return \Nette\Application\UI\Presenter
*/
protected function getPresenter()
{
return $this->__testbench_presenter;
}
/**
* @return integer
*/
protected function getReturnCode()
{
return $this->__testbench_httpCode;
}
/**
* @return \Exception
*/
protected function getException()
{
return $this->__testbench_exception;
}
}