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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
|
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Tests\Selenium;
use Closure;
use Exception;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Exception\InvalidSelectorException;
use Facebook\WebDriver\Exception\NoSuchElementException;
use Facebook\WebDriver\Exception\WebDriverException;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\RemoteWebElement;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverElement;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverSelect;
use InvalidArgumentException;
use PHPUnit\Framework\SkippedTest;
use PHPUnit\Framework\TestCase;
use Throwable;
use function curl_close;
use function curl_errno;
use function curl_error;
use function curl_exec;
use function curl_init;
use function curl_setopt;
use function current;
use function end;
use function file_put_contents;
use function getenv;
use function is_bool;
use function is_string;
use function json_decode;
use function json_encode;
use function mb_strtolower;
use function mb_substr;
use function mt_getrandmax;
use function preg_match;
use function random_int;
use function reset;
use function sha1;
use function sprintf;
use function strlen;
use function substr;
use function time;
use function trim;
use function usleep;
use const CURLOPT_CUSTOMREQUEST;
use const CURLOPT_HTTPHEADER;
use const CURLOPT_POSTFIELDS;
use const CURLOPT_RETURNTRANSFER;
use const CURLOPT_URL;
use const CURLOPT_USERPWD;
use const DIRECTORY_SEPARATOR;
use const JSON_PRETTY_PRINT;
use const JSON_UNESCAPED_SLASHES;
use const PHP_EOL;
abstract class TestBase extends TestCase
{
/** @var RemoteWebDriver */
protected $webDriver;
/**
* Name of database for the test
*
* @var string
*/
public $databaseName;
/**
* The session Id (Browserstack)
*
* @var string
*/
protected $sessionId;
/**
* The window handle for the SQL tab
*
* @var string|null
*/
private $sqlWindowHandle = null;
private const SESSION_REST_URL = 'https://api.browserstack.com/automate/sessions/';
/**
* Create a test database for this test class
*
* @var bool
*/
protected static $createDatabase = true;
/**
* Did the test create the phpMyAdmin storage database ?
*
* @var bool
*/
private $hadStorageDatabaseInstall = false;
/**
* Configures the selenium and database link.
*
* @throws Exception
*/
protected function setUp(): void
{
/**
* Needs to be implemented
*
* @ENV TESTSUITE_SELENIUM_COVERAGE
* @ENV TESTSUITE_FULL
*/
parent::setUp();
if ($this->getHubUrl() === '') {
$this->markTestSkipped('Selenium testing is not configured.');
}
if ($this->getTestSuiteUrl() === '') {
$this->markTestSkipped('The ENV "TESTSUITE_URL" is not defined.');
}
if ($this->getTestSuiteUserLogin() === '') {
//TODO: handle config mode
$this->markTestSkipped(
'The ENV "TESTSUITE_USER" is not defined, you may also want to define "TESTSUITE_PASSWORD".'
);
}
$capabilities = $this->getCapabilities();
$this->addCapabilities($capabilities);
$url = $this->getHubUrl();
$this->webDriver = RemoteWebDriver::create($url, $capabilities);
// The session Id is only used by BrowserStack
if ($this->hasBrowserstackConfig()) {
$this->sessionId = $this->webDriver->getSessionID();
}
$this->navigateTo('');
$this->webDriver->manage()->window()->maximize();
if (! static::$createDatabase) {
// Stop here, we where not asked to create a database
return;
}
$this->createDatabase();
}
/**
* Create a test database
*/
protected function createDatabase(): void
{
$this->databaseName = $this->getDbPrefix() . mb_substr(sha1((string) random_int(0, mt_getrandmax())), 0, 7);
$this->dbQuery(
'CREATE DATABASE IF NOT EXISTS `' . $this->databaseName . '`; USE `' . $this->databaseName . '`;'
);
static::$createDatabase = true;
}
public function getDbPrefix(): string
{
$envVar = getenv('TESTSUITE_DATABASE_PREFIX');
if ($envVar) {
return $envVar;
}
return '';
}
private function getBrowserStackCredentials(): string
{
return (string) getenv('TESTSUITE_BROWSERSTACK_USER') . ':' . (string) getenv('TESTSUITE_BROWSERSTACK_KEY');
}
protected function getTestSuiteUserLogin(): string
{
$user = getenv('TESTSUITE_USER');
return $user === false ? '' : $user;
}
protected function getTestSuiteUserPassword(): string
{
$user = getenv('TESTSUITE_PASSWORD');
return $user === false ? '' : $user;
}
protected function getTestSuiteUrl(): string
{
$user = getenv('TESTSUITE_URL');
return $user === false ? '' : $user;
}
/**
* Has CI config ( CI_MODE == selenium )
*/
public function hasCIConfig(): bool
{
$mode = getenv('CI_MODE');
if (empty($mode)) {
return false;
}
return $mode === 'selenium';
}
/**
* Has ENV variables set for Browserstack
*/
public function hasBrowserstackConfig(): bool
{
return ! empty(getenv('TESTSUITE_BROWSERSTACK_USER'))
&& ! empty(getenv('TESTSUITE_BROWSERSTACK_KEY'));
}
/**
* Has ENV variables set for local Selenium server
*/
public function hasSeleniumConfig(): bool
{
return ! empty(getenv('TESTSUITE_SELENIUM_HOST'))
&& ! empty(getenv('TESTSUITE_SELENIUM_PORT'));
}
/**
* Get the selenium hub url
*/
private function getHubUrl(): string
{
if ($this->hasBrowserstackConfig()) {
return 'https://'
. $this->getBrowserStackCredentials() .
'@hub-cloud.browserstack.com/wd/hub';
}
if ($this->hasSeleniumConfig()) {
return 'http://'
. (string) getenv('TESTSUITE_SELENIUM_HOST') . ':'
. (string) getenv('TESTSUITE_SELENIUM_PORT') . '/wd/hub';
}
return '';
}
/**
* Navigate to URL
*
* @param string $url The URL
*/
private function navigateTo(string $url): void
{
$suiteUrl = getenv('TESTSUITE_URL');
if ($suiteUrl === false) {
$suiteUrl = '';
}
if (substr($suiteUrl, -1) === '/') {
$url = $suiteUrl . $url;
} else {
$url = $suiteUrl . '/' . $url;
}
$this->webDriver->get($url);
}
/**
* Get the current running test name
*
* Usefull for browserstack
*
* @see https://github.com/phpmyadmin/phpmyadmin/pull/14595#issuecomment-418541475
* Reports the name of the test to browserstack
*/
public function getTestName(): string
{
$className = substr(static::class, strlen('PhpMyAdmin\Tests\Selenium\\'));
return $className . ': ' . $this->getName();
}
/**
* Add specific capabilities
*
* @param DesiredCapabilities $capabilities The capabilities object
*/
public function addCapabilities(DesiredCapabilities $capabilities): void
{
$buildLocal = true;
$buildId = 'Manual';
$projectName = 'phpMyAdmin';
$buildTagEnv = getenv('BUILD_TAG');
$githubActionEnv = getenv('GITHUB_ACTION');
if ($buildTagEnv) {
$buildId = $buildTagEnv;
$buildLocal = false;
$projectName = 'phpMyAdmin (Jenkins)';
} elseif ($githubActionEnv) {
$buildId = 'github-' . $githubActionEnv;
$buildLocal = true;
$projectName = 'phpMyAdmin (GitHub - Actions)';
}
if (! $buildLocal) {
return;
}
$capabilities->setCapability(
'bstack:options',
[
'os' => 'Windows',
'osVersion' => '10',
'resolution' => '1920x1080',
'projectName' => $projectName,
'sessionName' => $this->getTestName(),
'buildName' => $buildId,
'localIdentifier' => $buildId,
'local' => $buildLocal,
'debug' => false,
'consoleLogs' => 'verbose',
'networkLogs' => true,
]
);
}
/**
* Get basic capabilities
*/
public function getCapabilities(): DesiredCapabilities
{
switch (getenv('TESTSUITE_SELENIUM_BROWSER')) {
case 'chrome':
default:
$capabilities = DesiredCapabilities::chrome();
$chromeOptions = new ChromeOptions();
$chromeOptions->addArguments(['--lang=en']);
$capabilities->setCapability(ChromeOptions::CAPABILITY_W3C, $chromeOptions);
$capabilities->setCapability(
'loggingPrefs',
['browser' => 'ALL']
);
if ($this->hasCIConfig() && $this->hasBrowserstackConfig()) {
$capabilities->setCapability(
'os',
'Windows' // Force windows
);
$capabilities->setCapability(
'os_version',
'10' // Force windows 10
);
$capabilities->setCapability(
'browser_version',
'80.0' // Force chrome 80.0
);
$capabilities->setCapability('resolution', '1920x1080');
}
return $capabilities;
case 'safari':
$capabilities = DesiredCapabilities::safari();
if ($this->hasCIConfig() && $this->hasBrowserstackConfig()) {
$capabilities->setCapability(
'os',
'OS X' // Force OS X
);
$capabilities->setCapability(
'os_version',
'Sierra' // Force OS X Sierra
);
$capabilities->setCapability(
'browser_version',
'10.1' // Force Safari 10.1
);
}
return $capabilities;
case 'edge':
$capabilities = DesiredCapabilities::microsoftEdge();
if ($this->hasCIConfig() && $this->hasBrowserstackConfig()) {
$capabilities->setCapability(
'os',
'Windows' // Force windows
);
$capabilities->setCapability(
'os_version',
'10' // Force windows 10
);
$capabilities->setCapability(
'browser_version',
'insider preview' // Force Edge insider preview
);
}
return $capabilities;
}
}
/**
* Checks whether the user is a superuser.
*/
protected function isSuperUser(): bool
{
return $this->dbQuery('SELECT COUNT(*) FROM mysql.user');
}
/**
* Skips test if test user is not a superuser.
*/
protected function skipIfNotSuperUser(): void
{
if ($this->isSuperUser()) {
return;
}
$this->markTestSkipped('Test user is not a superuser.');
}
/**
* Use the fix relation button to install phpMyAdmin storage
*/
protected function fixUpPhpMyAdminStorage(): bool
{
$this->navigateTo('index.php?route=/check-relations');
$fixTextSelector = '//div[@class="alert alert-primary" and contains(., "Create a database named")]/a';
if ($this->isElementPresent('xpath', $fixTextSelector)) {
$this->byXPath($fixTextSelector)->click();
$this->waitAjax();
return true;
}
return false;
}
/**
* Skips test if pmadb is not configured.
*/
protected function skipIfNotPMADB(): void
{
$this->navigateTo('index.php?route=/check-relations');
$pageContent = $this->waitForElement('id', 'page_content');
if (! preg_match('/Configuration of pmadb… not OK/i', $pageContent->getText())) {
return;
}
if (! $this->fixUpPhpMyAdminStorage()) {
$this->markTestSkipped('The phpMyAdmin configuration storage is not working.');
}
// If it failed the code already has exited with markTestSkipped
$this->hadStorageDatabaseInstall = true;
}
/**
* perform a login
*
* @param string $username Username
* @param string $password Password
*/
public function login(string $username = '', string $password = ''): void
{
$this->logOutIfLoggedIn();
if ($username === '') {
$username = $this->getTestSuiteUserLogin();
}
if ($password === '') {
$password = $this->getTestSuiteUserPassword();
}
$this->navigateTo('');
/* Wait while page */
while ($this->webDriver->executeScript('return document.readyState !== "complete";')) {
usleep(5000);
}
// Return if already logged in
if ($this->isSuccessLogin()) {
return;
}
// Select English if the Language selector is available
if ($this->isElementPresent('id', 'languageSelect')) {
$this->selectByLabel($this->byId('languageSelect'), 'English');
}
// Clear the input for Microsoft Edge (remembers the username)
$this->waitForElement('id', 'input_username')->clear()->click()->sendKeys($username);
$this->byId('input_password')->click()->sendKeys($password);
$this->byId('input_go')->click();
}
/**
* Get element by Id
*
* @param string $id The element ID
*/
public function byId(string $id): RemoteWebElement
{
return $this->webDriver->findElement(WebDriverBy::id($id));
}
/**
* Get element by css selector
*
* @param string $selector The element css selector
*/
public function byCssSelector(string $selector): RemoteWebElement
{
return $this->webDriver->findElement(WebDriverBy::cssSelector($selector));
}
/**
* Get element by xpath
*
* @param string $xpath The xpath
*/
public function byXPath(string $xpath): RemoteWebElement
{
return $this->webDriver->findElement(WebDriverBy::xpath($xpath));
}
/**
* Get element by linkText
*
* @param string $linkText The link text
*/
public function byLinkText(string $linkText): RemoteWebElement
{
return $this->webDriver->findElement(WebDriverBy::linkText($linkText));
}
/**
* Double click
*/
public function doubleclick(): void
{
$this->webDriver->action()->doubleClick()->perform();
}
/**
* Simple click
*/
public function click(): void
{
$this->webDriver->action()->click()->perform();
}
/**
* Get element by byPartialLinkText
*
* @param string $partialLinkText The partial link text
*/
public function byPartialLinkText(string $partialLinkText): RemoteWebElement
{
return $this->webDriver->findElement(WebDriverBy::partialLinkText($partialLinkText));
}
public function isSafari(): bool
{
$capabilities = $this->webDriver->getCapabilities();
return $capabilities !== null && mb_strtolower($capabilities->getBrowserName()) === 'safari';
}
/**
* Get element by name
*
* @param string $name The name
*/
public function byName(string $name): RemoteWebElement
{
return $this->webDriver->findElement(WebDriverBy::name($name));
}
/**
* Checks whether the login is successful
*/
public function isSuccessLogin(): bool
{
return $this->isElementPresent('xpath', '//*[@id="server-breadcrumb"]');
}
/**
* Checks whether the login is unsuccessful
*/
public function isUnsuccessLogin(): bool
{
return $this->isElementPresent('cssSelector', 'div #pma_errors');
}
/**
* Used to go to the homepage
*/
public function gotoHomepage(): void
{
$e = $this->byPartialLinkText('Server: ');
$e->click();
$this->waitAjax();
}
/**
* Execute a database query
*
* @param string $query SQL Query to be executed
* @param Closure|null $onResults The function to call when the results are displayed
* @param Closure|null $afterSubmit The function to call after the submit button is clicked
*
* @throws Exception
*/
public function dbQuery(string $query, ?Closure $onResults = null, ?Closure $afterSubmit = null): bool
{
$didSucceed = false;
$handles = null;
if (! $this->sqlWindowHandle) {
$this->webDriver->executeScript("window.open('about:blank','_blank');", []);
$this->webDriver->wait()->until(
WebDriverExpectedCondition::numberOfWindowsToBe(2)
);
$handles = $this->webDriver->getWindowHandles();
$lastWindow = end($handles);
$this->webDriver->switchTo()->window($lastWindow);
$this->login();
$this->sqlWindowHandle = $lastWindow;
}
if ($handles === null) {
$handles = $this->webDriver->getWindowHandles();
}
if ($this->sqlWindowHandle) {
$this->webDriver->switchTo()->window($this->sqlWindowHandle);
if (! $this->isSuccessLogin()) {
$this->takeScrenshot('SQL_window_not_logged_in');
return false;
}
$this->byXPath('//*[contains(@class,"nav-item") and contains(., "SQL")]')->click();
$this->waitAjax();
$this->typeInTextArea($query);
$this->byId('button_submit_query')->click();
if ($afterSubmit !== null) {
$afterSubmit->call($this);
}
$this->waitAjax();
$this->waitForElement('className', 'result_query');
// If present then
$didSucceed = $this->isElementPresent('cssSelector', '.result_query .alert-success');
if ($onResults !== null) {
$onResults->call($this);
}
}
reset($handles);
$lastWindow = current($handles);
$this->webDriver->switchTo()->window($lastWindow);
return $didSucceed;
}
public function takeScrenshot(string $comment): void
{
$screenshotDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR . 'build' . DIRECTORY_SEPARATOR
. 'selenium';
if ($this->webDriver === null) {
return;
}
$key = time();
// This call will also create the file path
$this->webDriver->takeScreenshot(
$screenshotDir . DIRECTORY_SEPARATOR
. 'screenshot_' . $key . '_' . $comment . '.png'
);
$htmlOutput = $screenshotDir . DIRECTORY_SEPARATOR . 'source_' . $key . '.html';
file_put_contents($htmlOutput, $this->webDriver->getPageSource());
$testInfo = $screenshotDir . DIRECTORY_SEPARATOR . 'source_' . $key . '.json';
file_put_contents($testInfo, json_encode(
[
'filesKey' => $key,
'testName' => $this->getTestName(),
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
));
}
/**
* Check if user is logged in to phpmyadmin
*/
public function isLoggedIn(): bool
{
return $this->isElementPresent('xpath', '//*[@class="navigationbar"]');
}
/**
* Perform a logout, if logged in
*/
public function logOutIfLoggedIn(): void
{
if (! $this->isLoggedIn()) {
return;
}
$this->byCssSelector('img.icon.ic_s_loggoff')->click();
}
/**
* Wait for an element to be present on the page
*
* @param string $func Locate using - cssSelector, xpath, tagName, partialLinkText, linkText, name, id, className
* @param string $arg Selector
*/
public function waitForElement(string $func, string $arg): RemoteWebElement
{
return $this->webDriver->wait(30, 500)->until(
WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::$func($arg))
);
}
/**
* Wait for an element to be present on the page or timeout
*
* @param string $func Locate using - cssSelector, xpath, tagName, partialLinkText, linkText, name, id, className
* @param string $arg Selector
* @param int $timeout Timeout in seconds
*/
public function waitUntilElementIsPresent(string $func, string $arg, int $timeout): RemoteWebElement
{
return $this->webDriver->wait($timeout, 500)->until(
WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::$func($arg))
);
}
/**
* Wait for an element to be visible on the page or timeout
*
* @param string $func Locate using - cssSelector, xpath, tagName, partialLinkText, linkText, name, id, className
* @param string $arg Selector
* @param int $timeout Timeout in seconds
*/
public function waitUntilElementIsVisible(string $func, string $arg, int $timeout): WebDriverElement
{
return $this->webDriver->wait($timeout, 500)->until(
WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::$func($arg))
);
}
/**
* Wait for an element to disappear
*
* @param string $func Locate using - byCss, byXPath, etc
* @param string $arg Selector
*/
public function waitForElementNotPresent(string $func, string $arg): void
{
while (true) {
if (! $this->isElementPresent($func, $arg)) {
return;
}
usleep(5000);
}
}
/**
* Check if element is present or not
*
* @param string $func Locate using - cssSelector, xpath, tagName, partialLinkText, linkText, name, id, className
* @param string $arg Selector
*/
public function isElementPresent(string $func, string $arg): bool
{
try {
$this->webDriver->findElement(WebDriverBy::$func($arg));
} catch (NoSuchElementException | InvalidArgumentException | InvalidSelectorException $e) {
// Element not present
return false;
}
// Element Present
return true;
}
/**
* Get table cell data by the ID of the table
*
* @param string $tableID Table identifier
* @param int $row Table row
* @param int $column Table column
*
* @return string text Data from the particular table cell
*/
public function getCellByTableId(string $tableID, int $row, int $column): string
{
$sel = sprintf('table#%s tbody tr:nth-child(%d) td:nth-child(%d)', $tableID, $row, $column);
$element = $this->byCssSelector($sel);
$text = $element->getText();
return $text && is_string($text) ? trim($text) : '';
}
/**
* Get table cell data by the class attribute of the table
*
* @param string $tableClass Class of the table
* @param int $row Table row
* @param int $column Table column
*
* @return string text Data from the particular table cell
*/
public function getCellByTableClass(string $tableClass, int $row, int $column): string
{
$sel = sprintf('table.%s tbody tr:nth-child(%d) td:nth-child(%d)', $tableClass, $row, $column);
$element = $this->byCssSelector($sel);
$text = $element->getText();
return $text && is_string($text) ? trim($text) : '';
}
/**
* Wrapper around keys method to not use it on not supported
* browsers.
*
* @param string $text Keys to send
*/
public function keys(string $text): void
{
/**
* Not supported in Safari Webdriver, see
* https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/4136
*/
if ($this->isSafari()) {
$this->markTestSkipped('Can not send keys to Safari browser.');
} else {
$this->webDriver->getKeyboard()->sendKeys($text);
}
}
/**
* Wrapper around moveto method to not use it on not supported
* browsers.
*
* @param RemoteWebElement $element element
*/
public function moveto(RemoteWebElement $element): void
{
/**
* Not supported in Safari Webdriver, see
* https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/4136
*/
if ($this->isSafari()) {
$this->markTestSkipped('MoveTo not supported on Safari browser.');
} else {
$this->webDriver->getMouse()->mouseMove($element->getCoordinates());
}
}
/**
* Wrapper around alertText method to not use it on not supported
* browsers.
*
* @return mixed
*/
public function alertText()
{
/**
* Not supported in Safari Webdriver, see
* https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/4136
*/
if (! $this->isSafari()) {
return $this->webDriver->switchTo()->alert()->getText();
}
$this->markTestSkipped('Alerts not supported on Safari browser.');
}
/**
* Type text in textarea (CodeMirror enabled)
*
* @param string $text Text to type
* @param int $index Index of CodeMirror instance to write to
*/
public function typeInTextArea(string $text, int $index = 0): void
{
$this->waitForElement('cssSelector', 'div.cm-s-default');
$this->webDriver->executeScript(
"$('.cm-s-default')[" . $index . '].CodeMirror.setValue(' . json_encode($text) . ');'
);
}
/**
* Accept alert
*/
public function acceptAlert(): void
{
$this->webDriver->switchTo()->alert()->accept();
}
/**
* Clicks the "More" link in the menu
*/
public function expandMore(): void
{
// "More" menu is not displayed on large screens
if ($this->isElementPresent('cssSelector', 'li.nav-item.dropdown.d-none')) {
return;
}
// Not found, searching for another alternative
try {
$ele = $this->waitForElement('cssSelector', 'li.dropdown > a');
$ele->click();
$this->waitForElement('cssSelector', 'li.dropdown.show > a');
$this->waitUntilElementIsPresent('cssSelector', 'li.nav-item.dropdown.show > ul', 5000);
} catch (WebDriverException $e) {
return;
}
}
/**
* Navigates browser to a table page.
*
* @param string $table Name of table
* @param bool $gotoHomepageRequired Go to homepage required
*/
public function navigateTable(string $table, bool $gotoHomepageRequired = false): void
{
$this->navigateDatabase($this->databaseName, $gotoHomepageRequired);
// go to table page
$this->waitForElement('xpath', "//th//a[contains(., '" . $table . "')]")->click();
$this->waitAjax();
}
/**
* Navigates browser to a database page.
*
* @param string $database Name of database
* @param bool $gotoHomepageRequired Go to homepage required
*/
public function navigateDatabase(string $database, bool $gotoHomepageRequired = false): void
{
if ($gotoHomepageRequired) {
$this->gotoHomepage();
}
// Go to server databases
$this->waitForElement('partialLinkText', 'Databases')->click();
$this->waitAjax();
// go to specific database page
$this->waitForElement(
'xpath',
'//tr[(contains(@class, "db-row"))]//a[contains(., "' . $database . '")]'
)->click();
$this->waitAjax();
}
/**
* Select an option that matches a value
*
* @param WebDriverElement $element The element
* @param string $value The value of the option
*/
public function selectByValue(WebDriverElement $element, string $value): void
{
$select = new WebDriverSelect($element);
$select->selectByValue($value);
}
/**
* Select an option that matches a text
*
* @param WebDriverElement $element The element
* @param string $text The text
*/
public function selectByLabel(WebDriverElement $element, string $text): void
{
$select = new WebDriverSelect($element);
$select->selectByVisibleText($text);
}
/**
* Scrolls to a coordinate such that the element with given id is visible
*
* @param string $elementId Id of the element
* @param int $yOffset Offset from Y-coordinate of element
*/
public function scrollIntoView(string $elementId, int $yOffset = 70): void
{
// 70pt offset by-default so that the topmenu does not cover the element
$script = <<<'JS'
const elementId = arguments[0];
const yOffset = arguments[1];
const position = document.getElementById(elementId).getBoundingClientRect();
window.scrollBy({left: 0, top: position.top - yOffset, behavior: 'instant'});
JS;
$this->webDriver->executeScript($script, [$elementId, $yOffset]);
}
/**
* Scrolls to a coordinate such that the element
*
* @param WebDriverElement $element The element
* @param int $xOffset The x offset to apply (defaults to 0)
* @param int $yOffset The y offset to apply (defaults to 0)
*/
public function scrollToElement(WebDriverElement $element, int $xOffset = 0, int $yOffset = 0): void
{
$script = <<<'JS'
const leftValue = arguments[0];
const topValue = arguments[1];
window.scrollBy({left: leftValue, top: topValue, behavior: 'instant'});
JS;
$this->webDriver->executeScript($script, [
$element->getLocation()->getX() + $xOffset,
$element->getLocation()->getY() + $yOffset,
]);
}
/**
* Scroll to the bottom of page
*/
public function scrollToBottom(): void
{
$script = <<<'JS'
window.scrollTo({left: 0, top: document.body.scrollHeight, behavior: 'instant'});
JS;
$this->webDriver->executeScript($script);
}
/**
* Reload the page
*/
public function reloadPage(): void
{
$this->webDriver->executeScript('window.location.reload();');
}
/**
* Wait for AJAX completion
*/
public function waitAjax(): void
{
/* Wait while code is loading */
$this->webDriver->executeAsyncScript(
'var callback = arguments[arguments.length - 1];'
. 'function startWaitingForAjax() {'
. ' if (! AJAX.active) {'
. ' callback();'
. ' } else {'
. ' setTimeout(startWaitingForAjax, 200);'
. ' }'
. '}'
. 'startWaitingForAjax();'
);
}
/**
* Wait for AJAX message disappear
*/
public function waitAjaxMessage(): void
{
/* Get current message count */
$ajax_message_count = $this->webDriver->executeScript('return ajaxMessageCount;');
/* Ensure the popup is gone */
$this->waitForElementNotPresent('id', 'ajax_message_num_' . $ajax_message_count);
}
/**
* Tear Down function for test cases
*/
protected function tearDown(): void
{
if (static::$createDatabase) {
$this->dbQuery('DROP DATABASE IF EXISTS `' . $this->databaseName . '`;');
}
if ($this->hadStorageDatabaseInstall) {
$this->dbQuery('DROP DATABASE IF EXISTS `phpmyadmin`;');
}
if ($this->hasFailed()) {
return;
}
$this->markTestAs('passed', '');
$this->sqlWindowHandle = null;
$this->webDriver->quit();
}
/**
* Mark test as failed or passed on BrowserStack
*
* @param string $status passed or failed
* @param string $message a message
*/
private function markTestAs(string $status, string $message): void
{
// If this is being run on Browerstack,
// mark the test on Browerstack as failure
if (! $this->hasBrowserstackConfig()) {
return;
}
$payload = json_encode(
[
'status' => $status,
'reason' => $message,
]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::SESSION_REST_URL . $this->sessionId . '.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt(
$ch,
CURLOPT_USERPWD,
$this->getBrowserStackCredentials()
);
$headers = [];
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch) . PHP_EOL;
}
curl_close($ch);
}
private function getErrorVideoUrl(): void
{
if (! $this->hasBrowserstackConfig()) {
return;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::SESSION_REST_URL . $this->sessionId . '.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch,
CURLOPT_USERPWD,
$this->getBrowserStackCredentials()
);
$result = curl_exec($ch);
if (is_bool($result)) {
echo 'Error: ' . curl_error($ch) . PHP_EOL;
return;
}
$proj = json_decode($result);
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
if (isset($proj->automation_session)) {
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
echo 'Test failed, get more information here: ' . $proj->automation_session->public_url . PHP_EOL;
}
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch) . PHP_EOL;
}
curl_close($ch);
}
/**
* Mark unsuccessful tests as 'Failures' on Browerstack
*
* @param Throwable $t Throwable
*/
public function onNotSuccessfulTest(Throwable $t): void
{
if ($t instanceof SkippedTest) {
parent::onNotSuccessfulTest($t);
}
$this->markTestAs('failed', $t->getMessage());
$this->takeScrenshot('test_failed');
// End testing session
if ($this->webDriver !== null) {
$this->webDriver->quit();
}
$this->sqlWindowHandle = null;
$this->getErrorVideoUrl();
// Call parent's onNotSuccessful to handle everything else
parent::onNotSuccessfulTest($t);
}
}
|