Repository navigation
Expand file tree
/
Copy pathWebDriver.php
More file actions
1291 lines (1166 loc) · 42.1 KB
/
Copy pathWebDriver.php
File metadata and controls
1291 lines (1166 loc) · 42.1 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 Codeception\Module;
use Codeception\Exception\ElementNotFound;
use Codeception\Exception\TestRuntime;
use Codeception\Util\Locator;
use Codeception\Util\WebInterface;
use Codeception\Util\RemoteInterface;
use Symfony\Component\DomCrawler\Crawler;
use Codeception\PHPUnit\Constraint\WebDriver as WebDriverConstraint;
use Codeception\PHPUnit\Constraint\WebDriverNot as WebDriverConstraintNot;
use Codeception\PHPUnit\Constraint\Page as PageConstraint;
/**
* New generation Selenium2 module.
* *Included in Codeception 1.7.0*
*
* ## Installation
*
* Download [Selenium2 WebDriver](http://code.google.com/p/selenium/downloads/list?q=selenium-server-standalone-2)
* Launch the daemon: `java -jar selenium-server-standalone-2.xx.xxx.jar`
*
* ## Migration Guide (Selenium2 -> WebDriver)
*
* * `wait` method accepts seconds instead of milliseconds. All waits use second as parameter.
*
*
*
* ## Status
*
* * Maintainer: **davert**
* * Stability: **beta**
* * Contact: davert.codecept@mailican.com
* * Based on [facebook php-webdriver](https://github.com/facebook/php-webdriver)
*
* ## Configuration
*
* * url *required* - start url for your app
* * browser *required* - browser that would be launched
* * host - Selenium server host (localhost by default)
* * port - Selenium server port (4444 by default)
* * restart - set to false to share browser sesssion between tests (by default), or set to true to create a session per test
* * wait - set the implicit wait (5 secs) by default.
* * capabilities - sets Selenium2 [desired capabilities](http://code.google.com/p/selenium/wiki/DesiredCapabilities). Should be a key-value array.
*
* ### Example (`acceptance.suite.yml`)
*
* modules:
* enabled: [WebDriver]
* config:
* WebDriver:
* url: 'http://localhost/'
* browser: firefox
* wait: 10
* capabilities:
* unexpectedAlertBehaviour: 'accept'
*
*
* Class WebDriver
* @package Codeception\Module
*/
class WebDriver extends \Codeception\Module implements WebInterface, RemoteInterface {
protected $requiredFields = array('browser', 'url');
protected $config = array(
'host' => '127.0.0.1',
'port' => '4444',
'restart' => false,
'wait' => 5,
'capabilities' => array()
);
protected $wd_host;
protected $capabilities;
protected $test;
/**
* @var \RemoteWebDriver
*/
public $webDriver;
public function _initialize()
{
$this->wd_host = sprintf('http://%s:%s/wd/hub', $this->config['host'], $this->config['port']);
$this->capabilities = $this->config['capabilities'];
$this->capabilities[\WebDriverCapabilityType::BROWSER_NAME] = $this->config['browser'];
$this->webDriver = new \RemoteWebDriver($this->wd_host, $this->capabilities);
$this->webDriver->manage()->timeouts()->implicitlyWait($this->config['wait']);
}
public function _before(\Codeception\TestCase $test)
{
if (!isset($this->webDriver)) {
$this->_initialize();
}
$this->test = $test;
$size = $this->webDriver->manage()->window()->getSize();
$this->debugSection("Window", $size->getWidth().'x'.$size->getHeight());
}
public function _after(\Codeception\TestCase $test)
{
if ($this->config['restart'] && isset($this->webDriver)) {
$this->webDriver->quit();
// \RemoteWebDriver consists of four parts, executor, mouse, keyboard and touch, quit only set executor to null,
// but \RemoteWebDriver doesn't provide public access to check on executor
// so we need to unset $this->webDriver here to shut it down completely
$this->webDriver = null;
}
}
public function _failed(\Codeception\TestCase $test, $fail)
{
$this->_saveScreenshot(\Codeception\Configuration::logDir().basename($test->getFileName()).'.fail.png');
$this->debug("Screenshot was saved into 'log' dir");
}
public function _afterSuite()
{
// this is just to make sure webDriver is cleared after suite
if (isset($this->webDriver)) {
$this->webDriver->quit();
unset($this->webDriver);
}
}
public function _getResponseCode() {}
public function _sendRequest($url) {}
public function amOnSubdomain($subdomain)
{
$url = $this->config['url'];
$url = preg_replace('~(https?:\/\/)(.*\.)(.*\.)~', "$1$3", $url); // removing current subdomain
$url = preg_replace('~(https?:\/\/)(.*)~', "$1$subdomain.$2", $url); // inserting new
$this->_reconfigure(array('url' => $url));
}
public function _getUrl()
{
if (!isset($this->config['url']))
throw new \Codeception\Exception\ModuleConfig(__CLASS__, "Module connection failure. The URL for client can't bre retrieved");
return $this->config['url'];
}
public function _getCurrentUri()
{
$url = $this->webDriver->getCurrentURL();
$parts = parse_url($url);
if (!$parts) $this->fail("URL couldn't be parsed");
$uri = "";
if (isset($parts['path'])) $uri .= $parts['path'];
if (isset($parts['query'])) $uri .= "?".$parts['query'];
if (isset($parts['fragment'])) $uri .= "#".$parts['fragment'];
return $uri;
}
public function _saveScreenshot($filename)
{
$this->webDriver->takeScreenshot($filename);
}
/**
* Makes a screenshot of current window and saves it to `tests/_log/debug`.
*
* ``` php
* <?php
* $I->amOnPage('/user/edit');
* $I->makeScreenshot('edit page');
* // saved to: tests/_log/debug/UserEdit - edit page.png
* ?>
* ```
*
* @param $name
*/
public function makeScreenshot($name)
{
$debugDir = \Codeception\Configuration::logDir().'debug';
if (!is_dir($debugDir)) mkdir($debugDir, 0777);
$caseName = str_replace('Cept.php', '', $this->test->getFileName());
$caseName = str_replace('Cept.php', '', $caseName);
$screenName = $debugDir . DIRECTORY_SEPARATOR . $caseName.' - '.$name.'.png';
$this->_saveScreenshot($screenName);
$this->debug("Screenshot saved to $screenName");
}
/**
* Resize current window
*
* Example:
* ``` php
* <?php
* $I->resizeWindow(800, 600);
*
* ```
*
* @param int $width
* @param int $height
*/
public function resizeWindow($width, $height) {
$this->webDriver->manage()->window()->setSize(new \WebDriverDimension($width, $height));
}
public function seeCookie($cookie)
{
$cookies = $this->webDriver->manage()->getCookies();
$cookies = array_map(function($c) { return $c['name']; }, $cookies);
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
$this->assertContains($cookie, $cookies);
}
public function dontSeeCookie($cookie)
{
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
$this->assertNull($this->webDriver->manage()->getCookieNamed($cookie));
}
public function setCookie($cookie, $value)
{
$this->webDriver->manage()->addCookie(array('name' => $cookie, 'value' => $value));
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
}
public function resetCookie($cookie)
{
$this->webDriver->manage()->deleteCookieNamed($cookie);
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
}
public function grabCookie($cookie)
{
$value = $this->webDriver->manage()->getCookieNamed($cookie);
if (is_array($value)) return $value['value'];
}
public function amOnPage($page)
{
$host = rtrim($this->config['url'], '/');
$page = ltrim($page, '/');
$this->webDriver->get($host . '/' . $page);
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
}
public function see($text, $selector = null)
{
if (!$selector) return $this->assertPageContains($text);
$nodes = $this->match($this->webDriver, $selector);
$this->assertNodesContain($text, $nodes, $selector);
}
public function dontSee($text, $selector = null)
{
if (!$selector) return $this->assertPageNotContains($text);
$nodes = $this->match($this->webDriver, $selector);
$this->assertNodesNotContain($text, $nodes, $selector);
}
public function click($link, $context = null)
{
$page = $this->webDriver;
if ($context) {
$nodes = $this->match($this->webDriver, $context);
if (empty($nodes)) throw new ElementNotFound($context,'CSS or XPath');
$page = reset($nodes);
}
$el = $this->findClickable($page, $link);
if (!$el) {
$els = $this->match($page, $link);
$el = reset($els);
}
if (!$el) throw new ElementNotFound($link, 'Link or Button or CSS or XPath');
$el->click();
}
/**
* @param $page
* @param $link
* @return \WebDriverElement
*/
protected function findClickable($page, $link)
{
$locator = Crawler::xpathLiteral(trim($link));
// narrow
$xpath = Locator::combine(
".//a[normalize-space(.)=$locator]",
".//button[normalize-space(.)=$locator]",
".//a/img[normalize-space(@alt)=$locator]/ancestor::a",
".//input[./@type = 'submit' or ./@type = 'image' or ./@type = 'button'][normalize-space(@value)=$locator]"
);
$els = $page->findElements(\WebDriverBy::xpath($xpath));
if (count($els)) return reset($els);
// wide
$xpath = Locator::combine(
".//a[./@href][((contains(normalize-space(string(.)), $locator)) or .//img[contains(./@alt, $locator)])]",
".//input[./@type = 'submit' or ./@type = 'image' or ./@type = 'button'][contains(./@value, $locator)]",
".//input[./@type = 'image'][contains(./@alt, $locator)]",
".//button[contains(normalize-space(string(.)), $locator)]"
);
$els = $page->findElements(\WebDriverBy::xpath($xpath));
if (count($els)) return reset($els);
return null;
}
/**
* @param $selector
* @return \WebDriverElement
* @throws \Codeception\Exception\ElementNotFound
*/
protected function findField($selector)
{
if ($selector instanceof \WebDriverElement) return $selector;
$locator = Crawler::xpathLiteral(trim($selector));
$xpath = Locator::combine(
".//*[self::input | self::textarea | self::select][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'hidden')][(((./@name = $locator) or ./@id = //label[contains(normalize-space(string(.)), $locator)]/@for) or ./@placeholder = $locator)]",
".//label[contains(normalize-space(string(.)), $locator)]//.//*[self::input | self::textarea | self::select][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'hidden')]"
);
$els = $this->webDriver->findElements(\WebDriverBy::xpath($xpath));
if (count($els)) return reset($els);
$els = $this->match($this->webDriver, $selector);
if (count($els)) return reset($els);
throw new ElementNotFound($selector, "Field by name, label, CSS or XPath");
}
public function seeLink($text, $url = null)
{
$nodes = $this->webDriver->findElements(\WebDriverBy::partialLinkText($text));
if (!$url) return $this->assertNodesContain($text, $nodes, 'a');
$nodes = array_filter($nodes, function(\WebDriverElement $e) use ($url) {
$parts = parse_url($url);
if (!$parts) $this->fail("Link URL of '$url' couldn't be parsed");
$uri = "";
if (isset($parts['path'])) $uri .= $parts['path'];
if (isset($parts['query'])) $uri .= "?".$parts['query'];
if (isset($parts['fragment'])) $uri .= "#".$parts['fragment'];
return $uri == trim($url);
});
$this->assertNodesContain($text, $nodes, "a[href=$url]");
}
public function dontSeeLink($text, $url = null)
{
$nodes = $this->webDriver->findElements(\WebDriverBy::partialLinkText($text));
if (!$url) {
$this->assertNodesNotContain($text, $nodes, 'a');
return;
}
$nodes = array_filter($nodes, function(\WebDriverElement $e) use ($url) {
return trim($e->getAttribute('href')) == trim($url);
});
$this->assertNodesNotContain($text, $nodes, "a[href=$url]");
}
public function seeInCurrentUrl($uri)
{
$this->assertContains($uri, $this->_getCurrentUri());
}
public function seeCurrentUrlEquals($uri)
{
$this->assertEquals($uri, $this->_getCurrentUri());
}
public function seeCurrentUrlMatches($uri)
{
\PHPUnit_Framework_Assert::assertRegExp($uri, $this->_getCurrentUri());
}
public function dontSeeInCurrentUrl($uri)
{
$this->assertNotContains($uri, $this->_getCurrentUri());
}
public function dontSeeCurrentUrlEquals($uri)
{
$this->assertNotEquals($uri, $this->_getCurrentUri());
}
public function dontSeeCurrentUrlMatches($uri)
{
\PHPUnit_Framework_Assert::assertNotRegExp($uri, $this->_getCurrentUri());
}
public function grabFromCurrentUrl($uri = null)
{
if (!$uri) {
return $this->_getCurrentUri();
}
$matches = array();
$res = preg_match($uri, $this->_getCurrentUri(), $matches);
if (!$res) $this->fail("Couldn't match $uri in ".$this->_getCurrentUri());
if (!isset($matches[1])) $this->fail("Nothing to grab. A regex parameter required. Ex: '/user/(\\d+)'");
return $matches[1];
}
public function seeCheckboxIsChecked($checkbox)
{
$this->assertTrue($this->findField($checkbox)->isSelected());
}
public function dontSeeCheckboxIsChecked($checkbox)
{
$this->assertFalse($this->findField($checkbox)->isSelected());
}
public function seeInField($field, $value)
{
$el = $this->findField($field);
if (!$el) throw new ElementNotFound($field, "Field by name, label, CSS or XPath");
$el_value = $el->getTagName() == 'textarea'
? $el->getText()
: $el->getAttribute('value');
$this->assertEquals($value, $el_value);
}
public function dontSeeInField($field, $value)
{
$el = $this->findField($field);
$el_value = $el->getTagName() == 'textarea'
? $el->getText()
: $el->getAttribute('value');
$this->assertNotEquals($value, $el_value);
}
public function selectOption($select, $option)
{
$el = $this->findField($select);
if ($el->getTagName() != 'select') {
$els = $this->matchCheckables($select);
$radio = null;
foreach ($els as $el) {
$radio = $this->findCheckable($el, $option, true);
if ($radio) break;
}
if (!$radio) throw new ElementNotFound($select, "Radiobutton with value or name '$option in");
$radio->click();
return;
}
$wdSelect = new \WebDriverSelect($el);
if ($wdSelect->isMultiple()) {
$wdSelect->deselectAll();
}
if (!is_array($option)) {
$option = array($option);
}
$matched = false;
foreach ($option as $opt) {
try {
$wdSelect->selectByVisibleText($opt);
$matched = true;
} catch (\NoSuchElementWebDriverError $e) {}
}
if ($matched) return;
foreach ($option as $opt) {
try {
$wdSelect->selectByValue($opt);
$matched = true;
} catch (\NoSuchElementWebDriverError $e) {}
}
if ($matched) return;
throw new ElementNotFound(json_encode($option), "Option inside $select matched by name or value");
}
/*
* Unselect an option in a select box
*
*/
public function unselectOption($select, $option)
{
$el = $this->findField($select);
$wdSelect = new \WebDriverSelect($el);
if (!is_array($option)) $option = array($option);
$matched = false;
foreach ($option as $opt) {
try {
$wdSelect->deselectByVisibleText($opt);
$matched = true;
} catch (\NoSuchElementWebDriverError $e) {}
try {
$wdSelect->deselectByValue($opt);
$matched = true;
} catch (\NoSuchElementWebDriverError $e) {}
}
if ($matched) return;
throw new ElementNotFound(json_encode($option), "Option inside $select matched by name or value");
}
/**
* @param $context
* @param $radio_or_checkbox
* @param bool $byValue
* @return mixed|null
*/
protected function findCheckable($context, $radio_or_checkbox, $byValue = false)
{
if ($radio_or_checkbox instanceof \WebDriverElement) return $radio_or_checkbox;
$locator = Crawler::xpathLiteral($radio_or_checkbox);
$xpath = Locator::combine(
"//input[./@type = 'checkbox'][(./@id = //label[contains(normalize-space(string(.)), $locator)]/@for) or ./@placeholder = $locator]",
"//label[contains(normalize-space(string(.)), $locator)]//.//input[./@type = 'checkbox']",
"//input[./@type = 'radio'][(./@id = //label[contains(normalize-space(string(.)), $locator)]/@for) or ./@placeholder = $locator]",
"//label[contains(normalize-space(string(.)), $locator)]//.//input[./@type = 'radio']"
);
if ($byValue) {
$xpath = Locator::combine(
$xpath,
"//input[./@type = 'checkbox'][./@value = $locator]",
"//input[./@type = 'radio'][./@value = $locator]"
);
}
/** @var $context \WebDriverElement **/
$els = $context->findElements(\WebDriverBy::xpath($xpath));
if (count($els)) return reset($els);
$els = $this->match($context, $radio_or_checkbox);
if (count($els)) return reset($els);
return null;
}
protected function matchCheckables($selector)
{
$els = $this->match($this->webDriver, $selector);
if (!count($els)) throw new ElementNotFound($selector, "Element containing radio by CSS or XPath");
return $els;
}
public function checkOption($option)
{
$field = $this->findCheckable($this->webDriver, $option);
if (!$field) throw new ElementNotFound($option, "Checkbox or Radio by Label or CSS or XPath");
if ($field->isSelected()) return;
$field->click();
}
public function uncheckOption($option)
{
$field = $this->findCheckable($this->webDriver, $option);
if (!$field) throw new ElementNotFound($option, "Checkbox by Label or CSS or XPath");
if (!$field->isSelected()) return;
$field->click();
}
public function fillField($field, $value)
{
$el = $this->findField($field);
$el->clear();
$el->sendKeys($value);
}
public function attachFile($field, $filename)
{
$el = $this->findField($field);
$el->sendKeys(\Codeception\Configuration::dataDir().$filename);
}
public function grabTextFrom($cssOrXPathOrRegex)
{
$els = $this->match($this->webDriver, $cssOrXPathOrRegex);
if (count($els)) return $els[0]->getText();
if (@preg_match($cssOrXPathOrRegex, $this->webDriver->getPageSource(), $matches)) return $matches[1];
throw new ElementNotFound($cssOrXPathOrRegex, 'CSS or XPath or Regex');
}
public function grabValueFrom($field)
{
$el = $this->findField($field);
// value of multiple select is the value of the first selected option
if ($el->getTagName() == 'select') {
$select = new \WebDriverSelect($el);
return $select->getFirstSelectedOption()->getAttribute('value');
}
return $el->getAttribute('value');
}
/**
* Checks for a visible element on a page, matching it by CSS or XPath
*
* ``` php
* <?php
* $I->seeElement('.error');
* $I->seeElement('//form/input[1]');
* ?>
* ```
* @param $selector
*/
public function seeElement($selector)
{
$els = array_filter($this->match($this->webDriver, $selector), function(\WebDriverElement $el) {
return $el->isDisplayed();
});
$this->assertNotEmpty($els);
}
/**
* Checks that element is invisible or not present on page.
*
* ``` php
* <?php
* $I->dontSeeElement('.error');
* $I->dontSeeElement('//form/input[1]');
* ?>
* ```
*
* @param $selector
*/
public function dontSeeElement($selector)
{
$els = array_filter($this->match($this->webDriver, $selector), function(\WebDriverElement $el) {
return $el->isDisplayed();
});
$this->assertEmpty($els);
}
/**
* Checks if element exists on a page even it is invisible.
*
* ``` php
* <?php
* $I->seeElementInDOM('//form/input[type=hidden]');
* ?>
* ```
*
* @param $selector
*/
public function seeElementInDOM($selector)
{
$this->assertNotEmpty($this->match($this->webDriver, $selector));
}
/**
* Opposite to `seeElementInDOM`.
*
* @param $selector
*/
public function dontSeeElementInDOM($selector)
{
$this->assertEmpty($this->match($this->webDriver, $selector));
}
public function seeOptionIsSelected($selector, $optionText)
{
$el = $this->findField($selector);
if ($el->getTagName() !== 'select') {
$els = $this->matchCheckables($selector);
foreach ($els as $k => $el) {
$els[$k] = $this->findCheckable($el, $optionText, true);
}
$this->assertNotEmpty(array_filter($els, function($e) { return $e->isSelected(); }));
return;
}
$select = new \WebDriverSelect($el);
$this->assertNodesContain($optionText, $select->getAllSelectedOptions(), 'option');
}
public function dontSeeOptionIsSelected($selector, $optionText)
{
$el = $this->findField($selector);
if ($el->getTagName() !== 'select') {
$els = $this->matchCheckables($selector);
foreach ($els as $k => $el) {
$els[$k] = $this->findCheckable($el, $optionText, true);
}
$this->assertEmpty(array_filter($els, function($e) { return $e->isSelected(); }));
return;
}
$select = new \WebDriverSelect($el);
$this->assertNodesNotContain($optionText, $select->getAllSelectedOptions(), 'option');
}
public function seeInTitle($title)
{
$this->assertContains($title, $this->webDriver->getTitle());
}
public function dontSeeInTitle($title)
{
$this->assertNotContains($title, $this->webDriver->getTitle());
}
/**
* Accepts JavaScript native popup window created by `window.alert`|`window.confirm`|`window.prompt`.
* Don't confuse it with modal windows, created by [various libraries](http://jster.net/category/windows-modals-popups).
*
*/
public function acceptPopup()
{
$this->webDriver->switchTo()->alert()->accept();
}
/**
* Dismisses active JavaScript popup created by `window.alert`|`window.confirm`|`window.prompt`.
*/
public function cancelPopup()
{
$this->webDriver->switchTo()->alert()->dismiss();
}
/**
* Checks that active JavaScript popup created by `window.alert`|`window.confirm`|`window.prompt` contain text.
*
* @param $text
*/
public function seeInPopup($text)
{
$this->assertContains($text, $this->webDriver->switchTo()->alert()->getText());
}
/**
* Enters text into native JavaScript prompt popup created by `window.prompt`.
*
* @param $keys
*/
public function typeInPopup($keys)
{
$this->webDriver->switchTo()->alert()->sendKeys($keys);
}
/**
* Reloads current page
*/
public function reloadPage() {
$this->webDriver->navigate()->refresh();
}
/**
* Moves back in history
*/
public function moveBack() {
$this->webDriver->navigate()->back();
$this->debug($this->_getCurrentUri());
}
/**
* Moves forward in history
*/
public function moveForward() {
$this->webDriver->navigate()->forward();
$this->debug($this->_getCurrentUri());
}
/**
* Submits a form located on page.
* Specify the form by it's css or xpath selector.
* Fill the form fields values as array. Hidden fields can't be accessed.
*
* This command itself triggers the request to form's action.
*
* Examples:
*
* ``` php
* <?php
* $I->submitForm('#login', array('login' => 'davert', 'password' => '123456'));
*
* ```
*
* For sample Sign Up form:
*
* ``` html
* <form action="/sign_up">
* Login: <input type="text" name="user[login]" /><br/>
* Password: <input type="password" name="user[password]" /><br/>
* Do you agree to out terms? <input type="checkbox" name="user[agree]" /><br/>
* Select pricing plan <select name="plan"><option value="1">Free</option><option value="2" selected="selected">Paid</option></select>
* <input type="submit" value="Submit" />
* </form>
* ```
* You can write this:
*
* ``` php
* <?php
* $I->submitForm('#userForm', array('user' => array('login' => 'Davert', 'password' => '123456', 'agree' => true)));
*
* ```
*
* @param $selector
* @param $params
* @throws \Codeception\Exception\ElementNotFound
*/
public function submitForm($selector, $params)
{
$form = $this->match($this->webDriver,$selector);
if (empty($form)) throw new ElementNotFound($selector, "Form via CSS or XPath");
$form = reset($form);
/** @var $form \WebDriverElement **/
foreach ($params as $param => $value) {
if(!is_array($value) && !is_object($value)){
$value=(string)$value;
}
$els = $form->findElements(\WebDriverBy::name($param));
$el = reset($els);
if ($el->getTagName() == 'textarea') $this->fillField($el, $value);
if ($el->getTagName() == 'select') $this->selectOption($el, $value);
if ($el->getTagName() == 'input') {
$type = $el->getAttribute('type');
if ($type == 'text') $this->fillField($el, $value);
if ($type == 'radio' or $type == 'checkbox') {
foreach ($els as $radio) {
if ($radio->getAttribute('value') == $value) $this->checkOption($radio);
}
}
}
}
$this->debugSection('Uri', $form->getAttribute('action') ? $form->getAttribute('action') : $this->_getCurrentUri());
$this->debugSection('Method', $form->getAttribute('method') ? $form->getAttribute('method') : 'GET');
$this->debugSection('Parameters', json_encode($params));
$form->submit();
$this->debugSection('Page', $this->_getCurrentUri());
}
/**
* Waits for element to change or for $timeout seconds to pass. Element "change" is determined
* by a callback function which is called repeatedly until the return value evaluates to true.
*
* ``` php
* <?php
* $I->waitForElementChange('#menu', function(\WebDriverElement $el) {
* return $el->isDisplayed();
* }, 100);
* ?>
* ```
*
* @param $element
* @param \Closure $callback
* @param int $timeout seconds
* @throws \Codeception\Exception\ElementNotFound
*/
public function waitForElementChange($element, \Closure $callback, $timeout = 30)
{
$els = $this->match($this->webDriver, $element);
if (!count($els)) throw new ElementNotFound($element, "CSS or XPath");
$el = reset($els);
$checker = function() use ($el, $callback) {
return $callback($el);
};
$this->webDriver->wait($timeout)->until($checker);
}
/**
* Waits for element to appear on page for $timeout seconds to pass.
* If element not appears, timeout exception is thrown.
*
* ``` php
* <?php
* $I->waitForElement('#agree_button', 30); // secs
* $I->click('#agree_button');
* ?>
* ```
*
* @param $element
* @param int $timeout seconds
* @throws \Exception
*/
public function waitForElement($element, $timeout = 10)
{
$condition = null;
if (Locator::isID($element)) $condition = \WebDriverExpectedCondition::presenceOfElementLocated(\WebDriverBy::id(substr($element, 1)));
if (!$condition and Locator::isCSS($element)) $condition = \WebDriverExpectedCondition::presenceOfElementLocated(\WebDriverBy::cssSelector($element));
if (Locator::isXPath($element)) $condition = \WebDriverExpectedCondition::presenceOfElementLocated(\WebDriverBy::xpath($element));
if (!$condition) throw new \Exception("Only CSS or XPath allowed");
$this->webDriver->wait($timeout)->until($condition);
}
/**
* Waits for text to appear on the page for a specific amount of time.
* Can also be passed a selector to search in.
* If text does not appear, timeout exception is thrown.
*
* ``` php
* <?php
* $I->waitForText('foo', 30); // secs
* $I->waitForText('foo', 30, '.title'); // secs
* ?>
* ```
*
* @param string $text
* @param int $timeout seconds
* @param null $selector
* @throws \Exception
* @internal param string $element
*/
public function waitForText($text, $timeout = 10, $selector = null)
{
$condition = null;
if (!$selector) {
$condition = \WebDriverExpectedCondition::textToBePresentInElement(\WebDriverBy::xpath('//body'), $text);
} else {
if (Locator::isID($selector)) $condition = \WebDriverExpectedCondition::textToBePresentInElement(\WebDriverBy::id(substr($selector, 1)), $text);
if (!$condition and Locator::isCSS($selector)) $condition = \WebDriverExpectedCondition::textToBePresentInElement(\WebDriverBy::cssSelector($selector), $text);
if (Locator::isXPath($selector)) $condition = \WebDriverExpectedCondition::textToBePresentInElement(\WebDriverBy::xpath($selector), $text);
if (!$condition) throw new \Exception("Only CSS or XPath allowed");
}
$this->webDriver->wait($timeout)->until($condition);
}
/**
* Explicit wait.
*
* @param $timeout secs
*/
public function wait($timeout)
{
if ($timeout >= 1000) {
throw new TestRuntime("
Waiting for more then 1000 seconds: 16.6667 mins\n
Please note that wait method accepts number of seconds as parameter.");
}
sleep($timeout);
}
/**
* Low-level API method.
* If Codeception commands are not enough, use Selenium WebDriver methods directly
*
* ``` php
* $I->executeInSelenium(function(\WebDriver $webdriver) {
* $webdriver->get('http://google.com');
* });
* ```
*
* Use [WebDriver Session API](https://github.com/facebook/php-webdriver)
* Not recommended this command too be used on regular basis.
* If Codeception lacks important Selenium methods implement then and submit patches.
*
* @param callable $function
*/
public function executeInSelenium(\Closure $function)
{
return $function($this->webDriver);
}
/**
* Switch to another window identified by its name.
*
* The window can only be identified by its name. If the $name parameter is blank it will switch to the parent window.
*
* Example:
* ``` html
* <input type="button" value="Open window" onclick="window.open('http://example.com', 'another_window')">
* ```
*
* ``` php
* <?php
* $I->click("Open window");
* # switch to another window
* $I->switchToWindow("another_window");
* # switch to parent window
* $I->switchToWindow();
* ?>
* ```
*
* If the window has no name, the only way to access it is via the `executeInSelenium()` method like so:
*
* ```
* <?php
* $I->executeInSelenium(function (\Webdriver $webdriver) {
* $handles=$webDriver->getWindowHandles();
* $last_window = end($handles);
* $webDriver->switchTo()->window($name);
* });
* ?>
* ```
*
* @param string|null $name
*/
public function switchToWindow($name = null) {
$this->webDriver->switchTo()->window($name);
}
/**
* Switch to another frame
*
* Example:
* ``` html
* <iframe name="another_frame" src="http://example.com">
*
* ```
*