forked from michalochman/SilverStripeExtension
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicContext.php
More file actions
1746 lines (1595 loc) · 59.7 KB
/
BasicContext.php
File metadata and controls
1746 lines (1595 loc) · 59.7 KB
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace SilverStripe\BehatExtension\Context;
use Exception;
use InvalidArgumentException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\Environment\InitializedContextEnvironment;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Behat\Behat\Hook\Scope\AfterStepScope;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Behat\Hook\Scope\BeforeStepScope;
use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Element\ElementInterface;
use Behat\Mink\Element\NodeElement;
use Behat\Mink\Exception\ElementNotFoundException;
use Behat\Mink\Session;
use Behat\Testwork\Tester\Result\TestResult;
use Facebook\WebDriver\Exception\WebDriverException;
use Facebook\WebDriver\WebDriver;
use Facebook\WebDriver\WebDriverAlert;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverKeys;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\ExpectationFailedException;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Filesystem;
use SilverStripe\BehatExtension\Utility\StepHelper;
use SilverStripe\BehatExtension\Utility\DebugTools;
use SilverStripe\MinkFacebookWebDriver\FacebookWebDriver;
/**
* BasicContext
*
* Context used to define generic steps like following anchors or pressing buttons.
* Handles timeouts.
* Handles redirections.
* Handles AJAX enabled links, buttons and forms - jQuery is assumed.
*/
class BasicContext implements Context
{
use MainContextAwareTrait;
use StepHelper;
use DebugTools;
/**
* Date format in date() syntax
*
* @var string
*/
protected $dateFormat = 'Y-m-d';
/**
* Time format in date() syntax
* @var String
*/
protected $timeFormat = 'H:i:s';
/**
* Date/time format in date() syntax
* @var String
*/
protected $datetimeFormat = 'Y-m-d H:i:s';
/**
* @var FixtureContext
*/
protected $fixtureContext = null;
/**
* Get the fixture context of the current module
*
* @BeforeScenario
*/
public function gatherContexts(BeforeScenarioScope $scope): void
{
/** @var InitializedContextEnvironment $environment */
$environment = $scope->getEnvironment();
// Find the FixtureContext defined in behat.yml
$subClasses = $this->getSubclassesOf(FixtureContext::class);
foreach ($subClasses as $class) {
if (!$environment->hasContextClass($class)) {
continue;
}
$this->fixtureContext = $environment->getContext($class);
break;
}
// Fallback to base FixtureClass
if (!$this->fixtureContext && $environment->hasContextClass(FixtureContext::class)) {
$this->fixtureContext = $environment->getContext(FixtureContext::class);
}
}
/**
* Gets the subclasses of a class
*/
private function getSubclassesOf($parent): array
{
$result = [];
foreach (get_declared_classes() as $class) {
if (is_subclass_of($class, $parent ?? '')) {
$result[] = $class;
}
}
return $result;
}
/**
* Get Mink session from MinkContext
*
* @param string $name
* @return Session
*/
public function getSession($name = null)
{
/** @var SilverStripeContext $context */
$context = $this->getMainContext();
return $context->getSession($name);
}
/**
* @AfterStep
*
* Excluding scenarios with @modal tag is required,
* because modal dialogs stop any JS interaction
*
* @param AfterStepScope $event
*/
public function appendErrorHandlerBeforeStep(AfterStepScope $event)
{
// Manually exclude @modal
if ($this->stepHasTag($event, 'modal')) {
return;
}
try {
$javascript = <<<JS
window.onerror = function(message, file, line, column, error) {
var body = document.getElementsByTagName('body')[0];
var msg = message + " in " + file + ":" + line + ":" + column;
if(error !== undefined && error.stack !== undefined) {
msg += "\\nSTACKTRACE:\\n" + error.stack;
}
body.setAttribute('data-jserrors', '[captured JavaScript error] ' + msg);
};
if ('undefined' !== typeof window.jQuery) {
window.jQuery('body').ajaxError(function(event, jqxhr, settings, exception) {
if ('abort' === exception) {
return;
}
window.onerror(event.type + ': ' + settings.type + ' ' + settings.url + ' ' + exception + ' ' + jqxhr.responseText);
});
}
JS;
$this->getSession()->executeScript($javascript);
} catch (WebDriverException $e) {
$this->logException($e);
}
}
/**
* @AfterStep
*
* Excluding scenarios with @modal tag is required,
* because modal dialogs stop any JS interaction
*
* @param AfterStepScope $event
*/
public function readErrorHandlerAfterStep(AfterStepScope $event)
{
// Manually exclude @modal
if ($this->stepHasTag($event, 'modal')) {
return;
}
try {
$page = $this->getSession()->getPage();
$jserrors = $page->find('xpath', '//body[@data-jserrors]');
if (null !== $jserrors) {
$this->takeScreenshot($event);
$this->logMessage($jserrors->getAttribute('data-jserrors'));
}
$javascript = <<<JS
if ('undefined' !== typeof window.jQuery) {
window.jQuery(document).ready(function() {
window.jQuery('body').removeAttr('data-jserrors');
});
}
JS;
$this->getSession()->executeScript($javascript);
} catch (WebDriverException $e) {
$this->logException($e);
}
}
/**
* Hook into jQuery ajaxStart, ajaxSuccess and ajaxComplete events.
* Prepare __ajaxStatus() functions and attach them to these handlers.
* Event handlers are removed after one run.
*
* @BeforeStep
* @param BeforeStepScope $event
*/
public function handleAjaxBeforeStep(BeforeStepScope $event)
{
// Manually exclude @modal
if ($this->stepHasTag($event, 'modal')) {
return;
}
try {
$ajaxEnabledSteps = $this->getMainContext()->getAjaxSteps();
$ajaxEnabledSteps = implode('|', array_filter($ajaxEnabledSteps ?? []));
if (empty($ajaxEnabledSteps) || !preg_match('/(' . $ajaxEnabledSteps . ')/i', $event->getStep()->getText() ?? '')) {
return;
}
$javascript = <<<JS
if ('undefined' !== typeof window.jQuery && 'undefined' !== typeof window.jQuery.fn.on) {
window.jQuery(document).on('ajaxStart.ss.test.behaviour', function(){
window.__ajaxStatus = function() {
return 'waiting';
};
});
window.jQuery(document).on('ajaxComplete.ss.test.behaviour', function(e, jqXHR){
if (null === jqXHR.getResponseHeader('X-ControllerURL')) {
window.__ajaxStatus = function() {
return 'no ajax';
};
}
});
window.jQuery(document).on('ajaxSuccess.ss.test.behaviour', function(e, jqXHR){
if (null === jqXHR.getResponseHeader('X-ControllerURL')) {
window.__ajaxStatus = function() {
return 'success';
};
}
});
}
JS;
$this->getSession()->wait(500); // give browser a chance to process and render response
$this->getSession()->executeScript($javascript);
} catch (WebDriverException $e) {
$this->logException($e);
}
}
/**
* Wait for the __ajaxStatus()to return anything but 'waiting'.
* Don't wait longer than 5 seconds.
*
* Don't unregister handler if we're dealing with modal windows
*
* @AfterStep
* @param AfterStepScope $event
*/
public function handleAjaxAfterStep(AfterStepScope $event)
{
// Manually exclude @modal
if ($this->stepHasTag($event, 'modal')) {
return;
}
try {
$ajaxEnabledSteps = $this->getMainContext()->getAjaxSteps();
$ajaxEnabledSteps = implode('|', array_filter($ajaxEnabledSteps ?? []));
if (empty($ajaxEnabledSteps) || !preg_match('/(' . $ajaxEnabledSteps . ')/i', $event->getStep()->getText() ?? '')) {
return;
}
$this->handleAjaxTimeout();
$javascript = <<<JS
if ('undefined' !== typeof window.jQuery && 'undefined' !== typeof window.jQuery.fn.off) {
window.jQuery(document).off('ajaxStart.ss.test.behaviour');
window.jQuery(document).off('ajaxComplete.ss.test.behaviour');
window.jQuery(document).off('ajaxSuccess.ss.test.behaviour');
}
JS;
$this->getSession()->executeScript($javascript);
} catch (WebDriverException $e) {
$this->logException($e);
}
}
public function handleAjaxTimeout()
{
$timeoutMs = $this->getMainContext()->getAjaxTimeout();
// Wait for an ajax request to complete, but only for a maximum of 5 seconds to avoid deadlocks
$this->getSession()->wait(
$timeoutMs,
"(typeof window.__ajaxStatus !== 'undefined' ? window.__ajaxStatus() : 'no ajax') !== 'waiting'"
);
// wait additional 100ms to allow DOM to update
$this->getSession()->wait(100);
}
/**
* Close modal dialog if test scenario fails on CMS page
*
* @AfterScenario
* @param AfterScenarioScope $event
*/
public function closeModalDialog(AfterScenarioScope $event)
{
$expectsUnsavedChangesModal = $this->stepHasTag($event, 'unsavedChanges');
try {
// Only for failed tests on CMS page
if ($expectsUnsavedChangesModal || $event->getTestResult()->getResultCode() === TestResult::FAILED) {
$cmsElement = $this->getSession()->getPage()->find('css', '.cms');
if ($cmsElement) {
try {
// Navigate away triggered by reloading the page
$this->getSession()->reload();
$this->getExpectedAlert()->accept();
} catch (WebDriverException $e) {
// no-op, alert might not be present
}
}
}
} catch (WebDriverException $e) {
$this->logException($e);
}
}
/**
* Delete any created files and folders from assets directory
*
* @AfterScenario @assets
* @param AfterScenarioScope $event
*/
public function cleanAssetsAfterScenario(AfterScenarioScope $event)
{
foreach (File::get() as $file) {
$file->delete();
}
Filesystem::removeFolder(ASSETS_PATH, true);
}
/**
* @Given /^the page can't be found/
*/
public function stepPageCantBeFound()
{
$page = $this->getSession()->getPage();
Assert::assertTrue(
// Content from ErrorPage default record
$page->hasContent('Page not found')
// Generic ModelAsController message
|| $page->hasContent('The requested page could not be found')
);
}
/**
* @Given /^I wait (?:for )?([\d\.]+) second(?:s?)$/
*
* @param float $secs
*/
public function stepIWaitFor($secs)
{
$this->getSession()->wait((float)$secs * 1000);
}
/**
* Find visible button with the given text.
* Supports data-text-alternate property.
*
* @param string $title
* @return NodeElement|null
*/
public function findNamedButton($title, ?ElementInterface $parent = null)
{
if ($parent === null) {
$parent = $this->getSession()->getPage();
}
// See https://mathiasbynens.be/notes/css-escapes
$escapedTitle = addcslashes($title ?? '', '!"#$%&\'()*+,-./:;<=>?@[\]^`{|}~');
$searches = [
['named', ['link_or_button', "'{$title}'"]],
['css', "button[data-text-alternate='{$escapedTitle}']"],
];
foreach ($searches as list($type, $arg)) {
$buttons = $parent->findAll($type, $arg);
/** @var NodeElement $button */
foreach ($buttons as $button) {
if ($button->isVisible()) {
return $button;
}
}
}
return null;
}
/**
* Example: I should see a "Submit" button
* Example: I should not see a "Delete" button
*
* @Given /^I should( not? |\s*)see (?:a|an|the) "([^"]*)" button$/
* @param string $negative
* @param string $text
*/
public function iShouldSeeAButton($negative, $text)
{
$button = $this->findNamedButton($text);
if (trim($negative ?? '')) {
Assert::assertNull($button, sprintf('%s button found', $text));
} else {
Assert::assertNotNull($button, sprintf('%s button not found', $text));
}
}
/**
* @Given /^I press the "([^"]*)" button$/
* @param string $text
*/
public function stepIPressTheButton($text)
{
$button = $this->findNamedButton($text);
Assert::assertNotNull($button, "{$text} button not found");
$button->click();
}
/**
* @Given /^I press the "([^"]*)" buttons$/
* @param string $text A list of button names can be provided by seperating the entries with the | character.
*/
public function stepIPressTheButtons($text)
{
$buttonNames = explode('|', $text ?? '');
foreach ($buttonNames as $name) {
$button = $this->findNamedButton(trim($name ?? ''));
if ($button) {
break;
}
}
Assert::assertNotNull($button, "{$text} button not found");
$button->click();
}
/**
* Needs to be in single command to avoid "unexpected alert open" errors in Selenium.
* Example1: I press the "Remove current combo" button, confirming the dialog
* Example2: I follow the "Remove current combo" link, confirming the dialog
*
* @Given /^I (?:press|follow) the "([^"]*)" (?:button|link), confirming the dialog$/
* @param string $button
*/
public function stepIPressTheButtonConfirmingTheDialog($button)
{
$this->stepIPressTheButton($button);
$this->iConfirmTheDialog();
}
/**
* Needs to be in single command to avoid "unexpected alert open" errors in Selenium.
* Example: I follow the "Remove current combo" link, dismissing the dialog
*
* @Given /^I (?:press|follow) the "([^"]*)" (?:button|link), dismissing the dialog$/
* @param string $button
*/
public function stepIPressTheButtonDismissingTheDialog($button)
{
$this->stepIPressTheButton($button);
$this->iDismissTheDialog();
}
/**
* @Given /^I click on the "([^"]+)" element$/
* @param string $selector
*/
public function iClickOnTheElement($selector)
{
$page = $this->getMainContext()->getSession()->getPage();
$element = $page->find('css', $selector);
Assert::assertNotNull($element, sprintf('Element %s not found', $selector));
$element->click();
}
/**
* Needs to be in single command to avoid "unexpected alert open" errors in Selenium.
*
* @When /^I click on the "([^"]+)" element, confirming the dialog$/
* @param $selector
*/
public function iClickOnTheElementConfirmingTheDialog($selector)
{
$this->iClickOnTheElement($selector);
$this->iConfirmTheDialog();
}
/**
* @Given /^I (click|double click) "([^"]*)"(| directly) in the "([^"]*)" element$/
* @param string $clickType
* @param string $text
* @param string $directly If used, the text must be directly in the element. Otherwise it can be in a child element.
* @param string $selector
*/
public function iClickInTheElement($clickType, $text, $directly, $selector)
{
$clickTypeMap = array(
"double click" => "doubleclick",
"click" => "click"
);
$page = $this->getSession()->getPage();
$parentElement = $page->find('css', $selector);
Assert::assertNotNull($parentElement, sprintf('"%s" element not found', $selector));
if ($directly) {
// Finds the specific text within the selector element (to validate it's there), and then grabs the element that holds the text
$element = $parentElement->find('xpath', sprintf('/text()[contains(.,"%s")]/..', $text));
} else {
// Finds a child of the selector element which contains the text
$element = $parentElement->find('xpath', sprintf('//*[count(*)=0 and contains(.,"%s")]', $text));
}
Assert::assertNotNull($element, sprintf('"%s" not found', $text));
$clickTypeFn = $clickTypeMap[$clickType];
$element->$clickTypeFn();
}
/**
* Needs to be in single command to avoid "unexpected alert open" errors in Selenium.
* Example: I click "Delete" in the ".actions" element, confirming the dialog
*
* @Given /^I (click|double click) "([^"]*)" in the "([^"]*)" element, confirming the dialog$/
* @param string $clickType
* @param string $text
* @param string $selector
*/
public function iClickInTheElementConfirmingTheDialog($clickType, $text, $selector)
{
$this->iClickInTheElement($clickType, $text, $selector);
$this->iConfirmTheDialog();
}
/**
* Needs to be in single command to avoid "unexpected alert open" errors in Selenium.
* Example: I click "Delete" in the ".actions" element, dismissing the dialog
*
* @Given /^I (click|double click) "([^"]*)" in the "([^"]*)" element, dismissing the dialog$/
* @param string $clickType
* @param string $text
* @param string $selector
*/
public function iClickInTheElementDismissingTheDialog($clickType, $text, $selector)
{
$this->iClickInTheElement($clickType, $text, $selector);
$this->iDismissTheDialog();
}
/**
* @Then /^the "([^"]+)" element "([^"]+)" attribute should be "([^"]*)"$/
*/
public function theElementAttributeShouldBe($selector, $attribute, $value)
{
$page = $this->getSession()->getPage();
$element = $page->find('css', $selector);
Assert::assertNotNull($element, sprintf('Element %s not found', $selector));
Assert::assertEquals($value, $element->getAttribute($attribute));
}
/**
* @Given /^I see the text "([^"]+)" in the alert$/
* @param string $expected
*/
public function iSeeTheDialogText($expected)
{
$driver = $this->getSession()->getDriver();
if ($driver instanceof Selenium2Driver) {
$text = $driver->getWebDriverSession()->getAlert_text();
} else {
$text = $this->getExpectedAlert()->getText();
}
Assert::assertStringContainsString($expected, $text);
}
/**
* @Given /^I type "([^"]*)" into the dialog$/
* @param string $data
*/
public function iTypeIntoTheDialog($data)
{
$this->getExpectedAlert()
->sendKeys($data)
->accept();
}
/**
* Wait for alert to appear, and return handle
*
* @return WebDriverAlert
*/
protected function getExpectedAlert()
{
$session = $this->getWebDriverSession();
$session->wait()->until(
WebDriverExpectedCondition::alertIsPresent(),
"Alert is expected"
);
return $session->switchTo()->alert();
}
/**
* @Given /^I confirm the dialog$/
*/
public function iConfirmTheDialog()
{
$driver = $this->getSession()->getDriver();
if ($driver instanceof Selenium2Driver) {
$driver->getWebDriverSession()->accept_alert();
} else {
$session = $this->getWebDriverSession();
$session->wait()->until(
WebDriverExpectedCondition::alertIsPresent(),
"Alert is expected"
);
$session->switchTo()->alert()->accept();
}
$this->handleAjaxTimeout();
}
/**
* @Given /^I dismiss the dialog$/
*/
public function iDismissTheDialog()
{
$driver = $this->getSession()->getDriver();
if ($driver instanceof Selenium2Driver) {
$driver->getWebDriverSession()->dismiss_alert();
} else {
$this->getExpectedAlert()->dismiss();
}
$this->handleAjaxTimeout();
}
/**
* Get Selenium webdriver session.
* Note: Will fail if current driver isn't FacebookWebDriver
*
* @return WebDriver
*/
protected function getWebDriverSession()
{
$driver = $this->getSession()->getDriver();
if (!$driver instanceof FacebookWebDriver) {
throw new InvalidArgumentException("Only supported for FacebookWebDriver");
}
return $driver->getWebDriver();
}
/**
* Select a specific option in a select element
*
* @Given /^I select "([^"]*)" in the "([^"]*)" dropdown$/
*/
public function iSelectOptionInDropdown(string $optionLocator, string $dropdownLocator): void
{
$dropdown = $this->getElement($dropdownLocator);
$dropdown->selectOption($optionLocator);
}
/**
* Validate that a specific option is selected in a select element
*
* @Then /^the "([^"]*)" option is selected in the "([^"]*)" dropdown$/
*/
public function optionIsSelectedInDropdown(string $optionLocator, string $dropdownLocator): void
{
$dropdown = $this->getElement($dropdownLocator);
$selectedOption = null;
foreach ($dropdown->findAll('css', 'option') as $option) {
if ($option->isSelected()) {
$selectedOption = $option;
break;
}
}
if ($selectedOption === null) {
throw new InvalidArgumentException("No option was selected in dropdown '$dropdownLocator'");
}
// Try value first - use == instead of === because the type may be e.g. int vs our expected string.
if ($selectedOption->getValue() == $optionLocator) {
return;
}
// Then try text - sometimes the value isn't the same as the text, and often behat tests are written based on what's visible
if ($selectedOption->getText() === $optionLocator) {
return;
}
throw new InvalidArgumentException("Option '$optionLocator' wasn't selected - selected option is '{$selectedOption->getValue()}'");
}
/**
* Select an individual input from within a group, matched by the top-most label.
*
* @Given /^I select "([^"]*)" from "([^"]*)" input group$/
* @param string $value
* @param string $labelText
*/
public function iSelectFromInputGroup($value, $labelText)
{
$page = $this->getSession()->getPage();
$parent = null;
/** @var NodeElement $label */
foreach ($page->findAll('css', 'label') as $label) {
if ($label->getText() == $labelText) {
$parent = $label->getParent();
}
}
if (!$parent) {
throw new InvalidArgumentException(sprintf('Input group with label "%s" cannot be found', $labelText));
}
/** @var NodeElement $option */
foreach ($parent->findAll('css', 'label') as $option) {
if ($option->getText() == $value) {
$input = null;
// First, look for inputs referenced by the "for" element on this label
$for = $option->getAttribute('for');
if ($for) {
$input = $parent->findById($for);
}
// Otherwise look for inputs _inside_ the label
if (!$input) {
$input = $option->find('css', 'input');
}
if (!$input) {
throw new InvalidArgumentException(sprintf('Input "%s" cannot be found', $value));
}
$this->getSession()->getDriver()->click($input->getXPath());
}
}
}
/**
* Pauses the scenario until the user presses a key. Useful when debugging a scenario.
*
* @Then /^(?:|I )put a breakpoint$/
*/
public function iPutABreakpoint()
{
fwrite(STDOUT, "\033[s \033[93m[Breakpoint] Press \033[1;93m[RETURN]\033[0;93m to continue...\033[0m");
while (fgets(STDIN, 1024) == '') {
// noop
}
fwrite(STDOUT, "\033[u");
return;
}
/**
* Transforms relative time statements compatible with strtotime().
* Example: "time of 1 hour ago" might return "22:00:00" if its currently "23:00:00".
* Customize through {@link setTimeFormat()}.
*
* @Transform /^(?:(the|a)) time of (?<val>.*)$/
* @param string $prefix
* @param string $val
* @return false|string
*/
public function castRelativeToAbsoluteTime($prefix, $val)
{
$timestamp = strtotime($val ?? '');
if (!$timestamp) {
throw new InvalidArgumentException(sprintf(
"Can't resolve '%s' into a valid datetime value",
$val
));
}
return date($this->timeFormat ?? '', $timestamp);
}
/**
* Transforms relative date and time statements compatible with strtotime().
* Example: "datetime of 2 days ago" might return "2013-10-10 22:00:00" if its currently
* the 12th of October 2013. Customize through {@link setDatetimeFormat()}.
*
* @Transform /^(?:(the|a)) datetime of (?<val>.*)$/
* @param string $prefix
* @param string $val
* @return false|string
*/
public function castRelativeToAbsoluteDatetime($prefix, $val)
{
$timestamp = strtotime($val ?? '');
if (!$timestamp) {
throw new InvalidArgumentException(sprintf(
"Can't resolve '%s' into a valid datetime value",
$val
));
}
return date($this->datetimeFormat ?? '', $timestamp);
}
/**
* Transforms relative date statements compatible with strtotime().
* Example: "date 2 days ago" might return "2013-10-10" if its currently
* the 12th of October 2013. Customize through {@link setDateFormat()}.
*
* @Transform /^(?:(the|a)) date of (?<val>.*)$/
* @param string $prefix
* @param string $val
* @return false|string
*/
public function castRelativeToAbsoluteDate($prefix, $val)
{
$timestamp = strtotime($val ?? '');
if (!$timestamp) {
throw new InvalidArgumentException(sprintf(
"Can't resolve '%s' into a valid datetime value",
$val
));
}
return date($this->dateFormat ?? '', $timestamp);
}
public function getDateFormat()
{
return $this->dateFormat;
}
public function setDateFormat($format)
{
$this->dateFormat = $format;
}
public function getTimeFormat()
{
return $this->timeFormat;
}
public function setTimeFormat($format)
{
$this->timeFormat = $format;
}
public function getDatetimeFormat()
{
return $this->datetimeFormat;
}
public function setDatetimeFormat($format)
{
$this->datetimeFormat = $format;
}
/**
* Checks that field with specified in|name|label|value is disabled.
* Example: Then the field "Email" should be disabled
* Example: Then the "Email" field should be disabled
*
* @Then /^the "(?P<name>(?:[^"]|\\")*)" (?P<type>(?:(field|button))) should (?P<negate>(?:(not |)))be disabled/
* @Then /^the (?P<type>(?:(field|button))) "(?P<name>(?:[^"]|\\")*)" should (?P<negate>(?:(not |)))be disabled/
* @param string $name
* @param string $type
* @param string $negate
*/
public function stepFieldShouldBeDisabled($name, $type, $negate)
{
$page = $this->getSession()->getPage();
if ($type == 'field') {
$element = $page->findField($name);
} else {
$element = $page->find('named', array(
'button',
$this->getMainContext()->getXpathEscaper()->escapeLiteral($name)
));
}
Assert::assertNotNull($element, sprintf("Element '%s' not found", $name));
$disabledAttribute = $element->getAttribute('disabled');
if (trim($negate ?? '')) {
Assert::assertNull($disabledAttribute, sprintf("Failed asserting element '%s' is not disabled", $name));
} else {
Assert::assertNotNull($disabledAttribute, sprintf("Failed asserting element '%s' is disabled", $name));
}
}
/**
* Checks that checkbox with specified in|name|label|value is enabled.
* Example: Then the field "Email" should be enabled
* Example: Then the "Email" field should be enabled
*
* @Then /^the "(?P<field>(?:[^"]|\\")*)" field should be enabled/
* @Then /^the field "(?P<field>(?:[^"]|\\")*)" should be enabled/
* @param string $field
*/
public function stepFieldShouldBeEnabled($field)
{
$page = $this->getSession()->getPage();
$fieldElement = $page->findField($field);
Assert::assertNotNull($fieldElement, sprintf("Field '%s' not found", $field));
$disabledAttribute = $fieldElement->getAttribute('disabled');
Assert::assertNull($disabledAttribute, sprintf("Failed asserting field '%s' is enabled", $field));
}
/**
* Clicks a link in a specific region (an element identified by a CSS selector, a "data-title" attribute,
* or a named region mapped to a CSS selector via Behat configuration).
*
* Example: Given I follow "Select" in the "header .login-form" region
* Example: Given I follow "Select" in the "My Login Form" region
*
* @Given /^I (?:follow|click) "(?P<link>[^"]*)" in the "(?P<region>[^"]*)" region$/
* @param string $link
* @param string $region
* @throws \Exception
*/
public function iFollowInTheRegion($link, $region)
{
$context = $this->getMainContext();
$regionObj = $context->getRegionObj($region);
Assert::assertNotNull($regionObj);
$linkObj = $regionObj->findLink($link);
if (empty($linkObj)) {
throw new \Exception(sprintf('The link "%s" was not found in the region "%s"
on the page %s', $link, $region, $this->getSession()->getCurrentUrl()));
}
$linkObj->click();
}
/**
* Fills in a field in a specfic region similar to (@see iFollowInTheRegion or @see iSeeTextInRegion)
*
* Example: Given I fill in "Hello" with "World"
*
* @Given /^I fill in "(?P<field>[^"]*)" with "(?P<value>[^"]*)" in the "(?P<region>[^"]*)" region$/
* @param string $field
* @param string $value
* @param string $region
* @throws \Exception
*/
public function iFillinTheRegion($field, $value, $region)
{
$context = $this->getMainContext();
$regionObj = $context->getRegionObj($region);
Assert::assertNotNull($regionObj, "Region Object is null");
$fieldObj = $regionObj->findField($field);
if (empty($fieldObj)) {
throw new \Exception(sprintf('The field "%s" was not found in the region "%s"
on the page %s', $field, $region, $this->getSession()->getCurrentUrl()));
}
$regionObj->fillField($field, $value);
}
/**
* Asserts text in a specific region (an element identified by a CSS selector, a "data-title" attribute,
* or a named region mapped to a CSS selector via Behat configuration).
* Supports regular expressions in text value.
*
* Example: Given I should see "My Text" in the "header .login-form" region
* Example: Given I should not see "My Text" in the "My Login Form" region
*
* @Given /^I should (?P<negate>(?:(not |)))see "(?P<text>[^"]*)" in the "(?P<region>[^"]*)" region$/
* @param string $negate
* @param string $text
* @param string $region
* @throws \Exception
*/
public function iSeeTextInRegion($negate, $text, $region)
{
$context = $this->getMainContext();
$regionObj = $context->getRegionObj($region);
Assert::assertNotNull($regionObj);
$actual = $regionObj->getText();
$actual = preg_replace('/\s+/u', ' ', $actual ?? '');
$regex = '/' . preg_quote($text ?? '', '/') . '/ui';
if (trim($negate ?? '')) {
if (preg_match($regex ?? '', $actual ?? '')) {
$message = sprintf(
'The text "%s" was found in the text of the "%s" region on the page %s.',
$text,
$region,
$this->getSession()->getCurrentUrl()
);
throw new \Exception($message);
}
} else {
if (!preg_match($regex ?? '', $actual ?? '')) {