-
-
Save arcticlinux/2f59558898b4d74a57cb769aafd4ced7 to your computer and use it in GitHub Desktop.
Codeception - how to test for redirects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Simply place the following two functions in _support/Helper/Acceptance.php | |
// Then you can call $I->verifyRedirect(...) inside your tests | |
// | |
// 2020-12-21 Updated from https://gist.github.com/SimonEast/b550e04300ac56cb5ac8eea704fccdfa | |
// - tested using Codeception v4.1.12 | |
// - change backwards order of arguments in asserts, expected argument should be first | |
// - add additional type hints | |
// - add exception types | |
// - make asserts type safe | |
// - change getStatus to getStatusCode | |
namespace Helper; | |
class Acceptance extends \Codeception\Module | |
{ | |
/** | |
* Ensure that a particular URL does NOT contain a 301/302 nor a "Location" header | |
* | |
* @param string $url | |
* | |
* @throws \Codeception\Exception\ModuleException | |
*/ | |
public function verifyNoRedirect($url): void | |
{ | |
$phpBrowser = $this->getModule('PhpBrowser'); | |
/** @var AbstractBrowser $guzzle */ | |
$guzzle = $phpBrowser->client; | |
// Disable the following of redirects | |
$guzzle->followRedirects(false); | |
$phpBrowser->_loadPage('GET', $url); | |
$response = $guzzle->getInternalResponse(); | |
$responseCode = $response->getStatusCode(); | |
$locationHeader = $response->getHeader('Location'); | |
$this->assertNotSame(301, $responseCode); | |
$this->assertNotSame(302, $responseCode); | |
$this->assertNull($locationHeader); | |
$guzzle->followRedirects(true); | |
} | |
/** | |
* Ensure that a particular URL redirects to another URL | |
* | |
* @param string $startUrl | |
* @param string $endUrl (should match "Location" header exactly) | |
* @param int $redirectCode (301 = permanent, 302 = temporary) | |
* | |
* @throws \Codeception\Exception\ModuleException | |
*/ | |
public function verifyRedirect($startUrl, $endUrl, $redirectCode = 301): void | |
{ | |
$phpBrowser = $this->getModule('PhpBrowser'); | |
/** @var AbstractBrowser $guzzle */ | |
$guzzle = $phpBrowser->client; | |
// Disable the following of redirects | |
$guzzle->followRedirects(false); | |
$phpBrowser->_loadPage('GET', $startUrl); | |
$response = $guzzle->getInternalResponse(); | |
$responseCode = $response->getStatusCode(); | |
$locationHeader = $response->getHeader('Location'); | |
$this->assertSame($redirectCode, $responseCode); | |
$this->assertEquals($endUrl, $locationHeader); | |
$guzzle->followRedirects(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment