Skip to content

Commit

Permalink
Merge pull request #977 from JonPurvis/to-be-url-expectation
Browse files Browse the repository at this point in the history
[2.x] Adds `toBeUrl()` Expectation
  • Loading branch information
nunomaduro authored Oct 9, 2023
2 parents 2ffafd4 + 5101b9d commit 4be97ed
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Mixins/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -1142,4 +1142,20 @@ public function toBeBetween(int|float|DateTimeInterface $lowestValue, int|float|

return $this;
}

/**
* Asserts that the value is a url
*
* @return self<TValue>
*/
public function toBeUrl(string $message = ''): self
{
if ($message === '') {
$message = "Failed asserting that {$this->value} is a url.";
}

Assert::assertTrue(Str::isUrl((string) $this->value), $message);

return $this;
}
}
8 changes: 8 additions & 0 deletions src/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,12 @@ public static function describe(string $describeDescription, string $testDescrip
{
return sprintf('`%s` → %s', $describeDescription, $testDescription);
}

/**
* Determine if a given value is a valid URL.
*/
public static function isUrl(string $value): bool
{
return (bool) filter_var($value, FILTER_VALIDATE_URL);
}
}
24 changes: 24 additions & 0 deletions tests/Features/Expect/toBeUrl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

use PHPUnit\Framework\ExpectationFailedException;

test('pass', function () {
expect('https://pestphp.com')->toBeUrl()
->and('pestphp.com')->not->toBeUrl();
});

test('failures', function () {
expect('pestphp.com')->toBeUrl();
})->throws(ExpectationFailedException::class);

test('failures with custom message', function () {
expect('pestphp.com')->toBeUrl('oh no!');
})->throws(ExpectationFailedException::class, 'oh no!');

test('failures with default message', function () {
expect('pestphp.com')->toBeUrl();
})->throws(ExpectationFailedException::class, 'Failed asserting that pestphp.com is a url.');

test('not failures', function () {
expect('https://pestphp.com')->not->toBeUrl();
})->throws(ExpectationFailedException::class);

0 comments on commit 4be97ed

Please sign in to comment.