/
WebDriver.php
3363 lines (3127 loc) · 110 KB
/
WebDriver.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
namespace Codeception\Module;
use Codeception\Coverage\Subscriber\LocalServer;
use Codeception\Exception\ConnectionException;
use Codeception\Exception\ElementNotFound;
use Codeception\Exception\MalformedLocatorException;
use Codeception\Exception\ModuleConfigException as ModuleConfigException;
use Codeception\Exception\ModuleException;
use Codeception\Exception\TestRuntimeException;
use Codeception\Lib\Interfaces\ConflictsWithModule;
use Codeception\Lib\Interfaces\ElementLocator;
use Codeception\Lib\Interfaces\MultiSession as MultiSessionInterface;
use Codeception\Lib\Interfaces\PageSourceSaver;
use Codeception\Lib\Interfaces\Remote as RemoteInterface;
use Codeception\Lib\Interfaces\RequiresPackage;
use Codeception\Lib\Interfaces\ScreenshotSaver;
use Codeception\Lib\Interfaces\SessionSnapshot;
use Codeception\Lib\Interfaces\Web as WebInterface;
use Codeception\Module as CodeceptionModule;
use Codeception\PHPUnit\Constraint\Page as PageConstraint;
use Codeception\PHPUnit\Constraint\WebDriver as WebDriverConstraint;
use Codeception\PHPUnit\Constraint\WebDriverNot as WebDriverConstraintNot;
use Codeception\Test\Descriptor;
use Codeception\Test\Interfaces\ScenarioDriven;
use Codeception\TestInterface;
use Codeception\Util\ActionSequence;
use Codeception\Util\Debug;
use Codeception\Util\Locator;
use Codeception\Util\Uri;
use Facebook\WebDriver\Cookie;
use Facebook\WebDriver\Exception\InvalidElementStateException;
use Facebook\WebDriver\Exception\InvalidSelectorException;
use Facebook\WebDriver\Exception\NoSuchElementException;
use Facebook\WebDriver\Exception\UnknownServerException;
use Facebook\WebDriver\Exception\WebDriverCurlException;
use Facebook\WebDriver\Interactions\WebDriverActions;
use Facebook\WebDriver\Remote\LocalFileDetector;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\RemoteWebElement;
use Facebook\WebDriver\Remote\UselessFileDetector;
use Facebook\WebDriver\Remote\WebDriverCapabilityType;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverDimension;
use Facebook\WebDriver\WebDriverElement;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverKeys;
use Facebook\WebDriver\WebDriverSelect;
use GuzzleHttp\Cookie\SetCookie;
use Symfony\Component\DomCrawler\Crawler;
/**
* New generation Selenium WebDriver module.
*
* ## Local Testing
*
* ### Selenium
*
* To run Selenium Server you need [Java](https://www.java.com/) as well as Chrome or Firefox browser installed.
*
* 1. Download [Selenium Standalone Server](http://docs.seleniumhq.org/download/)
* 2. To use Chrome, install [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/getting-started). To use Firefox, install [GeckoDriver](https://github.com/mozilla/geckodriver).
* 3. Launch the Selenium Server: `java -jar selenium-server-standalone-3.xx.xxx.jar`. To locate Chromedriver binary use `-Dwebdriver.chrome.driver=./chromedriver` option. For Geckodriver use `-Dwebdriver.gecko.driver=./geckodriver`.
* 4. Configure this module (in `acceptance.suite.yml`) by setting `url` and `browser`:
*
* ```yaml
* modules:
* enabled:
* - WebDriver:
* url: 'http://localhost/'
* browser: chrome # 'chrome' or 'firefox'
* ```
*
* Launch Selenium Server before executing tests.
*
* ```
* java -jar "/path/to/selenium-server-standalone-xxx.jar"
* ```
*
* ### ChromeDriver
*
* To run tests in Chrome browser you may connect to ChromeDriver directly, without using Selenium Server.
*
* 1. Install [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/getting-started).
* 2. Launch ChromeDriver: `chromedriver --url-base=/wd/hub`
* 3. Configure this module to use ChromeDriver port:
*
* ```yaml
* modules:
* enabled:
* - WebDriver:
* url: 'http://localhost/'
* window_size: false # disabled in ChromeDriver
* port: 9515
* browser: chrome
* capabilities:
* "goog:chromeOptions": # additional chrome options
* ```
*
* Additional [Chrome options](https://sites.google.com/a/chromium.org/chromedriver/capabilities) can be set in `goog:chromeOptions` capabilities. Note that Selenium 3.8 renamed this capability from `chromeOptions` to `goog:chromeOptions`.
*
*
* ### PhantomJS
*
* PhantomJS is a [headless browser](https://en.wikipedia.org/wiki/Headless_browser) alternative to Selenium Server that implements
* [the WebDriver protocol](https://code.google.com/p/selenium/wiki/JsonWireProtocol).
* It allows you to run Selenium tests on a server without a GUI installed.
*
* 1. Download [PhantomJS](http://phantomjs.org/download.html)
* 2. Run PhantomJS in WebDriver mode: `phantomjs --webdriver=4444`
* 3. Configure this module (in `acceptance.suite.yml`) by setting url and `phantomjs` as browser:
*
* ```yaml
* modules:
* enabled:
* - WebDriver:
* url: 'http://localhost/'
* browser: phantomjs
* ```
*
* Since PhantomJS doesn't give you any visual feedback, it's probably a good idea to install [Codeception\Extension\Recorder](http://codeception.com/extensions#CodeceptionExtensionRecorder) which gives you screenshots of how PhantomJS "sees" your pages.
*
* ### Headless Selenium in Docker
*
* Docker can ship Selenium Server with all its dependencies and browsers inside a single container.
* Running tests inside Docker is as easy as pulling [official selenium image](https://github.com/SeleniumHQ/docker-selenium) and starting a container with Chrome:
*
* ```
* docker run --net=host selenium/standalone-chrome
* ```
*
* By using `--net=host` we allow selenium to access local websites.
*
* ## Cloud Testing
*
* Cloud Testing services can run your WebDriver tests in the cloud.
* In case you want to test a local site or site behind a firewall
* you should use a tunnel application provided by a service.
*
* ### SauceLabs
*
* 1. Create an account at [SauceLabs.com](http://SauceLabs.com) to get your username and access key
* 2. In the module configuration use the format `username`:`access_key`@ondemand.saucelabs.com' for `host`
* 3. Configure `platform` under `capabilities` to define the [Operating System](https://docs.saucelabs.com/reference/platforms-configurator/#/)
* 4. run a tunnel app if your site can't be accessed from Internet
*
* ```yaml
* modules:
* enabled:
* - WebDriver:
* url: http://mysite.com
* host: '<username>:<access key>@ondemand.saucelabs.com'
* port: 80
* browser: chrome
* capabilities:
* platform: 'Windows 10'
* ```
*
* ### BrowserStack
*
* 1. Create an account at [BrowserStack](https://www.browserstack.com/) to get your username and access key
* 2. In the module configuration use the format `username`:`access_key`@hub.browserstack.com' for `host`
* 3. Configure `os` and `os_version` under `capabilities` to define the operating System
* 4. If your site is available only locally or via VPN you should use a tunnel app. In this case add `browserstack.local` capability and set it to true.
*
* ```yaml
* modules:
* enabled:
* - WebDriver:
* url: http://mysite.com
* host: '<username>:<access key>@hub.browserstack.com'
* port: 80
* browser: chrome
* capabilities:
* os: Windows
* os_version: 10
* browserstack.local: true # for local testing
* ```
* ### TestingBot
*
* 1. Create an account at [TestingBot](https://testingbot.com/) to get your key and secret
* 2. In the module configuration use the format `key`:`secret`@hub.testingbot.com' for `host`
* 3. Configure `platform` under `capabilities` to define the [Operating System](https://testingbot.com/support/getting-started/browsers.html)
* 4. Run [TestingBot Tunnel](https://testingbot.com/support/other/tunnel) if your site can't be accessed from Internet
*
* ```yaml
* modules:
* enabled:
* - WebDriver:
* url: http://mysite.com
* host: '<key>:<secret>@hub.testingbot.com'
* port: 80
* browser: chrome
* capabilities:
* platform: Windows 10
* ```
*
* ## Configuration
*
* * `url` *required* - Starting URL for your app.
* * `browser` *required* - Browser to launch.
* * `host` - Selenium server host (127.0.0.1 by default).
* * `port` - Selenium server port (4444 by default).
* * `restart` - Set to `false` (default) to use the same browser window for all tests, or set to `true` to create a new window for each test. In any case, when all tests are finished the browser window is closed.
* * `start` - Autostart a browser for tests. Can be disabled if browser session is started with `_initializeSession` inside a Helper.
* * `window_size` - Initial window size. Set to `maximize` or a dimension in the format `640x480`.
* * `clear_cookies` - Set to false to keep cookies, or set to true (default) to delete all cookies between tests.
* * `wait` (default: 0 seconds) - Whenever element is required and is not on page, wait for n seconds to find it before fail.
* * `capabilities` - Sets Selenium [desired capabilities](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities). Should be a key-value array.
* * `connection_timeout` - timeout for opening a connection to remote selenium server (30 seconds by default).
* * `request_timeout` - timeout for a request to return something from remote selenium server (30 seconds by default).
* * `pageload_timeout` - amount of time to wait for a page load to complete before throwing an error (default 0 seconds).
* * `http_proxy` - sets http proxy server url for testing a remote server.
* * `http_proxy_port` - sets http proxy server port
* * `debug_log_entries` - how many selenium entries to print with `debugWebDriverLogs` or on fail (15 by default).
* * `log_js_errors` - Set to true to include possible JavaScript to HTML report, or set to false (default) to deactivate.
*
* Example (`acceptance.suite.yml`)
*
* ```yaml
* modules:
* enabled:
* - WebDriver:
* url: 'http://localhost/'
* browser: firefox
* window_size: 1024x768
* capabilities:
* unexpectedAlertBehaviour: 'accept'
* firefox_profile: '~/firefox-profiles/codeception-profile.zip.b64'
* ```
*
* ## Usage
*
* ### Locating Elements
*
* Most methods in this module that operate on a DOM element (e.g. `click`) accept a locator as the first argument,
* which can be either a string or an array.
*
* If the locator is an array, it should have a single element,
* with the key signifying the locator type (`id`, `name`, `css`, `xpath`, `link`, or `class`)
* and the value being the locator itself.
* This is called a "strict" locator.
* Examples:
*
* * `['id' => 'foo']` matches `<div id="foo">`
* * `['name' => 'foo']` matches `<div name="foo">`
* * `['css' => 'input[type=input][value=foo]']` matches `<input type="input" value="foo">`
* * `['xpath' => "//input[@type='submit'][contains(@value, 'foo')]"]` matches `<input type="submit" value="foobar">`
* * `['link' => 'Click here']` matches `<a href="google.com">Click here</a>`
* * `['class' => 'foo']` matches `<div class="foo">`
*
* Writing good locators can be tricky.
* The Mozilla team has written an excellent guide titled [Writing reliable locators for Selenium and WebDriver tests](https://blog.mozilla.org/webqa/2013/09/26/writing-reliable-locators-for-selenium-and-webdriver-tests/).
*
* If you prefer, you may also pass a string for the locator. This is called a "fuzzy" locator.
* In this case, Codeception uses a a variety of heuristics (depending on the exact method called) to determine what element you're referring to.
* For example, here's the heuristic used for the `submitForm` method:
*
* 1. Does the locator look like an ID selector (e.g. "#foo")? If so, try to find a form matching that ID.
* 2. If nothing found, check if locator looks like a CSS selector. If so, run it.
* 3. If nothing found, check if locator looks like an XPath expression. If so, run it.
* 4. Throw an `ElementNotFound` exception.
*
* Be warned that fuzzy locators can be significantly slower than strict locators.
* Especially if you use Selenium WebDriver with `wait` (aka implicit wait) option.
* In the example above if you set `wait` to 5 seconds and use XPath string as fuzzy locator,
* `submitForm` method will wait for 5 seconds at each step.
* That means 5 seconds finding the form by ID, another 5 seconds finding by CSS
* until it finally tries to find the form by XPath).
* If speed is a concern, it's recommended you stick with explicitly specifying the locator type via the array syntax.
*
* ## Public Properties
*
* * `webDriver` - instance of `\Facebook\WebDriver\Remote\RemoteWebDriver`. Can be accessed from Helper classes for complex WebDriver interactions.
*
* ```php
* // inside Helper class
* $this->getModule('WebDriver')->webDriver->getKeyboard()->sendKeys('hello, webdriver');
* ```
*
*/
class WebDriver extends CodeceptionModule implements
WebInterface,
RemoteInterface,
MultiSessionInterface,
SessionSnapshot,
ScreenshotSaver,
PageSourceSaver,
ElementLocator,
ConflictsWithModule,
RequiresPackage
{
protected $requiredFields = ['browser', 'url'];
protected $config = [
'protocol' => 'http',
'host' => '127.0.0.1',
'port' => '4444',
'path' => '/wd/hub',
'start' => true,
'restart' => false,
'wait' => 0,
'clear_cookies' => true,
'window_size' => false,
'capabilities' => [],
'connection_timeout' => null,
'request_timeout' => null,
'pageload_timeout' => null,
'http_proxy' => null,
'http_proxy_port' => null,
'ssl_proxy' => null,
'ssl_proxy_port' => null,
'debug_log_entries' => 15,
'log_js_errors' => false
];
protected $wdHost;
protected $capabilities;
protected $connectionTimeoutInMs;
protected $requestTimeoutInMs;
protected $test;
protected $sessions = [];
protected $sessionSnapshots = [];
protected $httpProxy;
protected $httpProxyPort;
protected $sslProxy;
protected $sslProxyPort;
/**
* @var RemoteWebDriver
*/
public $webDriver;
/**
* @var RemoteWebElement
*/
protected $baseElement;
public function _requires()
{
return ['Facebook\WebDriver\Remote\RemoteWebDriver' => '"facebook/webdriver": "^1.0.1"'];
}
/**
* @return RemoteWebElement
* @throws ModuleException
*/
protected function getBaseElement()
{
if (!$this->baseElement) {
throw new ModuleException($this, "Page not loaded. Use `\$I->amOnPage` (or hidden API methods `_request` and `_loadPage`) to open it");
}
return $this->baseElement;
}
public function _initialize()
{
$this->wdHost = sprintf('%s://%s:%s%s', $this->config['protocol'], $this->config['host'], $this->config['port'], $this->config['path']);
$this->capabilities = $this->config['capabilities'];
$this->capabilities[WebDriverCapabilityType::BROWSER_NAME] = $this->config['browser'];
if ($proxy = $this->getProxy()) {
$this->capabilities[WebDriverCapabilityType::PROXY] = $proxy;
}
$this->connectionTimeoutInMs = $this->config['connection_timeout'] * 1000;
$this->requestTimeoutInMs = $this->config['request_timeout'] * 1000;
$this->loadFirefoxProfile();
}
/**
* Change capabilities of WebDriver. Should be executed before starting a new browser session.
* This method expects a function to be passed which returns array or [WebDriver Desired Capabilities](https://github.com/facebook/php-webdriver/blob/community/lib/Remote/DesiredCapabilities.php) object.
* Additional [Chrome options](https://github.com/facebook/php-webdriver/wiki/ChromeOptions) (like adding extensions) can be passed as well.
*
* ```php
* <?php // in helper
* public function _before(TestInterface $test)
* {
* $this->getModule('WebDriver')->_capabilities(function($currentCapabilities) {
* // or new \Facebook\WebDriver\Remote\DesiredCapabilities();
* return \Facebook\WebDriver\Remote\DesiredCapabilities::firefox();
* });
* }
* ```
*
* to make this work load `\Helper\Acceptance` before `WebDriver` in `acceptance.suite.yml`:
*
* ```yaml
* modules:
* enabled:
* - \Helper\Acceptance
* - WebDriver
* ```
*
* For instance, [**BrowserStack** cloud service](https://www.browserstack.com/automate/capabilities) may require a test name to be set in capabilities.
* This is how it can be done via `_capabilities` method from `Helper\Acceptance`:
*
* ```php
* <?php // inside Helper\Acceptance
* public function _before(TestInterface $test)
* {
* $name = $test->getMetadata()->getName();
* $this->getModule('WebDriver')->_capabilities(function($currentCapabilities) use ($name) {
* $currentCapabilities['name'] = $name;
* return $currentCapabilities;
* });
* }
* ```
* In this case, please ensure that `\Helper\Acceptance` is loaded before WebDriver so new capabilities could be applied.
*
* @api
* @param \Closure $capabilityFunction
*/
public function _capabilities(\Closure $capabilityFunction)
{
$this->capabilities = $capabilityFunction($this->capabilities);
}
public function _conflicts()
{
return 'Codeception\Lib\Interfaces\Web';
}
public function _before(TestInterface $test)
{
if (!isset($this->webDriver) && $this->config['start']) {
$this->_initializeSession();
}
$this->setBaseElement();
$test->getMetadata()->setCurrent(
[
'browser' => $this->webDriver->getCapabilities()->getBrowserName(),
'capabilities' => $this->webDriver->getCapabilities()->toArray(),
]
);
}
/**
* Restarts a web browser.
* Can be used with `_reconfigure` to open browser with different configuration
*
* ```php
* <?php
* // inside a Helper
* $this->getModule('WebDriver')->_restart(); // just restart
* $this->getModule('WebDriver')->_restart(['browser' => $browser]); // reconfigure + restart
* ```
*
* @param array $config
* @api
*/
public function _restart($config = [])
{
$this->webDriver->quit();
if (!empty($config)) {
$this->_reconfigure($config);
}
$this->_initializeSession();
}
protected function onReconfigure()
{
$this->_initialize();
}
protected function loadFirefoxProfile()
{
if (!array_key_exists('firefox_profile', $this->config['capabilities'])) {
return;
}
$firefox_profile = $this->config['capabilities']['firefox_profile'];
if (file_exists($firefox_profile) === false) {
throw new ModuleConfigException(
__CLASS__,
"Firefox profile does not exist under given path " . $firefox_profile
);
}
// Set firefox profile as capability
$this->capabilities['firefox_profile'] = file_get_contents($firefox_profile);
}
protected function initialWindowSize()
{
if ($this->config['window_size'] == 'maximize') {
$this->maximizeWindow();
return;
}
$size = explode('x', $this->config['window_size']);
if (count($size) == 2) {
$this->resizeWindow(intval($size[0]), intval($size[1]));
}
}
public function _after(TestInterface $test)
{
if ($this->config['restart']) {
$this->stopAllSessions();
return;
}
if ($this->config['clear_cookies'] && isset($this->webDriver)) {
try {
$this->webDriver->manage()->deleteAllCookies();
} catch (\Exception $e) {
// may cause fatal errors when not handled
$this->debug("Error, can't clean cookies after a test: " . $e->getMessage());
}
}
}
public function _failed(TestInterface $test, $fail)
{
$this->debugWebDriverLogs($test);
$filename = preg_replace('~\W~', '.', Descriptor::getTestSignatureUnique($test));
$outputDir = codecept_output_dir();
$this->_saveScreenshot($report = $outputDir . mb_strcut($filename, 0, 245, 'utf-8') . '.fail.png');
$test->getMetadata()->addReport('png', $report);
$this->_savePageSource($report = $outputDir . mb_strcut($filename, 0, 244, 'utf-8') . '.fail.html');
$test->getMetadata()->addReport('html', $report);
$this->debug("Screenshot and page source were saved into '$outputDir' dir");
}
/**
* Print out latest Selenium Logs in debug mode
*
* @param \Codeception\TestInterface $test
*/
public function debugWebDriverLogs(TestInterface $test = null)
{
if (!isset($this->webDriver)) {
$this->debug('WebDriver::debugWebDriverLogs method has been called when webDriver is not set');
return;
}
try {
// Dump out latest Selenium logs
$logs = $this->webDriver->manage()->getAvailableLogTypes();
foreach ($logs as $logType) {
$logEntries = array_slice(
$this->webDriver->manage()->getLog($logType),
-$this->config['debug_log_entries']
);
if (empty($logEntries)) {
$this->debugSection("Selenium {$logType} Logs", " EMPTY ");
continue;
}
$this->debugSection("Selenium {$logType} Logs", "\n" . $this->formatLogEntries($logEntries));
if ($logType === 'browser' && $this->config['log_js_errors']
&& ($test instanceof ScenarioDriven)
) {
$this->logJSErrors($test, $logEntries);
}
}
} catch (\Exception $e) {
$this->debug('Unable to retrieve Selenium logs : ' . $e->getMessage());
}
}
/**
* Turns an array of log entries into a human-readable string.
* Each log entry is an array with the keys "timestamp", "level", and "message".
* See https://code.google.com/p/selenium/wiki/JsonWireProtocol#Log_Entry_JSON_Object
*
* @param array $logEntries
* @return string
*/
protected function formatLogEntries(array $logEntries)
{
$formattedLogs = '';
foreach ($logEntries as $logEntry) {
// Timestamp is in milliseconds, but date() requires seconds.
$time = date('H:i:s', $logEntry['timestamp'] / 1000) .
// Append the milliseconds to the end of the time string
'.' . ($logEntry['timestamp'] % 1000);
$formattedLogs .= "{$time} {$logEntry['level']} - {$logEntry['message']}\n";
}
return $formattedLogs;
}
/**
* Logs JavaScript errors as comments.
*
* @param ScenarioDriven $test
* @param array $browserLogEntries
*/
protected function logJSErrors(ScenarioDriven $test, array $browserLogEntries)
{
foreach ($browserLogEntries as $logEntry) {
if (true === isset($logEntry['level'])
&& true === isset($logEntry['message'])
&& $this->isJSError($logEntry['level'], $logEntry['message'])
) {
// Timestamp is in milliseconds, but date() requires seconds.
$time = date('H:i:s', $logEntry['timestamp'] / 1000) .
// Append the milliseconds to the end of the time string
'.' . ($logEntry['timestamp'] % 1000);
$test->getScenario()->comment("{$time} {$logEntry['level']} - {$logEntry['message']}");
}
}
}
/**
* Determines if the log entry is an error.
* The decision is made depending on browser and log-level.
*
* @param string $logEntryLevel
* @param string $message
* @return bool
*/
protected function isJSError($logEntryLevel, $message)
{
return
(
($this->isPhantom() && $logEntryLevel != 'INFO') // phantomjs logs errors as "WARNING"
|| $logEntryLevel === 'SEVERE' // other browsers log errors as "SEVERE"
)
&& strpos($message, 'ERR_PROXY_CONNECTION_FAILED') === false; // ignore blackhole proxy
}
public function _afterSuite()
{
// this is just to make sure webDriver is cleared after suite
$this->stopAllSessions();
}
protected function stopAllSessions()
{
foreach ($this->sessions as $session) {
$this->_closeSession($session);
}
$this->webDriver = null;
$this->baseElement = null;
}
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(['url' => $url]);
}
/**
* Returns URL of a host.
*
* @api
* @return mixed
* @throws ModuleConfigException
*/
public function _getUrl()
{
if (!isset($this->config['url'])) {
throw new ModuleConfigException(
__CLASS__,
"Module connection failure. The URL for client can't bre retrieved"
);
}
return $this->config['url'];
}
protected function getProxy()
{
$proxyConfig = [];
if ($this->config['http_proxy']) {
$proxyConfig['httpProxy'] = $this->config['http_proxy'];
if ($this->config['http_proxy_port']) {
$proxyConfig['httpProxy'] .= ':' . $this->config['http_proxy_port'];
}
}
if ($this->config['ssl_proxy']) {
$proxyConfig['sslProxy'] = $this->config['ssl_proxy'];
if ($this->config['ssl_proxy_port']) {
$proxyConfig['sslProxy'] .= ':' . $this->config['ssl_proxy_port'];
}
}
if (!empty($proxyConfig)) {
$proxyConfig['proxyType'] = 'manual';
return $proxyConfig;
}
return null;
}
/**
* Uri of currently opened page.
* @return string
* @api
* @throws ModuleException
*/
public function _getCurrentUri()
{
$url = $this->webDriver->getCurrentURL();
if ($url == 'about:blank' || strpos($url, 'data:') === 0) {
throw new ModuleException($this, 'Current url is blank, no page was opened');
}
return Uri::retrieveUri($url);
}
public function _saveScreenshot($filename)
{
if (!isset($this->webDriver)) {
$this->debug('WebDriver::_saveScreenshot method has been called when webDriver is not set');
return;
}
try {
$this->webDriver->takeScreenshot($filename);
} catch (\Exception $e) {
$this->debug('Unable to retrieve screenshot from Selenium : ' . $e->getMessage());
return;
}
}
public function _findElements($locator)
{
return $this->match($this->webDriver, $locator);
}
/**
* Saves HTML source of a page to a file
* @param $filename
*/
public function _savePageSource($filename)
{
if (!isset($this->webDriver)) {
$this->debug('WebDriver::_savePageSource method has been called when webDriver is not set');
return;
}
try {
file_put_contents($filename, $this->webDriver->getPageSource());
} catch (\Exception $e) {
$this->debug('Unable to retrieve source page from Selenium : ' . $e->getMessage());
}
}
/**
* Takes a screenshot of the current window and saves it to `tests/_output/debug`.
*
* ``` php
* <?php
* $I->amOnPage('/user/edit');
* $I->makeScreenshot('edit_page');
* // saved to: tests/_output/debug/edit_page.png
* $I->makeScreenshot();
* // saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.png
* ```
*
* @param $name
*/
public function makeScreenshot($name = null)
{
if (empty($name)) {
$name = uniqid(date("Y-m-d_H-i-s_"));
}
$debugDir = codecept_log_dir() . 'debug';
if (!is_dir($debugDir)) {
mkdir($debugDir, 0777);
}
$screenName = $debugDir . DIRECTORY_SEPARATOR . $name . '.png';
$this->_saveScreenshot($screenName);
$this->debugSection('Screenshot Saved', "file://$screenName");
}
public function makeHtmlSnapshot($name = null)
{
if (empty($name)) {
$name = uniqid(date("Y-m-d_H-i-s_"));
}
$debugDir = codecept_output_dir() . 'debug';
if (!is_dir($debugDir)) {
mkdir($debugDir, 0777);
}
$fileName = $debugDir . DIRECTORY_SEPARATOR . $name . '.html';
$this->_savePageSource($fileName);
$this->debugSection('Snapshot Saved', "file://$fileName");
}
/**
* Resize the current window.
*
* ``` 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, array $params = [])
{
$cookies = $this->filterCookies($this->webDriver->manage()->getCookies(), $params);
$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, array $params = [])
{
$cookies = $this->filterCookies($this->webDriver->manage()->getCookies(), $params);
$cookies = array_map(
function ($c) {
return $c['name'];
},
$cookies
);
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
$this->assertNotContains($cookie, $cookies);
}
public function setCookie($cookie, $value, array $params = [])
{
$params['name'] = $cookie;
$params['value'] = $value;
if (isset($params['expires'])) { // PhpBrowser compatibility
$params['expiry'] = $params['expires'];
}
if (!isset($params['domain'])) {
$urlParts = parse_url($this->config['url']);
if (isset($urlParts['host'])) {
$params['domain'] = $urlParts['host'];
}
}
// #5401 Supply defaults, otherwise chromedriver 2.46 complains.
$defaults = [
'path' => '/',
'expiry' => time() + 86400,
'secure' => false,
'httpOnly' => false,
];
foreach ($defaults as $key => $default) {
if (empty($params[$key])) {
$params[$key] = $default;
}
}
$this->webDriver->manage()->addCookie($params);
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
}
public function resetCookie($cookie, array $params = [])
{
$this->webDriver->manage()->deleteCookieNamed($cookie);
$this->debugSection('Cookies', json_encode($this->webDriver->manage()->getCookies()));
}
public function grabCookie($cookie, array $params = [])
{
$params['name'] = $cookie;
$cookies = $this->filterCookies($this->webDriver->manage()->getCookies(), $params);
if (empty($cookies)) {
return null;
}
$cookie = reset($cookies);
return $cookie['value'];
}
/**
* Grabs current page source code.
*
* @throws ModuleException if no page was opened.
*
* @return string Current page source code.
*/
public function grabPageSource()
{
// Make sure that some page was opened.
$this->_getCurrentUri();
return $this->webDriver->getPageSource();
}
protected function filterCookies($cookies, $params = [])
{
foreach (['domain', 'path', 'name'] as $filter) {
if (!isset($params[$filter])) {
continue;
}
$cookies = array_filter(
$cookies,
function ($item) use ($filter, $params) {
return $item[$filter] == $params[$filter];
}
);
}
return $cookies;
}
public function amOnUrl($url)
{
$host = Uri::retrieveHost($url);
$this->_reconfigure(['url' => $host]);
$this->debugSection('Host', $host);
$this->webDriver->get($url);
}
public function amOnPage($page)
{
$url = Uri::appendPath($this->config['url'], $page);
$this->debugSection('GET', $url);
$this->webDriver->get($url);
}
public function see($text, $selector = null)
{
if (!$selector) {
return $this->assertPageContains($text);
}
$this->enableImplicitWait();
$nodes = $this->matchVisible($selector);
$this->disableImplicitWait();
$this->assertNodesContain($text, $nodes, $selector);
}
public function dontSee($text, $selector = null)
{
if (!$selector) {
return $this->assertPageNotContains($text);
}
$nodes = $this->matchVisible($selector);
$this->assertNodesNotContain($text, $nodes, $selector);
}
public function seeInSource($raw)
{
$this->assertPageSourceContains($raw);
}
public function dontSeeInSource($raw)
{
$this->assertPageSourceNotContains($raw);
}
/**
* Checks that the page source contains the given string.
*
* ```php
* <?php
* $I->seeInPageSource('<link rel="apple-touch-icon"');
* ```
*
* @param $text
*/
public function seeInPageSource($text)
{
$this->assertThat(
$this->webDriver->getPageSource(),
new PageConstraint($text, $this->_getCurrentUri()),
''
);
}
/**
* Checks that the page source doesn't contain the given string.
*
* @param $text
*/
public function dontSeeInPageSource($text)
{
$this->assertThatItsNot(
$this->webDriver->getPageSource(),
new PageConstraint($text, $this->_getCurrentUri()),
''
);
}
public function click($link, $context = null)
{
$page = $this->webDriver;
if ($context) {
$page = $this->matchFirstOrFail($this->webDriver, $context);
}
$el = $this->_findClickable($page, $link);
if (!$el) { // check one more time if this was a CSS selector we didn't match
try {
$els = $this->match($page, $link);
} catch (MalformedLocatorException $e) {
throw new ElementNotFound("name=$link", "'$link' is invalid CSS and XPath selector and Link or Button");
}
$el = reset($els);
}
if (!$el) {
throw new ElementNotFound($link, 'Link or Button or CSS or XPath');
}
$el->click();
}
/**