forked from michalochman/SilverStripeExtension
-
Notifications
You must be signed in to change notification settings - Fork 30
/
SilverStripeContext.php
624 lines (557 loc) · 19.4 KB
/
SilverStripeContext.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<?php
namespace SilverStripe\BehatExtension\Context;
use Behat\Behat\Hook\Scope\AfterStepScope;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Mink\Element\NodeElement;
use Behat\Mink\Exception\ElementNotFoundException;
use Behat\Mink\Exception\UnsupportedDriverActionException;
use Behat\Mink\Selector\Xpath\Escaper;
use Behat\MinkExtension\Context\MinkContext;
use InvalidArgumentException;
use SilverStripe\BehatExtension\Utility\TestMailer;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Resettable;
use SilverStripe\MinkFacebookWebDriver\FacebookWebDriver;
use SilverStripe\ORM\DataObject;
use SilverStripe\TestSession\TestSessionEnvironment;
use Symfony\Component\CssSelector\Exception\SyntaxErrorException;
/**
* SilverStripeContext
*
* Generic context wrapper used as a base for Behat FeatureContext.
*
* The default context for each module should extend this and be named `FeatureContext`
* under the standard module namespace.
*
* @link http://behat.org/en/latest/user_guide/context.html
*/
abstract class SilverStripeContext extends MinkContext implements SilverStripeAwareContext
{
protected $databaseName;
/**
* @var array Partial string match for step names
* that are considered to trigger Ajax request in the CMS,
* and hence need special timeout handling.
* @see \SilverStripe\BehatExtension\Context\BasicContextAwareTrait->handleAjaxBeforeStep().
*/
protected $ajaxSteps;
/**
* @var Int Timeout in milliseconds, after which the interface assumes
* that an Ajax request has timed out, and continues with assertions.
*/
protected $ajaxTimeout;
/**
* @var String Relative URL to the SilverStripe admin interface.
*/
protected $adminUrl;
/**
* @var String Relative URL to the SilverStripe login form.
*/
protected $loginUrl;
/**
* @var String Relative path to a writeable folder where screenshots can be stored.
* If set to NULL, no screenshots will be stored.
*/
protected $screenshotPath;
/**
* @var TestSessionEnvironment
*/
protected $testSessionEnvironment;
protected $regionMap;
/**
* XPath escaper
*
* @var Escaper
*/
protected $xpathEscaper;
/**
* Initializes context.
* Every scenario gets it's own context object.
*
* @param array $parameters context parameters (set them up through behat.yml)
*/
public function __construct(array $parameters = null)
{
if (!preg_match('#[\\\]FeatureContext$#', get_class($this))) {
throw new InvalidArgumentException(
'Subclasses of SilverStripeContext must be named FeatureContext. Found "' . get_class($this) . '""'
);
}
// Initialize your context here
$this->xpathEscaper = new Escaper();
$this->testSessionEnvironment = TestSessionEnvironment::singleton();
}
/**
* Get xpath escaper
*
* @return Escaper
*/
public function getXpathEscaper()
{
return $this->xpathEscaper;
}
public function setDatabase($databaseName)
{
$this->databaseName = $databaseName;
}
public function setAjaxSteps($ajaxSteps)
{
if ($ajaxSteps) {
$this->ajaxSteps = $ajaxSteps;
}
}
public function getAjaxSteps()
{
return $this->ajaxSteps;
}
public function setAjaxTimeout($ajaxTimeout)
{
$this->ajaxTimeout = $ajaxTimeout;
}
public function getAjaxTimeout()
{
return $this->ajaxTimeout;
}
public function setAdminUrl($adminUrl)
{
$this->adminUrl = $adminUrl;
}
public function getAdminUrl()
{
return $this->adminUrl;
}
public function setLoginUrl($loginUrl)
{
$this->loginUrl = $loginUrl;
}
public function getLoginUrl()
{
return $this->loginUrl;
}
public function setScreenshotPath($screenshotPath)
{
$this->screenshotPath = $screenshotPath;
}
public function getScreenshotPath()
{
return $this->screenshotPath;
}
public function getRegionMap()
{
return $this->regionMap;
}
public function setRegionMap($regionMap)
{
$this->regionMap = $regionMap;
}
/**
* Returns NodeElement based off region defined in .yml file.
* Also supports direct CSS selectors and regions identified by a "data-title" attribute.
* When using the "data-title" attribute, ensure not to include double quotes.
*
* @param string $region Region name or CSS selector
* @return NodeElement
* @throws ElementNotFoundException
*/
public function getRegionObj($region)
{
// Try to find regions directly by CSS selector.
try {
$regionObj = $this->getSession()->getPage()->find(
'css',
// Escape CSS selector
(false !== strpos($region ?? '', "'")) ? str_replace("'", "\\'", $region) : $region
);
if ($regionObj) {
return $regionObj;
}
} catch (SyntaxErrorException $e) {
// fall through to next case
}
// Fall back to region identified by data-title.
// Only apply if no double quotes exist in search string,
// which would break the CSS selector.
if (false === strpos($region ?? '', '"')) {
$regionObj = $this->getSession()->getPage()->find(
'css',
'[data-title="' . $region . '"]'
);
if ($regionObj) {
return $regionObj;
}
}
// Look for named region
if (!$this->regionMap) {
throw new \LogicException("Cannot find 'region_map' in the behat.yml");
}
if (!array_key_exists($region, $this->regionMap ?? [])) {
throw new \LogicException("Cannot find the specified region in the behat.yml");
}
$regionObj = $this->getSession()->getPage()->find('css', $region);
if (!$regionObj) {
throw new ElementNotFoundException($this->getSession(), "Cannot find the specified region on the page");
}
return $regionObj;
}
/**
* @BeforeScenario
* @param BeforeScenarioScope $event
*/
public function before(BeforeScenarioScope $event)
{
if (!isset($this->databaseName)) {
throw new \LogicException(
'Context\'s $databaseName has to be set when implementing SilverStripeAwareContextInterface.'
);
}
$webDriverSession = $this->getSession();
if (!$webDriverSession->isStarted()) {
$webDriverSession->start();
}
$state = $this->getTestSessionState();
$this->testSessionEnvironment->startTestSession($state);
// Optionally import database
if (!empty($state['importDatabasePath'])) {
$this->testSessionEnvironment->importDatabase(
$state['importDatabasePath'],
!empty($state['requireDefaultRecords']) ? $state['requireDefaultRecords'] : false
);
} elseif (!empty($state['requireDefaultRecords']) && $state['requireDefaultRecords']) {
$this->testSessionEnvironment->requireDefaultRecords();
}
// Fixtures
$fixtureFile = (!empty($state['fixture'])) ? $state['fixture'] : null;
if ($fixtureFile) {
$this->testSessionEnvironment->loadFixtureIntoDb($fixtureFile);
}
if ($screenSize = Environment::getEnv('BEHAT_SCREEN_SIZE')) {
list($screenWidth, $screenHeight) = explode('x', $screenSize ?? '');
$this->getSession()->resizeWindow((int)$screenWidth, (int)$screenHeight);
} else {
$this->getSession()->resizeWindow(1024, 768);
}
// Reset everything
foreach (ClassInfo::implementorsOf(Resettable::class) as $class) {
$class::reset();
}
DataObject::flush_and_destroy_cache();
DataObject::reset();
if (class_exists(SiteTree::class)) {
SiteTree::reset();
}
}
/**
* @AfterStep
*
* Wait for all requests to be handled after each step
*
* @param AfterStepScope $event
*/
public function waitResponsesAfterStep(AfterStepScope $event)
{
$success = $this->testSessionEnvironment->waitForPendingRequests();
if (!$success) {
echo (
'Warning! The timeout for waiting a response from the server has expired...'.PHP_EOL.
'I keep going on, but this test behaviour may be inconsistent.'.PHP_EOL.PHP_EOL.
'Your action required!'.PHP_EOL.PHP_EOL.
'You may want to investigate why the server is responding that slowly.'.PHP_EOL.
'Otherwise, you may need to increase the timeout.'
);
}
}
/**
* Returns a parameter map of state to set within the test session.
* Takes TESTSESSION_PARAMS environment variable into account for run-specific configurations.
*
* @return array
*/
public function getTestSessionState()
{
$extraParams = array();
parse_str(Environment::getEnv('TESTSESSION_PARAMS') ?? '', $extraParams);
return array_merge(
array(
'database' => $this->databaseName,
'mailer' => TestMailer::class,
),
$extraParams
);
}
/**
* Parses given URL and returns its components
*
* @param $url
* @return array|mixed Parsed URL
*/
public function parseUrl($url)
{
$url = parse_url($url ?? '');
$url['vars'] = array();
if (!isset($url['fragment'])) {
$url['fragment'] = null;
}
if (isset($url['query'])) {
parse_str($url['query'] ?? '', $url['vars']);
}
return $url;
}
/**
* Checks whether current URL is close enough to the given URL.
* Unless specified in $url, get vars will be ignored
* Unless specified in $url, fragment identifiers will be ignored
*
* @param $url string URL to compare to current URL
* @return boolean Returns true if the current URL is close enough to the given URL, false otherwise.
*/
public function isCurrentUrlSimilarTo($url)
{
$current = $this->parseUrl($this->getSession()->getCurrentUrl());
$test = $this->parseUrl($url);
if ($current['path'] !== $test['path']) {
return false;
}
if (isset($test['fragment']) && $current['fragment'] !== $test['fragment']) {
return false;
}
foreach ($test['vars'] as $name => $value) {
if (!isset($current['vars'][$name]) || $current['vars'][$name] !== $value) {
return false;
}
}
return true;
}
/**
* Returns base URL parameter set in MinkExtension.
* It simplifies configuration by allowing to specify this parameter
* once but makes code dependent on MinkExtension.
*
* @return string
*/
public function getBaseUrl()
{
return $this->getMinkParameter('base_url') ?: '';
}
/**
* Joins URL parts into an URL using forward slash.
* Forward slash usages are normalised to one between parts.
* This method takes variable number of parameters.
*
* @param string $part,...
* @return string
* @throws InvalidArgumentException
*/
public function joinUrlParts($part = null)
{
if (0 === func_num_args()) {
throw new InvalidArgumentException('Need at least one argument');
}
$parts = func_get_args();
$trimSlashes = function (&$part) {
$part = trim($part ?? '', '/');
};
array_walk($parts, $trimSlashes);
return implode('/', $parts);
}
public function canIntercept()
{
$driver = $this->getSession()->getDriver();
if ($driver instanceof FacebookWebDriver) {
return false;
}
throw new UnsupportedDriverActionException(
'You need to tag the scenario with "@mink:symfony". Intercepting the redirections is not supported by %s',
get_class($driver)
);
}
/**
* Fills in form field with specified id|name|label|value.
* Overwritten to select the first *visible* element, see https://github.com/Behat/Mink/issues/311
*
* @param string $field
* @param string $value
* @throws ElementNotFoundException
*/
public function fillField($field, $value)
{
$value = $this->fixStepArgument($value);
$nodes = $this->getSession()->getPage()->findAll('named', array(
'field', $this->getXpathEscaper()->escapeLiteral($field)
));
if ($nodes) {
/** @var NodeElement $node */
foreach ($nodes as $node) {
if ($node->isVisible()) {
// Work around for https://github.com/FluentLenium/FluentLenium/issues/129
// Otherwise "Element must be user-editable in order to clear it"
$type = $node->getAttribute('type');
$id = $node->getAttribute('id');
if ($type === 'date' && $id) {
$jsValue = Convert::raw2js($value);
$this->getSession()->getDriver()->executeScript(
"document.getElementById(\"{$id}\").value = \"{$jsValue}\";"
);
} else {
$node->setValue($value);
}
return;
}
}
}
throw new ElementNotFoundException(
$this->getSession(),
'form field',
'id|name|label|value',
$field
);
}
/**
* Overwritten to click the first *visible* link the DOM.
*
* @param string $link
* @throws ElementNotFoundException
*/
public function clickLink($link)
{
$link = $this->fixStepArgument($link);
$nodes = $this->getSession()->getPage()->findAll('named', array(
'link', $this->getXpathEscaper()->escapeLiteral($link)
));
if ($nodes) {
/** @var NodeElement $node */
foreach ($nodes as $node) {
if ($node->isVisible()) {
$node->click();
return;
}
}
}
throw new ElementNotFoundException(
$this->getSession(),
'link',
'id|name|label|value',
$link
);
}
/**
* Sets the current date. Relies on the underlying functionality using
* {@link SS_Datetime::now()} rather than PHP's system time methods like date().
* Supports ISO fomat: Y-m-d
* Example: Given the current date is "2009-10-31"
*
* @Given /^the current date is "([^"]*)"$/
* @param string $date
*/
public function givenTheCurrentDateIs($date)
{
$newDatetime = \DateTime::createFromFormat('Y-m-d', $date);
if (!$newDatetime) {
throw new InvalidArgumentException(sprintf('Invalid date format: %s (requires "Y-m-d")', $date));
}
$state = $this->testSessionEnvironment->getState();
$oldDatetime = \DateTime::createFromFormat('Y-m-d H:i:s', $state->datetime ?? '');
if ($oldDatetime) {
$newDatetime->setTime($oldDatetime->format('H'), $oldDatetime->format('i'), $oldDatetime->format('s'));
}
$state->datetime = $newDatetime->format('Y-m-d H:i:s');
$this->testSessionEnvironment->applyState($state);
}
/**
* Sets the current time. Relies on the underlying functionality using
* {@link \SS_Datetime::now()} rather than PHP's system time methods like date().
* Supports ISO fomat: H:i:s
* Example: Given the current time is "20:31:50"
*
* @Given /^the current time is "([^"]*)"$/
* @param string $time
*/
public function givenTheCurrentTimeIs($time)
{
$newDatetime = \DateTime::createFromFormat('H:i:s', $time);
if (!$newDatetime) {
throw new InvalidArgumentException(sprintf('Invalid date format: %s (requires "H:i:s")', $time));
}
$state = $this->testSessionEnvironment->getState();
$oldDatetime = \DateTime::createFromFormat('Y-m-d H:i:s', isset($state->datetime) ? $state->datetime : null);
if ($oldDatetime) {
$newDatetime->setDate($oldDatetime->format('Y'), $oldDatetime->format('m'), $oldDatetime->format('d'));
}
$state->datetime = $newDatetime->format('Y-m-d H:i:s');
$this->testSessionEnvironment->applyState($state);
}
/**
* Selects option in select field with specified id|name|label|value.
*
* @override /^(?:|I )select "(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)"$/
* @param string $select
* @param string $option
*/
public function selectOption($select, $option)
{
// Find field
$field = $this
->getSession()
->getPage()
->findField($this->fixStepArgument($select));
// If field is visible then select it as per normal
if ($field && $field->isVisible()) {
parent::selectOption($select, $option);
} else {
$this->selectOptionWithJavascript($select, $option);
}
}
/**
* Selects option in select field with specified id|name|label|value using javascript
* This method uses javascript to allow selection of options that may be
* overridden by javascript libraries, and thus hide the element.
*
* @When /^(?:|I )select "(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)" with javascript$/
* @param string $select
* @param string $option
* @throws ElementNotFoundException
*/
public function selectOptionWithJavascript($select, $option)
{
$select = $this->fixStepArgument($select);
$option = $this->fixStepArgument($option);
$page = $this->getSession()->getPage();
// Find field
$field = $page->findField($select);
if (null === $field) {
throw new ElementNotFoundException($this->getSession(), 'form field', 'id|name|label|value', $select);
}
// Find option
$opt = $field->find('named', array(
'option', $this->getXpathEscaper()->escapeLiteral($option)
));
if (null === $opt) {
throw new ElementNotFoundException($this->getSession(), 'select option', 'value|text', $option);
}
// Merge new option in with old handling both multiselect and single select
$value = $field->getValue();
$newValue = $opt->getAttribute('value');
if (is_array($value)) {
if (!in_array($newValue, $value ?? [])) {
$value[] = $newValue;
}
} else {
$value = $newValue;
}
$valueEncoded = json_encode($value);
// Inject this value via javascript
$fieldID = $field->getAttribute('ID');
$script = <<<EOS
(function($) {
$("#$fieldID")
.val($valueEncoded)
.change()
.trigger('liszt:updated')
.trigger('chosen:updated');
})(jQuery);
EOS;
$this->getSession()->getDriver()->executeScript($script);
}
}