-
Notifications
You must be signed in to change notification settings - Fork 5
/
HelperContext.php
1084 lines (932 loc) · 31.3 KB
/
HelperContext.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
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
/**
* @file
*/
namespace CWTest\Context;
use Drupal\DrupalExtension\Context\RawDrupalContext;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Behat\Hook\Scope\AfterStepScope;
use Drupal\DrupalExtension\Context\MinkContext;
use Behat\Gherkin\Node\TableNode;
use Behat\Behat\Context\SnippetAcceptingContext;
use CWTest\Exception\CWContextException;
use CWTest\Util\RandomItems;
/**
* Class HelperContext
*
* HelperContext contains supporting functions for all Behat projects.
*/
class HelperContext extends RawDrupalContext implements SnippetAcceptingContext {
// HTTP 200 status response.
const HTTP_200_STATUS = 200;
// Error code.
const ERROR_CODE = 99;
// Timeout value in ms.
const TIMEOUT = 15000;
// Wait value in ms.
const WAIT = 1000;
// Browser width.
const WIDTH = 1440;
// Browser height.
const HEIGHT = 900;
// Max number of retries.
const RETRIES = 30;
// One second.
const SECOND_TO_SLEEP = 1;
// Date format.
const DATE_FORMAT_CONCISE = "dmY-His";
// File extensions.
const EXTENSION_DOT = '.';
const EXTENSION_HTML = 'html';
const EXTENSION_JPG = 'jpg';
/**
* Parameters inherited from the .yml file
* @var string
*/
public $parameters;
/**
* Variable strings and numbers
* @var RandomItems
*/
public $randomItems;
/**
* @var MinkContext
*/
public $minkContext;
/**
* page HTML
* @var string
*/
private $html;
/**
* Array of page elements
* @var array
*/
private $pageElements = array();
/**
* The current Behat scenario.
* @var string
*/
private $currentScenario;
/**
* The current Behat scenario name.
*
* @var string
*/
private $scenarioName;
/*******************************************************************************
* Start of INITIALISATION functions.
*******************************************************************************/
/**
* Initializes context.
*
* Every scenario gets its own context instance.
* Arguments are passed through the behat.yml.
*/
public function __construct(array $parameters) {
$this->parameters = $parameters;
// Generate random strings for each scenario.
$this->generateRandomStrings();
}
/**
* @BeforeScenario
*
* Allow access to the MinkContext.
*/
public function gatherContexts(BeforeScenarioScope $scope) {
$environment = $scope->getEnvironment();
$this->minkContext = $environment->getContext('Drupal\DrupalExtension\Context\MinkContext');
$this->currentScenario = $scope->getScenario();
$this->scenarioName = $this->currentScenario->getTitle();
}
/**
* @Given I maximise the browser window
*/
public function maximiseTheBrowserWindow() {
$this->getSession()->maximizeWindow();
}
/**
* Generate random numbers/strings to be used throughout the scenarios.
*/
public function generateRandomStrings() {
$this->randomItems = new RandomItems();
// Generate a random number.
$this->randomItems->number = date("U");
// Generate a random alphanumeric string.
$this->randomItems->alphaNumber = uniqid();
// Generate a random string.
$this->randomItems->alpha = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8);
}
/**
* @AfterStep
*
* Take screenshot and HTML dump when test fails.
*/
public function captureScreenAfterFailedStep(AfterStepScope $scope) {
if (self::ERROR_CODE !== $scope->getTestResult()->getResultCode()) {
return;
}
// Remove quotes from the test step name.
$failed_test_step = preg_replace('/[^a-zA-Z0-9\-]+/', '_', $scope->getStep()
->getText());
// Set the screenshot location.
$featureFolder = str_replace(' ', '', $scope->getFeature()->getTitle());
$filePath = $this->parameters['screenshot_path'] . '/' . $featureFolder;
if (!file_exists($filePath)) {
mkdir($filePath, 0777, TRUE);
}
$driver = $this->getSession()->getDriver();
$filename_prefix = date(self::DATE_FORMAT_CONCISE) . '-' . $failed_test_step;
if ($driver instanceof \Behat\Mink\Driver\BrowserKitDriver) {
// Generate HTML dump.
$html_data = $this->getSession()->getDriver()->getContent();
$fileName = $filename_prefix . self::EXTENSION_DOT . self::EXTENSION_HTML;
file_put_contents($filePath . '/' . $fileName, $html_data);
}
elseif ($driver instanceof \Behat\Mink\Driver\Selenium2Driver) {
// Generate HTML dump.
$html_data = $this->getSession()->getDriver()->getContent();
$fileName = $filename_prefix . self::EXTENSION_DOT . self::EXTENSION_HTML;
file_put_contents($filePath . '/' . $fileName, $html_data);
// Generate JPG.
$fileName = $filename_prefix . self::EXTENSION_DOT . self::EXTENSION_JPG;
$this->saveScreenshot($fileName, $filePath);
}
}
/*******************************************************************************
* End of INITIALISATION functions.
*******************************************************************************/
/*******************************************************************************
* Start of WAITING functions.
*******************************************************************************/
/**
* Wait for an element to appear identified by CSS.
* @Given wait until css element :css is visible
*/
public function iWaitForElementToBeVisibleByCSS($css) {
$this->find('css', $css);
}
/**
* Wait for an element to appear identified by an Xpath.
* @Given wait until xpath element :xpath is visible
*/
public function iWaitForElementToBeVisibleByXpath($xpath) {
$this->find('xpath', $xpath);
}
/**
* Finds an element within a given timeout
* @param string $type
* The type of element identifier
* @param string $locator
* The locator of the element.
* @param int $retries
* @return bool The boolean returned from the function.
* The boolean returned from the function.
* @throws \Exception
*/
public function find($type, $locator, $retries = self::RETRIES) {
return $this->spin(function ($context) use ($type, $locator) {
$page = $this->getSession()->getPage();
if ($element = $page->find($type, $locator)) {
if ($element->isVisible()) {
return $element->isVisible();
}
}
return FALSE;
}, $retries, $locator);
}
/**
* Return true if an element is located
* @param callable $lambda
* The anonymous function passed from the calling function.
* @param int $retries
* The maximum number of retries.
* @param string $locator
* The locator of the element.
* @return bool
* The boolean returned from the function.
* @throws \Exception
* The exception if the element cannot be found.
*/
public function spin($lambda, $retries, $locator) {
for ($i = 0; $i < $retries; $i++) {
try {
if ($lambda($this)) {
return TRUE;
}
} catch (Exception $e) {
// do nothing
}
sleep(1);
}
throw new CWContextException("Timeout thrown by spinner - element {$locator} is not visible after 30 seconds.");
}
/**
* @Given I wait for :number seconds
*/
public function iWaitForSeconds($number) {
$this->getSession()->wait($number * self::WAIT);
}
/**
* @Given I wait for the page to complete loading
*/
public function iWaitForPageLoadToComplete() {
$bool_page_load_complete = FALSE;
$counter = 0;
while ((!$bool_page_load_complete) && ($counter < self::TIMEOUT)) {
$page_state = $this->getSession()
->evaluateScript('return window.document.readyState');
if ($page_state == "complete") {
$bool_page_load_complete = TRUE;
}
else {
// Sleep for 1 second between loops.
sleep(self::SECOND_TO_SLEEP);
$counter += 1;
}
}
}
/**
* @Given wait for jquery
* This function will wait for jquery to complete.
*/
public function waitForJquery() {
$this->getSession()->wait(self::TIMEOUT, '(0 === jQuery.active)');
}
/*******************************************************************************
* End of WAITING functions.
*******************************************************************************/
/*******************************************************************************
* Start of ELEMENT functions.
*******************************************************************************/
/**
* @Given I select the :modal modal
*/
public function iSelectTheModal($modal) {
$this->getSession()->switchToIFrame($modal);
}
/**
* @Given I deselect the modal
*/
public function iDeselectTheModal() {
$this->getSession()->switchToIFrame();
}
/**
*/
public function hasFrame($frame) {
$javascript = <<<JS
(function(){
var frame = document.getElementById('$frame');
if (!frame) {
return false;
}
else {
return true;
}
})()
JS;
$result = $this->getSession()->evaluateScript($javascript);
return $result;
}
/**
* @Given I assign an id to the nameless frame :frame and switch to it
* @Given I assign an id to the :number nameless frame :frame and switch to it
*/
public function iAssignIDToANamelessFrame($frame, $number = 0) {
$javascript = <<<JS
(function(){
var elem = document.getElementById('$frame');
var iframes = elem.getElementsByTagName('iframe');
var f = iframes['$number'];
f.id = '$frame';
})()
JS;
$this->getSession()->executeScript($javascript);
}
/**
* @Given I fill in :frame frame with :text
* $parentFrame - the frame that was originally in focus.
* $targetFrameID - the frame to be interacted with.
* $text - the text to be entered into the iframe.
*/
public function iFillInFrameWith($targetFrameID, $text, $modalID = NULL) {
$this->iAssignIDToANamelessFrame($targetFrameID);
// Select a frame.
$this->getSession()->switchToIFrame($targetFrameID);
// Enter text into the frame.
$this->getSession()
->executeScript("document.body.innerHTML = '<p>" . $text . "</p>'");
// Return to parent or modal window.
if ($modalID != NULL) {
// Switch to the main parent window, and re-select the modal.
$this->getSession()->switchToIFrame();
$this->iSelectTheModal($modalID);
}
else {
// Switch to the main parent window.
$this->getSession()->switchToIFrame();
}
}
/**
* @Given I retrieve value from :iframe iframe
* $targetFrameID - the frame to be interacted with.
*/
public function iRetrieveValueFromIFrame($targetFrameID) {
$this->iAssignIDToANamelessFrame($targetFrameID);
// Get inner html from the iframe.
return $this->getSession()
->evaluateScript("return document.body.innerHTML;");
}
/**
* @Given I click element with :class class
* This function allows you to click an element identified by it's class.
*/
public function iClickElementWithClass($class) {
$element = $this->getSession()
->getPage()
->find('xpath', '//*[@class="' . $class . '"]');
if ($element) {
$element->click();
}
else {
throw new CWContextException("The element " . $class . " does not exist");
}
}
/**
* @return string A string containing a random value.
*/
public function replace_value($value) {
$value = str_replace('<number>', $this->randomItems->number, $value);
$value = str_replace('<alpha_number>', $this->randomItems->alphaNumber, $value);
$value = str_replace('<alpha>', $this->randomItems->alpha, $value);
$value = str_replace('<datetime>', date(self::DATE_FORMAT_CONCISE), $value);
return $value;
}
/**
* @Given I fill in :field field by id with :value
*/
public function iFillInFieldByIDWith($field, $value) {
$value = self::replace_value($value);
$element = $this->getSession()->getPage()->findById($field);
if ($element) {
$element->setValue($value);
}
else {
throw new CWContextException("The element with id " . $field . " does not exist");
}
}
/**
* @Given I fill in :field field by name with :value
*/
public function iFillInFieldByNameWith($field, $value) {
$value = self::replace_value($value);
$element = $this->getSession()
->getPage()
->find('data-drupal-selector', $field);
if ($element) {
$element->setValue($value);
}
else {
throw new CWContextException("The element with data-drupal-selector " . $field . " does not exist");
}
}
/**
* @Given I fill in :field field by data drupal selector with :value
*/
public function iFillInFieldByDataDrupalSelectorWith($field, $value) {
$value = self::replace_value($value);
$element = $this->getSession()
->getPage()
->find('xpath', './/*[@data-drupal-selector="' . $field . '"]');
if ($element) {
$element->setValue($value);
}
else {
throw new CWContextException("The element with data-drupal-selector " . $field . " does not exist");
}
}
/**
* @Given I click element with :xpath xpath
* This function allows you to click an element identified by an xpath.
*/
public function iClickElementWithXpath($xpath) {
$element = $this->getSession()->getPage()->find('xpath', $xpath);
if ($element) {
$element->click();
}
else {
throw new CWContextException("The element " . $xpath . " does not exist");
}
}
/**
* @Given I set the value of :field to :value
* This function allows you to set the value of an element
*/
public function iSetTheValueOf($field, $value) {
$element = $this->getSession()->getPage()->findField($field);
if ($element) {
$element->setValue($value);
}
else {
throw new CWContextException("The element " . $field . " does not exist");
}
}
/**
* @Given scroll into view :element
* This function will scroll to a given element - useful for when the element is not visible.
*/
public function scrollIntoView($element_id) {
$function = <<<JS
(function(){
var element = document.getElementById("$element_id");
element.scrollIntoView(true);
})()
JS;
try {
$this->getSession()->executeScript($function);
} catch (Exception $e) {
throw new CWContextException("The scroll into view for element " . $element_id . " did not work");
}
}
/**
* @Given I click on the radiobutton with :label label
*/
public function iClickOnTheRadiobutton($label) {
$session = $this->getSession();
$element = $session->getPage()->find(
'xpath',
$session->getSelectorsHandler()
->selectorToXpath('xpath', "//*[@class='option'][contains(concat(' ', normalize-space(), ' '), ' $label ')]")
);
if (NULL === $element) {
throw new \InvalidArgumentException(sprintf('Cannot find radiobutton: "%s"', $label));
}
$element->click();
}
/**
* @Given I verify the following fields are present:
*
* This function will verify a field exists on a page.
* The function will accept the following field identifiers:
* - id
* - name
* - label
* - class
* - button name
* - checkbox
* - full xpath
*/
public function iVerifyTheFollowingFieldsArePresent(TableNode $fields) {
// Get a DOM of the current page.
$dom = $this->createDOMOfPage();
foreach ($fields->getHash() as $key => $value) {
$identifier = trim($value['IDENTIFIER']);
$field = trim($value['FIELD']);
switch (strtoupper($identifier)) {
case 'ID':
case 'NAME':
case 'CLASS':
$xpath = "//*[@$identifier='$field']";
break;
case 'LABEL':
$xpath = "//" . $identifier . "[text()[contains(.,'$field')]]";
break;
case 'LINK':
$xpath = "//a[text()[contains(.,'$field')]]";
break;
case 'BUTTON':
$xpath = "//input[@type='submit'][@value='$field']";
break;
case 'XPATH':
$xpath = $field;
break;
default:
throw new CWContextException("The identifier $identifier is not valid for this function.");
}
// Get all the nodes matching the xpath and verify the count.
$nodes = $this->getNodesMatchingXpath($dom, $xpath);
if ($nodes->length === 0) {
throw new CWContextException("The field '$field' was not found");
}
}
}
/**
* @Given I verify the field :field is not present
*/
public function iVerifyTheFieldIsNotPresent($field) {
// Get a DOM of the current page.
$dom = $this->createDOMOfPage();
// Get all the assets matching the $field.
$assets = $this->getNodesMatchingXpath($dom, $field);
if ($assets->length >= 1) {
throw new CWContextException("This '{$field}' field was located when it should not have been.");
}
}
/**
* @Given I select a random entry from :dropdown dropdown
* This function will select a random entry from a dropdown
*/
public function iSelectARandomEntryFromDropdown($dropdown) {
$dropdownElement = $this->getSession()->getPage()->findField($dropdown);
// Get an array of all the entries in the dropdown.
$optionElements = $dropdownElement->findAll('xpath', '//option');
// Get count of entries in dropdown.
$count = count($optionElements);
// Assume we do not want the first entry in the array.
// Select a random number from 1 to $count.
$value = rand(1, $count - 1);
// Select a random entry.
$random_value_to_select = $optionElements[$value]->getValue();
// Create xpath string for the dropdown.
$strXpath = "//*[@id='" . $dropdown . "']";
// Select the entry from the dropdown.
$this->getSession()
->getDriver()
->selectOption($strXpath, $random_value_to_select);
}
/**
* @Given I verify that value :value is not present in :dropdown dropdown
*/
public function iVerifyThatValueIsNotPresentInDropdown($value, $dropdown) {
// Get the HTML of the dropdown
$sectionDropDownHTML = $this->minkContext->getSession()
->getPage()
->findById($dropdown)
->getHtml();
// Get all the dropdown options between > and <.
preg_match_all("/\>(.*?)\</", $sectionDropDownHTML, $match);
$dropdownOptions = ($match[1]);
// Check if $value is listed in $dropdownOptions.
if (in_array($value, $dropdownOptions)) {
throw new CWContextException("The value {$value} was present in the dropdown");
}
}
/**
* @Given I verify that value :value is present in :dropdown dropdown
*/
public function iVerifyThatValueIsPresentInDropdown($value, $dropdown) {
// Get the HTML of the dropdown
$sectionDropDownHTML = $this->minkContext->getSession()
->getPage()
->findById($dropdown)
->getHtml();
// Get all the dropdown options between > and <.
preg_match_all("/\>(.*?)\</", $sectionDropDownHTML, $match);
$dropdownOptions = ($match[1]);
// Check if $value is listed in $dropdownOptions.
if (!in_array($value, $dropdownOptions)) {
throw new CWContextException("The value {$value} was not present in the dropdown");
}
}
/*******************************************************************************
* End of ELEMENT functions.
*******************************************************************************/
/*******************************************************************************
* Start of NAVIGATION functions.
*******************************************************************************/
/**
* @Given get the HTTP response code :url
* Anonymous users ONLY.
*/
public function getHTTPResponseCode($url) {
$headers = get_headers($url, 1);
return substr($headers[0], 9, 3);
}
/**
* @Given I check the HTTP response code is :code for :url
*/
public function iCheckTheHttpResponseCodeIsFor($expected_response, $url) {
$path = $this->getMinkParameter('base_url') . $url;
$actual_response = $this->getHTTPResponseCode($path);
$this->verifyResponseForURL($actual_response, $expected_response, $url);
}
/**
* Compare the actual and expected status responses for a URL.
*/
function verifyResponseForURL($actual_response, $expected_response, $url) {
if (intval($actual_response) !== intval($expected_response)) {
throw new CWContextException("This '{$url}' asset returned a {$actual_response} response.");
}
}
/**
* @Given I should get the following HTTP status responses:
*/
public function iShouldGetTheFollowingHTTPStatusResponses(TableNode $table) {
foreach ($table->getRows() as $row) {
$this->getSession()->visit($row[0]);
$this->assertSession()->statusCodeEquals($row[1]);
}
}
/**
* @Given get node id from Edit link
*/
public function getNodeIDFromEDITLink() {
$node_id_url = $this->getSession()
->getPage()
->find("xpath", "//*[@rel='shortlink']")
->getAttribute("href");
$node_id = $this->extractNodeID($node_id_url);
return $node_id;
}
/**
* @Given get Node ID
* This will extract the node id from a URL.
*/
public function extractNodeID($url) {
preg_match('/\d+/', $url, $node_id);
return $node_id[0];
}
/**
* Asserts that a given content type is createable.
* - replaces the default DrupalContext version.
*
* @Then I am able to create a/an :type( content)
*/
public function assertCreateNodeOfType($type) {
$node = (object) array('title' => 'Test Title', 'type' => $type);
$saved = $this->nodeCreate($node);
// Set internal browser on the node edit page.
$url = $this->getMinkParameter('base_url') . '/node/' . $saved->nid;
$this->visitPath($url);
$this->minkContext->assertResponseStatus(200);
}
/**
* Asserts that a given content type is editable.
* - replaces the default DrupalContext version.
*
* @Then I am able to edit a/an :type( content)
*/
public function assertEditNodeOfType($type) {
$node = (object) array('title' => 'Test Title', 'type' => $type);
$saved = $this->nodeCreate($node);
// Set internal browser on the node edit page.
$url = $this->getMinkParameter('base_url') . '/node/' . $saved->nid . '/edit';
$this->visitPath($url);
$this->minkContext->assertResponseStatus(200);
}
/*******************************************************************************
* End of NAVIGATION functions.
*******************************************************************************/
/*******************************************************************************
* Start of REGION functions.
*******************************************************************************/
/**
* @Given I can see :text in the :region region
*/
public function iCanSeeInTheRegion($text, $region) {
$this->minkContext->assertElementContainsText($region, $text);
}
/**
* @Given I cannot see :text in the :region region
*/
public function iCannotSeeInTheRegion($text, $region) {
$this->minkContext->assertElementNotContainsText($region, $text);
}
/**
* @Given I can see the link :link in the :region region
*/
public function iCanSeeTheLinkInTheRegion($link, $region) {
$this->minkContext->assertLinkVisible($link);
$this->minkContext->assertElementContainsText($region, $link);
}
/**
* @Given I cannot see the link :link in the :region region
*/
public function iCannotSeeTheLinkInTheRegion($link, $region) {
$this->minkContext->assertNotLinkVisible($link);
$this->minkContext->assertElementNotContainsText($region, $link);
}
/**
* @Given I can see the vallue :value in the HTML
*/
public function iCanSeeTheValueInTheHTML($value) {
$this->minkContext->assertResponseContains($value);
}
/*******************************************************************************
* End of REGION functions.
*******************************************************************************/
/*******************************************************************************
* Start of ASSET functions.
*******************************************************************************/
/**
* @Given I get the HTML of the page
*
* @return string
*/
public function getHtml() {
if (empty($this->html)) {
$this->html = $this->getSession()->getPage()->getHTML();
}
return $this->html;
}
/**
* @Given I create a DOM object from the HTML of the page
*
* Assume result rows always start with the 'em' tag.
*/
public function createDOMOfPage() {
$dom = new \DOMDocument();
libxml_use_internal_errors(TRUE);
$dom->loadHTML($this->getHtml());
$dom->preserveWhiteSpace = FALSE;
return $dom;
}
/**
* @Given I get nodes matching an xpath
*/
public function getNodesMatchingXpath($dom, $xpath) {
// Create a DOMXpath object.
$xpathDOM = new \DomXPath($dom);
$nodes = $xpathDOM->query($xpath);
return $nodes;
}
/**
* @Given I verify the :asset assets via no JS
* Can be used to validate:
* - Image
* - Script
* - Hyperlink
* - Meta
* - Links
*/
public function iVerifyTheAssetsViaNoJS($assetType) {
// Get a DOM of the current page.
$dom = $this->createDOMOfPage();
// Get xpath of the asset.
$xpath = $this->getXpathForAnAsset($assetType);
// Get all the assets matching the xpath.
$assets = $this->getNodesMatchingXpath($dom, $xpath);
foreach ($assets as $asset) {
$assetToCheck = $asset->nodeValue;
// Check the response for the asset (starting with '//')
if (preg_match('/^\/\//', $assetToCheck, $match)) {
$this->getSession()->visit($assetToCheck);
}
// Check the response for the asset (starting with 'http' or '/')
else {
if (preg_match('/^http|^\//', $assetToCheck, $match)) {
$this->visitPath($assetToCheck);
}
}
// Verify the response status code is 200.
$statusCode = $this->getSession()->getStatusCode();
if ($statusCode !== self::HTTP_200_STATUS) {
throw new CWContextException("This '{$assetType}' asset did not return a 200 response - {$assetToCheck}.");
}
}
}
/**
* @Given I verify the :asset assets via JS
* Can be used to validate:
* - Image
* - Script
* - Hyperlink
*/
public function iVerifyTheAssetsviaJS($assetType) {
// Get a DOM of the current page.
$dom = $this->createDOMOfPage();
// Get xpath of the asset.
$xpath = $this->getXpathForAnAsset($assetType);
// Get all the assets matching the xpath.
$assets = $this->getNodesMatchingXpath($dom, $xpath);
foreach ($assets as $asset) {
$assetToCheck = $asset->nodeValue;
// Check the response for the asset (starting with '//')
if (preg_match('/^\/\//', $assetToCheck, $match)) {
$url = 'http:' . $assetToCheck;
}
// Check the response for the asset (starting with 'http')
elseif (preg_match('/^http/', $assetToCheck, $match)) {
$url = $assetToCheck;
}
// Check the response for the asset (starting with '/')
elseif (preg_match('/^\//', $assetToCheck, $match)) {
$url = $this->getMinkParameter('base_url') . $assetToCheck;
}
else {
// do not check the asset.
break;
}
$this->visitPath($url);
$response = $this->getHTTPResponseCode($url);
$this->verifyResponseForURL($response, self::HTTP_200_STATUS, $url);
}
}
/**
* Get the xpath for an asset
*/
function getXpathForAnAsset($asset) {
switch (strtoupper($asset)) {
case "SCRIPT":
$xpath = "//script/@src";
break;
case "LINK":
$xpath = "//link/@href";
break;
case "META":
$xpath = "//meta/@content";
break;
case "IMAGE":
$xpath = "//img/@src";
break;
case "HYPERLINK":
$xpath = "//a/@href";
break;
default:
throw new CWContextException("This asset '{$asset}' is not a valid value for this test.");
}
return $xpath;
}
/*******************************************************************************
* End of ASSET functions.
*******************************************************************************/
/*******************************************************************************
* Start of OBJECT REPOSITORY functions.
*******************************************************************************/
/**
* @Given I build repository from :page
*
* Visits a page and creates a file in features/bootstrap folder.
*/
public function getObjects($page) {
// Go to page.
$this->visitPath($page);
// Get a DOM of the current page.
$dom = $this->createDOMOfPage();
// Create array of xpath => name for repository building.
$toBuild = [
["//input[@type='submit']", 'BUTTON'],
["//input[@type='text']", 'TEXTFIELD'],
["//input[@type='password']", 'PASSWORD'],
["//input[@type='checkbox']", 'CHECKBOX'],
['//select', 'DROPDOWN']