From 870aa711ed3d6d08e68f5136483b7b4e17ee1915 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 7 Apr 2024 19:24:33 +0300 Subject: [PATCH] Harden window closing code upon session reset --- src/WebdriverClassicDriver.php | 11 ++++-- tests/Custom/SessionResetTest.php | 62 +++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) create mode 100644 tests/Custom/SessionResetTest.php diff --git a/src/WebdriverClassicDriver.php b/src/WebdriverClassicDriver.php index eb532f4..d1d66ff 100644 --- a/src/WebdriverClassicDriver.php +++ b/src/WebdriverClassicDriver.php @@ -138,14 +138,19 @@ public function reset(): void { // switch to default window.. $this->switchToWindow(); + $actualInitialWindowName = $this->getWindowName(); // Account for initial window rename. + $webDriver = $this->getWebDriver(); + // ..and close all other windows foreach ($this->getWindowNames() as $name) { - if ($name !== $this->initialWindowName) { - $this->withWindow($name, fn() => $this->getWebDriver()->close()); + if ($name !== $actualInitialWindowName) { + $this->switchToWindow($name); + $webDriver->close(); + $this->switchToWindow(); } } - $this->getWebDriver()->manage()->deleteAllCookies(); + $webDriver->manage()->deleteAllCookies(); } public function visit(string $url): void diff --git a/tests/Custom/SessionResetTest.php b/tests/Custom/SessionResetTest.php new file mode 100644 index 0000000..7fee0d7 --- /dev/null +++ b/tests/Custom/SessionResetTest.php @@ -0,0 +1,62 @@ +getSession(); + $session->visit($this->pathTo('/window.html')); + + if (null !== $initialWindowName) { + $session->executeScript('window.name = "'.$initialWindowName.'";'); + } + + $page = $session->getPage(); + + $page->clickLink('Popup #1'); + $page->clickLink('Popup #2'); + + $expectedInitialWindowName = $session->evaluateScript('window.name'); + + $windowNames = $session->getWindowNames(); + $this->assertCount(3, $windowNames); + + $session->reset(); + + $windowNames = $session->getWindowNames(); + $this->assertCount(1, $windowNames); + + $actualInitialWindowName = $session->evaluateScript('window.name'); + $this->assertEquals($expectedInitialWindowName, $actualInitialWindowName); + } + + public static function initialWindowNameDataProvider(): array + { + return array( + 'no name' => array(null), + 'non-empty name' => array('initial-window'), + ); + } + + /** + * @after + */ + protected function resetSessions() + { + $session = $this->getSession(); + + // Stop the session instead of resetting, because resetting behavior is being tested. + if ($session->isStarted()) { + $session->stop(); + } + + parent::resetSessions(); + } +}