-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathMagentoWebDriver.php
1052 lines (949 loc) · 30.6 KB
/
MagentoWebDriver.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
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\Module;
use Codeception\Lib\Actor\Shared\Pause;
use Codeception\Module\WebDriver;
use Codeception\Test\Descriptor;
use Codeception\TestInterface;
use Magento\FunctionalTestingFramework\Allure\AllureHelper;
use Facebook\WebDriver\Interactions\WebDriverActions;
use Codeception\Exception\ModuleConfigException;
use Codeception\Exception\ModuleException;
use Codeception\Util\Uri;
use Codeception\Lib\ModuleContainer;
use Magento\FunctionalTestingFramework\DataTransport\WebApiExecutor;
use Magento\FunctionalTestingFramework\DataTransport\Auth\WebApiAuth;
use Magento\FunctionalTestingFramework\DataTransport\Auth\Tfa\OTP;
use Magento\FunctionalTestingFramework\DataTransport\Protocol\CurlInterface;
use Magento\FunctionalTestingFramework\DataGenerator\Handlers\CredentialStore;
use Magento\FunctionalTestingFramework\Util\Path\UrlFormatter;
use Magento\FunctionalTestingFramework\Util\ConfigSanitizerUtil;
use Yandex\Allure\Adapter\AllureException;
use Magento\FunctionalTestingFramework\DataTransport\Protocol\CurlTransport;
use Yandex\Allure\Adapter\Support\AttachmentSupport;
use Magento\FunctionalTestingFramework\Exceptions\TestFrameworkException;
use Magento\FunctionalTestingFramework\DataGenerator\Handlers\PersistedObjectHandler;
/**
* MagentoWebDriver module provides common Magento web actions through Selenium WebDriver.
*
* Configuration:
*
* ```
* modules:
* enabled:
* - \Magento\FunctionalTestingFramework\Module\MagentoWebDriver
* config:
* \Magento\FunctionalTestingFramework\Module\MagentoWebDriver:
* url: magento_base_url
* backend_name: magento_backend_name
* username: admin_username
* password: admin_password
* browser: chrome
* ```
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessivePublicCount)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class MagentoWebDriver extends WebDriver
{
use AttachmentSupport;
use Pause {
pause as codeceptPause;
}
const MAGENTO_CRON_INTERVAL = 60;
const MAGENTO_CRON_COMMAND = 'cron:run';
/**
* List of known magento loading masks by selector
*
* @var array
*/
protected $loadingMasksLocators = [
'//div[contains(@class, "loading-mask")]',
'//div[contains(@class, "admin_data-grid-loading-mask")]',
'//div[contains(@class, "admin__data-grid-loading-mask")]',
'//div[contains(@class, "admin__form-loading-mask")]',
'//div[@data-role="spinner"]',
];
/**
* The module required fields, to be set in the suite .yml configuration file.
*
* @var array
*/
protected $requiredFields = [
'url',
'backend_name',
'username',
'password',
'browser',
];
/**
* Set all Locale variables to NULL.
*
* @var array $localeAll
*/
protected static $localeAll = [
LC_COLLATE => null,
LC_CTYPE => null,
LC_MONETARY => null,
LC_NUMERIC => null,
LC_TIME => null,
LC_MESSAGES => null,
];
/**
* Current Test Interface
*
* @var TestInterface
*/
private $current_test;
/**
* Png image filepath for current test
*
* @var string
*/
private $pngReport;
/**
* Html filepath for current test
*
* @var string
*/
private $htmlReport;
/**
* Array to store Javascript errors
*
* @var string[]
*/
private $jsErrors = [];
/**
* Contains last execution times for Cron
*
* @var int[]
*/
private $cronExecution = [];
/**
* Sanitizes config, then initializes using parent.
*
* @return void
*/
public function _initialize()
{
$this->config = ConfigSanitizerUtil::sanitizeWebDriverConfig($this->config);
parent::_initialize();
$this->cleanJsError();
}
/**
* Calls parent reset, then re-sanitizes config
*
* @return void
*/
public function _resetConfig()
{
parent::_resetConfig();
$this->config = ConfigSanitizerUtil::sanitizeWebDriverConfig($this->config);
$this->cleanJsError();
}
/**
* Remap parent::_after, called in TestContextExtension
*
* @param TestInterface $test
* @return void
*/
public function _runAfter(TestInterface $test)
{
parent::_after($test); // TODO: Change the autogenerated stub
}
/**
* Override parent::_after to do nothing.
*
* @param TestInterface $test
* @SuppressWarnings(PHPMD)
* @return void
*/
public function _after(TestInterface $test)
{
// DO NOT RESET SESSIONS
}
/**
* Return ModuleContainer
*
* @return ModuleContainer
*/
public function getModuleContainer()
{
return $this->moduleContainer;
}
/**
* Returns URL of a host.
*
* @return mixed
* @throws ModuleConfigException
* @api
*/
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'];
}
/**
* Uri of currently opened page.
*
* @return string
* @throws ModuleException
* @api
*/
public function _getCurrentUri()
{
$url = $this->webDriver->getCurrentURL();
if ($url == 'about:blank') {
throw new ModuleException($this, 'Current url is blank, no page was opened');
}
return Uri::retrieveUri($url);
}
/**
* Assert that the current webdriver url does not equal the expected string.
*
* @param string $url
* @return void
* @throws AllureException
*/
public function dontSeeCurrentUrlEquals($url)
{
$actualUrl = $this->webDriver->getCurrentURL();
$comparison = "Expected: $url\nActual: $actualUrl";
AllureHelper::addAttachmentToCurrentStep($comparison, 'Comparison');
$this->assertNotEquals($url, $actualUrl);
}
/**
* Assert that the current webdriver url does not match the expected regex.
*
* @param string $regex
* @return void
* @throws AllureException
*/
public function dontSeeCurrentUrlMatches($regex)
{
$actualUrl = $this->webDriver->getCurrentURL();
$comparison = "Expected: $regex\nActual: $actualUrl";
AllureHelper::addAttachmentToCurrentStep($comparison, 'Comparison');
$this->assertNotRegExp($regex, $actualUrl);
}
/**
* Assert that the current webdriver url does not contain the expected string.
*
* @param string $needle
* @return void
* @throws AllureException
*/
public function dontSeeInCurrentUrl($needle)
{
$actualUrl = $this->webDriver->getCurrentURL();
$comparison = "Expected: $needle\nActual: $actualUrl";
AllureHelper::addAttachmentToCurrentStep($comparison, 'Comparison');
$this->assertStringNotContainsString($needle, $actualUrl);
}
/**
* Return the current webdriver url or return the first matching capture group.
*
* @param string|null $regex
* @return string
*/
public function grabFromCurrentUrl($regex = null)
{
$fullUrl = $this->webDriver->getCurrentURL();
if (!$regex) {
return $fullUrl;
}
$matches = [];
$res = preg_match($regex, $fullUrl, $matches);
if (!$res) {
$this->fail("Couldn't match $regex in " . $fullUrl);
}
if (!isset($matches[1])) {
$this->fail("Nothing to grab. A regex parameter with a capture group is required. Ex: '/(foo)(bar)/'");
}
return $matches[1];
}
/**
* Assert that the current webdriver url equals the expected string.
*
* @param string $url
* @return void
* @throws AllureException
*/
public function seeCurrentUrlEquals($url)
{
$actualUrl = $this->webDriver->getCurrentURL();
$comparison = "Expected: $url\nActual: $actualUrl";
AllureHelper::addAttachmentToCurrentStep($comparison, 'Comparison');
$this->assertEquals($url, $actualUrl);
}
/**
* Assert that the current webdriver url matches the expected regex.
*
* @param string $regex
* @return void
* @throws AllureException
*/
public function seeCurrentUrlMatches($regex)
{
$actualUrl = $this->webDriver->getCurrentURL();
$comparison = "Expected: $regex\nActual: $actualUrl";
AllureHelper::addAttachmentToCurrentStep($comparison, 'Comparison');
$this->assertRegExp($regex, $actualUrl);
}
/**
* Assert that the current webdriver url contains the expected string.
*
* @param string $needle
* @return void
* @throws AllureException
*/
public function seeInCurrentUrl($needle)
{
$actualUrl = $this->webDriver->getCurrentURL();
$comparison = "Expected: $needle\nActual: $actualUrl";
AllureHelper::addAttachmentToCurrentStep($comparison, 'Comparison');
$this->assertStringContainsString($needle, $actualUrl);
}
/**
* Close admin notification popup windows.
*
* @return void
*/
public function closeAdminNotification()
{
// Cheating here for the minute. Still working on the best method to deal with this issue.
try {
$this->executeJS("jQuery('.modal-popup').remove(); jQuery('.modals-overlay').remove();");
} catch (\Exception $e) {
}
}
/**
* Search for and Select multiple options from a Magento Multi-Select drop down menu.
* e.g. The drop down menu you use to assign Products to Categories.
*
* @param string $select
* @param array $options
* @param boolean $requireAction
* @return void
* @throws \Exception
*/
public function searchAndMultiSelectOption($select, array $options, $requireAction = false)
{
$selectDropdown = $select . ' .action-select.admin__action-multiselect';
$selectSearchText = $select
. ' .admin__action-multiselect-search-wrap>input[data-role="advanced-select-text"]';
$selectSearchResult = $select . ' .admin__action-multiselect-label>span';
$this->waitForPageLoad();
$this->waitForElementVisible($selectDropdown);
$this->click($selectDropdown);
$this->selectMultipleOptions($selectSearchText, $selectSearchResult, $options);
if ($requireAction) {
$selectAction = $select . ' button[class=action-default]';
$this->waitForPageLoad();
$this->click($selectAction);
}
}
/**
* Select multiple options from a drop down using a filter and text field to narrow results.
*
* @param string $selectSearchTextField
* @param string $selectSearchResult
* @param string[] $options
* @return void
* @throws \Exception
*/
public function selectMultipleOptions($selectSearchTextField, $selectSearchResult, array $options)
{
foreach ($options as $option) {
$this->waitForPageLoad();
$this->fillField($selectSearchTextField, '');
$this->waitForPageLoad();
$this->fillField($selectSearchTextField, $option);
$this->waitForPageLoad();
$this->click($selectSearchResult);
}
}
/**
* Wait for all Ajax calls to finish.
*
* @param integer $timeout
* @return void
*/
public function waitForAjaxLoad($timeout = null)
{
$timeout = $timeout ?? $this->_getConfig()['pageload_timeout'];
try {
$this->waitForJS('return !!window.jQuery && window.jQuery.active == 0;', $timeout);
} catch (\Exception $exceptione) {
$this->debug("js never executed, performing {$timeout} second wait.");
$this->wait($timeout);
}
$this->wait(1);
}
/**
* Wait for all JavaScript to finish executing.
*
* @param integer $timeout
* @return void
* @throws \Exception
*/
public function waitForPageLoad($timeout = null)
{
$timeout = $timeout ?? $this->_getConfig()['pageload_timeout'];
$this->waitForJS('return document.readyState == "complete"', $timeout);
$this->waitForAjaxLoad($timeout);
$this->waitForLoadingMaskToDisappear($timeout);
}
/**
* Wait for all visible loading masks to disappear. Gets all elements by mask selector, then loops over them.
*
* @param integer $timeout
* @return void
* @throws \Exception
*/
public function waitForLoadingMaskToDisappear($timeout = null)
{
$timeout = $timeout ?? $this->_getConfig()['pageload_timeout'];
foreach ($this->loadingMasksLocators as $maskLocator) {
// Get count of elements found for looping.
// Elements are NOT useful for interaction, as they cannot be fed to codeception actions.
$loadingMaskElements = $this->_findElements($maskLocator);
for ($i = 1; $i <= count($loadingMaskElements); $i++) {
// Formatting and looping on i as we can't interact elements returned above
// eg. (//div[@data-role="spinner"])[1]
$this->waitForElementNotVisible("({$maskLocator})[{$i}]", $timeout);
}
}
}
/**
* Format input to specified currency in locale specified
* @link https://php.net/manual/en/numberformatter.formatcurrency.php
*
* @param float $value
* @param string $locale
* @param string $currency
* @return string
* @throws TestFrameworkException
*/
public function formatCurrency(float $value, $locale, $currency)
{
$formatter = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
if ($formatter && !empty($formatter)) {
$result = $formatter->formatCurrency($value, $currency);
if ($result) {
return $result;
}
}
throw new TestFrameworkException('Invalid attributes used in formatCurrency.');
}
/**
* Parse float number with thousands_sep.
*
* @param string $floatString
* @return float
*/
public function parseFloat($floatString)
{
$floatString = str_replace(',', '', $floatString);
return floatval($floatString);
}
/**
* @param integer $category
* @param string $locale
* @return void
*/
public function mSetLocale(int $category, $locale)
{
if (self::$localeAll[$category] == $locale) {
return;
}
foreach (self::$localeAll as $c => $l) {
self::$localeAll[$c] = setlocale($c, 0);
}
setlocale($category, $locale);
}
/**
* Reset Locale setting.
*
* @return void
*/
public function mResetLocale()
{
foreach (self::$localeAll as $c => $l) {
if ($l !== null) {
setlocale($c, $l);
self::$localeAll[$c] = null;
}
}
}
/**
* Scroll to the Top of the Page.
*
* @return void
*/
public function scrollToTopOfPage()
{
$this->executeJS('window.scrollTo(0,0);');
}
/**
* Takes given $command and executes it against bin/magento or custom exposed entrypoint. Returns command output.
*
* @param string $command
* @param integer $timeout
* @param string $arguments
* @return string
*
* @throws TestFrameworkException
*/
public function magentoCLI($command, $timeout = null, $arguments = null)
{
// Remove index.php if it's present in url
$baseUrl = rtrim(
str_replace('index.php', '', rtrim($this->config['url'], '/')),
'/'
);
$apiURL = UrlFormatter::format(
$baseUrl . '/' . ltrim(getenv('MAGENTO_CLI_COMMAND_PATH'), '/'),
false
);
$executor = new CurlTransport();
$executor->write(
$apiURL,
[
'token' => WebApiAuth::getAdminToken(),
getenv('MAGENTO_CLI_COMMAND_PARAMETER') => $command,
'arguments' => $arguments,
'timeout' => $timeout,
],
CurlInterface::POST,
[]
);
$response = $executor->read();
$executor->close();
return $response;
}
/**
* Executes Magento Cron keeping the interval (> 60 seconds between each run)
*
* @param string|null $cronGroups
* @param integer|null $timeout
* @param string|null $arguments
* @return string
*/
public function magentoCron($cronGroups = null, $timeout = null, $arguments = null)
{
$cronGroups = explode(' ', $cronGroups);
return $this->executeCronjobs($cronGroups, $timeout, $arguments);
}
/**
* Updates last execution time for Cron
*
* @param array $cronGroups
* @return void
*/
private function notifyCronFinished(array $cronGroups = [])
{
if (empty($cronGroups)) {
$this->cronExecution['*'] = time();
}
foreach ($cronGroups as $group) {
$this->cronExecution[$group] = time();
}
}
/**
* Returns last Cron execution time for specific cron or all crons
*
* @param array $cronGroups
* @return integer
*/
private function getLastCronExecution(array $cronGroups = [])
{
if (empty($this->cronExecution)) {
return 0;
}
if (empty($cronGroups)) {
return (int)max($this->cronExecution);
}
$cronGroups = array_merge($cronGroups, ['*']);
return array_reduce($cronGroups, function ($lastExecution, $group) {
if (isset($this->cronExecution[$group]) && $this->cronExecution[$group] > $lastExecution) {
$lastExecution = $this->cronExecution[$group];
}
return (int)$lastExecution;
}, 0);
}
/**
* Returns time to wait for next run
*
* @param array $cronGroups
* @param integer $cronInterval
* @return integer
*/
private function getCronWait(array $cronGroups = [], int $cronInterval = self::MAGENTO_CRON_INTERVAL)
{
$nextRun = $this->getLastCronExecution($cronGroups) + $cronInterval;
$toNextRun = $nextRun - time();
return max(0, $toNextRun);
}
/**
* Runs DELETE request to delete a Magento entity against the url given.
*
* @param string $url
* @return string
* @throws TestFrameworkException
*/
public function deleteEntityByUrl($url)
{
$executor = new WebApiExecutor(null);
$executor->write($url, [], CurlInterface::DELETE, []);
$response = $executor->read();
$executor->close();
return $response;
}
/**
* Conditional click for an area that should be visible
*
* @param string $selector
* @param string $dependentSelector
* @param boolean $visible
* @return void
* @throws \Exception
*/
public function conditionalClick($selector, $dependentSelector, $visible)
{
$el = $this->_findElements($dependentSelector);
if (sizeof($el) > 1) {
throw new \Exception("more than one element matches selector " . $dependentSelector);
}
$clickCondition = null;
if ($visible) {
$clickCondition = !empty($el) && $el[0]->isDisplayed();
} else {
$clickCondition = empty($el) || !$el[0]->isDisplayed();
}
if ($clickCondition) {
$this->click($selector);
}
}
/**
* Clear the given Text Field or Textarea
*
* @param string $selector
* @return void
*/
public function clearField($selector)
{
$this->fillField($selector, "");
}
/**
* Assert that an element contains a given value for the specific attribute.
*
* @param string $selector
* @param string $attribute
* @param string $value
* @return void
*/
public function assertElementContainsAttribute($selector, $attribute, $value)
{
$attributes = $this->grabAttributeFrom($selector, $attribute);
if (isset($value) && empty($value)) {
// If an "attribute" is blank, "", or null we need to be able to assert that it's present.
// When an "attribute" is blank or null it returns "true" so we assert that "true" is present.
$this->assertEquals($attributes, 'true');
} else {
$this->assertStringContainsString($value, $attributes);
}
}
/**
* Sets current test to the given test, and resets test failure artifacts to null
*
* @param TestInterface $test
* @return void
*/
public function _before(TestInterface $test)
{
$this->current_test = $test;
$this->htmlReport = null;
$this->pngReport = null;
parent::_before($test);
}
/**
* Override for codeception's default dragAndDrop to include offset options.
*
* @param string $source
* @param string $target
* @param integer $xOffset
* @param integer $yOffset
* @return void
*/
public function dragAndDrop($source, $target, $xOffset = null, $yOffset = null)
{
$snodes = $this->matchFirstOrFail($this->baseElement, $source);
$tnodes = $this->matchFirstOrFail($this->baseElement, $target);
$action = new WebDriverActions($this->webDriver);
if ($xOffset !== null || $yOffset !== null) {
$targetX = intval($tnodes->getLocation()->getX() + $xOffset);
$targetY = intval($tnodes->getLocation()->getY() + $yOffset);
$travelX = intval($targetX - $snodes->getLocation()->getX());
$travelY = intval($targetY - $snodes->getLocation()->getY());
$action->moveToElement($snodes);
$action->clickAndHold($snodes);
// Fix Start
$action->moveByOffset(-1, -1);
$action->moveByOffset(1, 1);
// Fix End
$action->moveByOffset($travelX, $travelY);
$action->release()->perform();
} else {
$action->clickAndHold($snodes);
// Fix Start
$action->moveByOffset(-1, -1);
$action->moveByOffset(1, 1);
// Fix End
$action->moveToElement($tnodes);
$action->release($tnodes)->perform();
}
}
/**
* Function used to fill sensitive credentials with user data, data is decrypted immediately prior to fill to avoid
* exposure in console or log.
*
* @param string $field
* @param string $value
* @return void
* @throws TestFrameworkException
*/
public function fillSecretField($field, $value)
{
// to protect any secrets from being printed to console the values are executed only at the webdriver level as a
// decrypted value
$decryptedValue = CredentialStore::getInstance()->decryptSecretValue($value);
if ($decryptedValue === false) {
throw new TestFrameworkException("\nFailed to decrypt value {$value} for field {$field}\n");
}
$this->fillField($field, $decryptedValue);
}
/**
* Function used to create data that contains sensitive credentials in a <createData> <field> override.
* The data is decrypted immediately prior to data creation to avoid exposure in console or log.
*
* @param string $command
* @param null $timeout
* @param null $arguments
* @throws TestFrameworkException
* @return string
*/
public function magentoCLISecret($command, $timeout = null, $arguments = null)
{
// to protect any secrets from being printed to console the values are executed only at the webdriver level as a
// decrypted value
$decryptedCommand = CredentialStore::getInstance()->decryptAllSecretsInString($command);
if ($decryptedCommand === false) {
throw new TestFrameworkException("\nFailed to decrypt magentoCLI command {$command}\n");
}
return $this->magentoCLI($decryptedCommand, $timeout, $arguments);
}
/**
* Override for _failed method in Codeception method. Adds png and html attachments to allure report
* following parent execution of test failure processing.
*
* @param TestInterface $test
* @param \Exception $fail
* @return void
*/
public function _failed(TestInterface $test, $fail)
{
$this->debugWebDriverLogs($test);
if ($this->pngReport === null && $this->htmlReport === null) {
$this->saveScreenshot();
if (getenv('ENABLE_PAUSE') === 'true') {
$this->pause(true);
}
}
if ($this->current_test == null) {
throw new \RuntimeException("Suite condition failure: \n" . $fail->getMessage());
}
$this->addAttachment($this->pngReport, $test->getMetadata()->getName() . '.png', 'image/png');
$this->addAttachment($this->htmlReport, $test->getMetadata()->getName() . '.html', 'text/html');
$this->debug("Failure due to : {$fail->getMessage()}");
$this->debug("Screenshot saved to {$this->pngReport}");
$this->debug("Html saved to {$this->htmlReport}");
}
/**
* Function which saves a screenshot of the current stat of the browser
*
* @return void
*/
public function saveScreenshot()
{
$testDescription = "unknown." . uniqid();
if ($this->current_test != null) {
$testDescription = Descriptor::getTestSignature($this->current_test);
}
$filename = preg_replace('~\W~', '.', $testDescription);
$outputDir = codecept_output_dir();
$this->_saveScreenshot($this->pngReport = $outputDir . mb_strcut($filename, 0, 245, 'utf-8') . '.fail.png');
$this->_savePageSource($this->htmlReport = $outputDir . mb_strcut($filename, 0, 244, 'utf-8') . '.fail.html');
}
/**
* Go to a page and wait for ajax requests to finish
*
* @param string $page
* @return void
* @throws \Exception
*/
public function amOnPage($page)
{
(0 === strpos($page, 'http')) ? parent::amOnUrl($page) : parent::amOnPage($page);
$this->waitForPageLoad();
}
/**
* Clean Javascript errors in internal array
*
* @return void
*/
public function cleanJsError()
{
$this->jsErrors = [];
}
/**
* Save Javascript error message to internal array
*
* @param string $errMsg
* @return void
*/
public function setJsError($errMsg)
{
$this->jsErrors[] = $errMsg;
}
/**
* Get all Javascript errors
*
* @return string
*/
private function getJsErrors()
{
$errors = '';
if (!empty($this->jsErrors)) {
$errors = 'Errors in JavaScript:';
foreach ($this->jsErrors as $jsError) {
$errors .= "\n" . $jsError;
}
}
return $errors;
}
/**
* Verify that there is no JavaScript error in browser logs
*
* @return void
*/
public function dontSeeJsError()
{
$this->assertEmpty($this->jsErrors, $this->getJsErrors());
}
/**
* Takes a screenshot of the current window and saves it to `tests/_output/debug`.
*
* This function is copied over from the original Codeception WebDriver so that we still have visibility of
* the screenshot filename to be passed to the AllureHelper.
*
* @param string $name
* @return void
* @throws AllureException
*/
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->debug("Screenshot saved to $screenName");
AllureHelper::addAttachmentToCurrentStep($screenName, 'Screenshot');
}
/**
* Return OTP based on a shared secret
*
* @return string
* @throws TestFrameworkException
*/
public function getOTP()
{
return OTP::getOTP();
}
/**
* Waits proper amount of time to perform Cron execution
*
* @param array $cronGroups
* @param integer $timeout
* @param string $arguments
* @return string
* @throws TestFrameworkException
*/
private function executeCronjobs($cronGroups, $timeout, $arguments): string
{
$cronGroups = array_filter($cronGroups);
$waitFor = $this->getCronWait($cronGroups);
if ($waitFor) {
$this->wait($waitFor);
}
$command = array_reduce($cronGroups, function ($command, $cronGroup) {