Page Menu
Home
DevCentral
Search
Configure Global Search
Log In
Files
F11724977
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
99 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/composer.json b/composer.json
index a017944..7b26b45 100644
--- a/composer.json
+++ b/composer.json
@@ -1,27 +1,27 @@
{
"name": "keruald/omnitools",
"description": "Utilities classes",
"type": "library",
"license": "BSD-2-Clause",
"authors": [
{
"name": "Sébastien Santoro",
"email": "dereckson@espace-win.org"
}
],
"autoload": {
"psr-4": {
"Keruald\\OmniTools\\": "src/",
"Keruald\\OmniTools\\Tests\\": "tests/"
}
},
"require": {
"ext-intl": "*"
},
"require-dev": {
"nasqueron/codestyle": "^0.0.1",
"phan/phan": "^5.3.1",
- "phpunit/phpunit": "^9.5",
+ "phpunit/phpunit": "^10.2",
"squizlabs/php_codesniffer": "^3.6"
}
}
diff --git a/phpunit.xml b/phpunit.xml
index f5c1939..7027a51 100644
--- a/phpunit.xml
+++ b/phpunit.xml
@@ -1,24 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
+ xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.3/phpunit.xsd"
bootstrap="vendor/autoload.php"
- convertErrorsToExceptions="true"
- convertNoticesToExceptions="true"
- convertWarningsToExceptions="true"
stopOnFailure="false">
<php>
<ini name="display_errors" value="On" />
<ini name="display_startup_errors" value="On" />
<ini name="error_reporting" value="On" />
</php>
<testsuites>
<testsuite name="Unit tests">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
- <coverage processUncoveredFiles="true">
+ <source>
<include>
<directory suffix=".php">src/</directory>
</include>
- </coverage>
+ </source>
</phpunit>
diff --git a/tests/Collections/ArrayUtilitiesTest.php b/tests/Collections/ArrayUtilitiesTest.php
index 737ea38..d536cd0 100644
--- a/tests/Collections/ArrayUtilitiesTest.php
+++ b/tests/Collections/ArrayUtilitiesTest.php
@@ -1,24 +1,23 @@
<?php
namespace Keruald\OmniTools\Tests\Collections;
use Keruald\OmniTools\Collections\ArrayUtilities;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class ArrayUtilitiesTest extends TestCase {
- /**
- * @dataProvider provideIntegersArray
- */
+ #[DataProvider('provideIntegersArray')]
public function testToIntegers ($expected, $toConvert) {
$this->assertEquals($expected, ArrayUtilities::toIntegers($toConvert));
}
- public function provideIntegersArray () : iterable {
+ public static function provideIntegersArray () : iterable {
yield [[1, 2, 3], ["1", "2", "3"]];
yield [[1, 2, 3], [1, 2, 3]];
yield [[], []];
}
}
diff --git a/tests/Collections/BitsVectorTest.php b/tests/Collections/BitsVectorTest.php
index d6064ce..1bcde23 100644
--- a/tests/Collections/BitsVectorTest.php
+++ b/tests/Collections/BitsVectorTest.php
@@ -1,265 +1,262 @@
<?php
namespace Keruald\OmniTools\Tests\Collections;
use InvalidArgumentException;
use OutOfRangeException;
use Keruald\OmniTools\Collections\BitsVector;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class BitsVectorTest extends TestCase {
///
/// Constructors
///
public function testConstructorWithInvalidIterable () : void {
$this->expectException(InvalidArgumentException::class);
new BitsVector([1, 2, 3, 4]);
}
public function testNew () : void {
$bits = BitsVector::new(8);
$this->assertEquals(8, $bits->count());
}
public function testNewWhenCapacityIsEmpty () : void {
$bits = BitsVector::new(0);
$this->assertEquals(0, $bits->count());
}
public function testNewWhenCapacityIsNegative () : void {
$this->expectException(InvalidArgumentException::class);
BitsVector::new(-8);
}
public function testFromInteger () : void {
$bits = BitsVector::fromInteger(4);
$this->assertEquals([1, 0, 0], $bits->toArray());
}
public function testFromIntegerWhenValueIsNegative () : void {
$bits = BitsVector::fromInteger(-1);
$expected = array_fill(0, 64, 1);
$this->assertEquals($expected, $bits->toArray());
}
public function testFromBinString () : void {
$bits = BitsVector::fromBinaryString("1001");
$this->assertEquals([1, 0, 0, 1], $bits->toArray());
}
public function testFromHexString () : void {
$bits = BitsVector::fromHexString("337362ea");
$this->assertEquals("337362ea", $bits->toHexString());
}
public function testFromDecoratedHexString () : void {
$bits = BitsVector::fromDecoratedHexString("cc4eca23-b825-11ec-ab20-a81e84f35d9c");
$this->assertEquals("cc4eca23b82511ecab20a81e84f35d9c", $bits->toHexString());
}
public function testFromString () : void {
// Exemple based on pack() documentation
$binaryData = pack("nvc*", 0x1234, 0x5678, 65, 66);
$bits = BitsVector::fromString($binaryData);
$this->assertEquals(
[0x12, 0x34, 0x78, 0x56, 0x41, 0x42],
$bits->toBytesArray(),
);
}
public function testBytesArray () : void {
$bits = BitsVector::new(16)
->copyInteger(1, 0, 4)
->copyInteger(2, 4, 4)
->copyInteger(3, 8, 4)
->copyInteger(4, 12, 4);
$this->assertEquals(
[0x12, 0x34],
$bits->toBytesArray(),
);
}
- public function provideLengths () : iterable {
+ public static function provideLengths () : iterable {
yield [1];
yield [2];
yield [8];
yield [500];
yield [5000];
yield [0];
}
- /**
- * @dataProvider provideLengths
- */
+ #[DataProvider('provideLengths')]
public function testRandom($length) : void {
$bits = BitsVector::random($length);
$this->assertEquals($length, $bits->count());
}
public function testRandomWithNegativeLength() : void {
$this->expectException(InvalidArgumentException::class);
BitsVector::random(-1);
}
public function testBytesArrayWithBadLength () : void {
$this->expectException(InvalidArgumentException::class);
$bits = new BitsVector([1, 1, 1]); // 3 bits isn't a byte
$bits->toBytesArray();
}
public function testToBinaryString () : void {
$bits = new BitsVector([1, 0, 0, 1]);
$this->assertEquals("1001", $bits->toBinaryString());
}
public function testToInteger () : void {
$bits = new BitsVector([1, 0, 0, 1]);
$this->assertEquals(9, $bits->toInteger());
}
public function testToIntegerWhenThereIsTooMuchBits () : void {
$this->expectException(InvalidArgumentException::class);
BitsVector::new(66)->toInteger();
}
public function testPad () : void {
$bits = new BitsVector([1, 0, 0, 1]);
$bits->pad(8);
$this->assertEquals([0, 0, 0, 0, 1, 0, 0, 1], $bits->toArray());
}
public function testPadWithLargeEnoughCount () : void {
$bits = new BitsVector([1, 0, 0, 1]);
$bits->pad(4);
$this->assertEquals([1, 0, 0, 1], $bits->toArray());
}
public function testTruncate () : void {
$bits = new BitsVector([1, 0, 0, 1, 0, 0, 0, 0]);
$bits->truncate(4);
$this->assertEquals([1, 0, 0, 1], $bits->toArray());
}
public function testTruncateWithSmallEnoughCount () : void {
$bits = new BitsVector([1, 0, 0, 1]);
$bits->truncate(4);
$this->assertEquals([1, 0, 0, 1], $bits->toArray());
}
- public function provideShapeArrays () : iterable {
+ public static function provideShapeArrays () : iterable {
yield [[1, 0, 0, 1, 0, 0, 0, 0], 4, [1, 0, 0, 1]];
yield [[1, 0, 0, 1], 4, [1, 0, 0, 1]];
yield [[1, 0, 0, 1], 3, [1, 0, 0]];
yield [[1, 0, 0, 1], 0, []];
yield [[], 0, []];
yield [[], 4, [0, 0, 0, 0]];
}
- /**
- * @dataProvider provideShapeArrays
- */
+ #[DataProvider('provideShapeArrays')]
public function testShapeCapacity (array $initial, int $length, array $final) : void {
$bits = new BitsVector($initial);
$bits->shapeCapacity($length);
$this->assertEquals($final, $bits->toArray());
}
public function testCopyInteger() : void {
$bits = BitsVector::new(8);
$bits->copyInteger(5, 2, 3);
$this->assertEquals([0, 0, 1, 0, 1, 0, 0, 0], $bits->toArray());
}
///
/// BaseVector overrides
///
public function testSet () : void {
$bits = BitsVector::new(4);
$bits->set(2, 1);
$this->assertEquals([0, 0, 1, 0], $bits->toArray());
}
public function testContains () : void {
$bits = BitsVector::new(4);
$this->assertFalse($bits->contains(1));
}
public function testPush () : void {
$bits = BitsVector::new(4);
$bits->push(1);
$this->assertEquals([0, 0, 0, 0, 1], $bits->toArray());
}
public function testAppend () : void {
$bits = BitsVector::new(4);
$bits->append([1, 1]);
$this->assertEquals([0, 0, 0, 0, 1, 1], $bits->toArray());
}
public function testUpdate () : void {
$bits = BitsVector::new(4);
$bits->update([1, 0, 1, 0]); // 0 already exists, we'll add ONE 1
$this->assertEquals([0, 0, 0, 0, 1], $bits->toArray());
}
public function testOffsetSet () : void {
$bits = BitsVector::new(4);
$bits[2] = 1;
$this->assertEquals([0, 0, 1, 0], $bits->toArray());
}
///
/// WithCollection trait
///
public function testFirst () : void {
$bits = BitsVector::new(4);
$bits[2] = 1;
$this->assertEquals(0, $bits->first());
}
public function testFirstWhenEmpty () : void {
$bits = BitsVector::new(0);
$this->expectException(OutOfRangeException::class);
$bits->first();
}
public function testFirstOr () : void {
$bits = BitsVector::new(4);
$bits[2] = 1;
$this->assertEquals(0, $bits->firstOr(2));
}
public function testFirstOrWhenEmpty () : void {
$bits = BitsVector::new(0);
$this->assertEquals(2, $bits->firstOr(2));
}
}
diff --git a/tests/Collections/HashMapTest.php b/tests/Collections/HashMapTest.php
index 940b88f..9529d66 100644
--- a/tests/Collections/HashMapTest.php
+++ b/tests/Collections/HashMapTest.php
@@ -1,529 +1,528 @@
<?php
namespace Keruald\OmniTools\Tests\Collections;
use Keruald\OmniTools\Collections\BitsVector;
use Keruald\OmniTools\Collections\HashMap;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
use IteratorAggregate;
use OutOfRangeException;
use Traversable;
class HashMapTest extends TestCase {
///
/// Test set up
///
private HashMap $map;
const MAP_CONTENT = [
// Some sci-fi civilizations and author
"The Culture" => "Iain Banks",
"Radchaai Empire" => "Ann Leckie",
"Barrayar" => "Lois McMaster Bujold",
"Hainish" => "Ursula K. Le Guin",
];
protected function setUp () : void {
$this->map = new HashMap(self::MAP_CONTENT);
}
///
/// Constructors
///
public function testConstructorWithArray () {
$this->assertSame(self::MAP_CONTENT, $this->map->toArray());
}
public function testConstructorWithTraversable () {
$expected = [
"color" => "blue",
"material" => "glass",
"shape" => "sphere",
];
$iterable = new class implements IteratorAggregate {
function getIterator () : Traversable {
yield "color" => "blue";
yield "material" => "glass";
yield "shape" => "sphere";
}
};
$map = new HashMap($iterable);
$this->assertSame($expected, $map->toArray());
}
- private function provideDeepArrays() : iterable {
+ public static function provideDeepArrays() : iterable {
yield [self::MAP_CONTENT, self::MAP_CONTENT];
yield [[], []];
yield [null, []];
$caps = new \stdClass;
$caps->color = "red";
$caps->logo = "HCKR";
yield [$caps, [
"color" => "red",
"logo" => "HCKR",
]];
$sizedCaps = clone $caps;
$sizedCaps->size = new \stdClass;
$sizedCaps->size->h = 8;
$sizedCaps->size->r = 20;
yield [$sizedCaps, [
"color" => "red",
"logo" => "HCKR",
"size" => ["h" => 8, "r" => 20],
]];
}
- /**
- * @dataProvider provideDeepArrays
- */
+ #[DataProvider('provideDeepArrays')]
public function testFrom($from, array $expected) : void {
$map = HashMap::from($from);
$this->assertEquals($expected, $map->toArray());
}
///
/// Getters and setters
///
public function testGet () {
$this->assertSame("Iain Banks", $this->map->get("The Culture"));
}
public function testGetWhenKeyIsNotFound () {
$this->expectException(InvalidArgumentException::class);
$this->map->get("Quuxians");
}
public function testGetOr () {
$actual = $this->map
->getOr("The Culture", "Another author");
$this->assertSame("Iain Banks", $actual);
}
public function testGetOrWhenKeyIsNotFound () {
$actual = $this->map
->getOr("Quuxians", "Another author");
$this->assertSame("Another author", $actual);
}
public function testSetWithNewKey () {
$this->map->set("Thélème", "François Rabelais");
$this->assertSame("François Rabelais",
$this->map->get("Thélème"));
}
public function testSetWithExistingKey () {
$this->map->set("The Culture", "Iain M. Banks");
$this->assertSame("Iain M. Banks",
$this->map->get("The Culture"));
}
public function testUnset() {
$this->map->unset("The Culture");
$this->assertFalse($this->map->contains("Iain Banks"));
}
public function testUnsetNotExistingKey() {
$this->map->unset("Not existing");
$this->assertEquals(4, $this->map->count());
}
public function testHas () {
$this->assertTrue($this->map->has("The Culture"));
$this->assertFalse($this->map->has("Not existing key"));
}
public function testContains () {
$this->assertTrue($this->map->contains("Iain Banks"));
$this->assertFalse($this->map->contains("Not existing value"));
}
///
/// Collection method
///
public function testCount () {
$this->assertSame(4, $this->map->count());
}
public function testClear () {
$this->map->clear();
$this->assertSame(0, $this->map->count());
}
public function testIsEmpty () : void {
$this->map->clear();
$this->assertTrue($this->map->isEmpty());
}
public function testMerge () {
$iterable = [
"The Culture" => "Iain M. Banks", // existing key
"Thélème" => "François Rabelais", // new key
];
$expected = [
// The original map
"The Culture" => "Iain Banks", // Old value should be kept
"Radchaai Empire" => "Ann Leckie",
"Barrayar" => "Lois McMaster Bujold",
"Hainish" => "Ursula K. Le Guin",
// The entries with a new key
"Thélème" => "François Rabelais",
];
$this->map->merge($iterable);
$this->assertSame($expected, $this->map->toArray());
}
public function testUpdate () {
$iterable = [
"The Culture" => "Iain M. Banks", // existing key
"Thélème" => "François Rabelais", // new key
];
$expected = [
// The original map
"The Culture" => "Iain M. Banks", // Old value should be updated
"Radchaai Empire" => "Ann Leckie",
"Barrayar" => "Lois McMaster Bujold",
"Hainish" => "Ursula K. Le Guin",
// The entries with a new key
"Thélème" => "François Rabelais",
];
$this->map->update($iterable);
$this->assertSame($expected, $this->map->toArray());
}
public function testToArray () {
$this->assertEquals(self::MAP_CONTENT, $this->map->toArray());
}
///
/// High order functions
///
public function testMap () {
$callback = function ($value) {
return "author='" . $value . "'";
};
$expected = [
"The Culture" => "author='Iain Banks'",
"Radchaai Empire" => "author='Ann Leckie'",
"Barrayar" => "author='Lois McMaster Bujold'",
"Hainish" => "author='Ursula K. Le Guin'",
];
$actual = $this->map->map($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testMapKeys () {
$callback = function ($key) {
return "civ::" . $key;
};
$expected = [
// Some sci-fi civilizations and author
"civ::The Culture" => "Iain Banks",
"civ::Radchaai Empire" => "Ann Leckie",
"civ::Barrayar" => "Lois McMaster Bujold",
"civ::Hainish" => "Ursula K. Le Guin",
];
$actual = $this->map->mapKeys($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testMapKeysAndValues () : void {
$callback = function ($civilization, $author) {
return [$author[0], "$author, $civilization"];
};
$expected = [
// Some sci-fi civilizations and author
"I" => "Iain Banks, The Culture",
"A" => "Ann Leckie, Radchaai Empire",
"L" => "Lois McMaster Bujold, Barrayar",
"U"=> "Ursula K. Le Guin, Hainish",
];
$actual = $this->map->mapValuesAndKeys($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testMapKeysAndValuesForVectors () : void {
$callback = function ($author) {
return [$author[0], "author:" . $author];
};
$expected = [
// Some sci-fi civilizations and author
"I" => "author:Iain Banks",
"A" => "author:Ann Leckie",
"L" => "author:Lois McMaster Bujold",
"U" => "author:Ursula K. Le Guin",
];
$actual = $this->map->mapValuesAndKeys($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testMapKeysAndValuesWithCallbackWithoutArgument() : void {
$this->expectException(InvalidArgumentException::class);
$callback = function () {};
$this->map->mapValuesAndKeys($callback);
}
public function testFlatMap(): void {
$callback = function ($key, $value) {
$items = explode(" ", $value);
foreach ($items as $item) {
yield $item => $key;
}
};
$expected = [
"Iain" => "The Culture",
"Banks" => "The Culture",
"Ann" => "Radchaai Empire",
"Leckie" => "Radchaai Empire",
"Lois" => "Barrayar",
"McMaster" => "Barrayar",
"Bujold" => "Barrayar",
"Ursula"=> "Hainish",
"K."=> "Hainish",
"Le"=> "Hainish",
"Guin"=> "Hainish",
];
$actual = $this->map->flatMap($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFlatMapForVectors() : void {
$callback = function ($value) {
$items = explode(" ", $value);
foreach ($items as $item) {
yield $item => $value;
}
};
$expected = [
"Iain" => "Iain Banks",
"Banks" => "Iain Banks",
"Ann" => "Ann Leckie",
"Leckie" => "Ann Leckie",
"Lois" => "Lois McMaster Bujold",
"McMaster" => "Lois McMaster Bujold",
"Bujold" => "Lois McMaster Bujold",
"Ursula"=> "Ursula K. Le Guin",
"K."=> "Ursula K. Le Guin",
"Le"=> "Ursula K. Le Guin",
"Guin"=> "Ursula K. Le Guin",
];
$actual = $this->map->flatMap($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFlatMapWithCallbackWithoutArgument() : void {
$this->expectException(InvalidArgumentException::class);
$callback = function () {};
$this->map->flatMap($callback);
}
public function testMapToVector() : void {
$expected = [
"The Culture by Iain Banks",
"Radchaai Empire by Ann Leckie",
"Barrayar by Lois McMaster Bujold",
"Hainish by Ursula K. Le Guin",
];
$fn = fn($key, $value) => "$key by $value";
$this->assertEquals($expected, $this->map->mapToVector($fn)->toArray());
}
public function testMapToVectorWithOnlyValueParameter() : void {
$expected = [
"Author: Iain Banks",
"Author: Ann Leckie",
"Author: Lois McMaster Bujold",
"Author: Ursula K. Le Guin",
];
$fn = fn($value) => "Author: $value";
$this->assertEquals($expected, $this->map->mapToVector($fn)->toArray());
}
public function testMapToVectorWithoutParameter() : void {
$this->expectException(InvalidArgumentException::class);
$fn = fn() => "";
$this->map->mapToVector($fn);
}
public function testFilter () {
// Let's filter to keep names with 3 parts or more
$callback = function ($value) : bool {
return str_word_count($value) > 2;
};
$expected = [
// Some sci-fi civilizations and author
"Barrayar" => "Lois McMaster Bujold",
"Hainish" => "Ursula K. Le Guin",
];
$actual = $this->map->filter($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFilterWithKeyValueCallback () {
// Let's find civilization AND author with e inside
$expected = [
// Some sci-fi civilizations and author
"Radchaai Empire" => "Ann Leckie",
];
$callback = function ($key, $value) : bool {
return str_contains($key, "e") && str_contains($value, "e");
};
$actual = $this->map->filter($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFilterWithCallbackWithoutArgument() {
$this->expectException(InvalidArgumentException::class);
$callback = function () : bool { // No argument
return true;
};
$this->map->filter($callback);
}
public function testFilterKeys () {
// Let's filter to keep short civilization names
$callback = function ($key) : bool {
return str_word_count($key) == 1;
};
$expected = [
// Some sci-fi civilizations and author
"Barrayar" => "Lois McMaster Bujold",
"Hainish" => "Ursula K. Le Guin",
];
$actual = $this->map->filterKeys($callback)->toArray();
$this->assertEquals($expected, $actual);
}
///
/// ArrayAccess
///
public function testOffsetExists () : void {
$this->assertTrue(isset($this->map["The Culture"]));
$this->assertFalse(isset($this->map["Not existing"]));
}
public function testOffsetSetWithoutOffset () : void {
$this->expectException(InvalidArgumentException::class);
$this->map[] = "Another Author";
}
public function testOffsetSet () : void {
$this->map["The Culture"] = "Iain M. Banks";
$this->assertEquals("Iain M. Banks", $this->map["The Culture"]);
}
public function testOffsetUnset () : void {
unset($this->map["Barrayar"]);
$expected = [
"The Culture" => "Iain Banks",
"Radchaai Empire" => "Ann Leckie",
// "Barrayar" => "Lois McMaster Bujold", UNSET ENTRY
"Hainish" => "Ursula K. Le Guin",
];
$this->assertEquals($expected, $this->map->toArray());
}
///
/// IteratorAggregate
///
public function testGetIterator () : void {
$this->assertEquals(self::MAP_CONTENT, iterator_to_array($this->map));
}
///
/// WithCollection trait
///
public function testFirst () : void {
$this->assertEquals("Iain Banks", $this->map->first());
}
public function testFirstWhenEmpty () : void {
$map = new HashMap();
$this->expectException(OutOfRangeException::class);
$map->first();
}
public function testFirstOr () : void {
$bits = BitsVector::new(4);
$bits[2] = 1;
$this->assertEquals("Iain Banks", $this->map->firstOr("Anonymous"));
}
public function testFirstOrWhenEmpty () : void {
$map = new HashMap();
$this->assertEquals("Anonymous", $map->firstOr("Anonymous"));
}
}
diff --git a/tests/Collections/TraversableUtilitiesTest.php b/tests/Collections/TraversableUtilitiesTest.php
index e2056fa..e2cab7b 100644
--- a/tests/Collections/TraversableUtilitiesTest.php
+++ b/tests/Collections/TraversableUtilitiesTest.php
@@ -1,116 +1,107 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Collections;
use Keruald\OmniTools\Collections\TraversableUtilities;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
use Traversable;
class TraversableUtilitiesTest extends TestCase {
- /**
- * @dataProvider provideCountables
- */
+ #[DataProvider('provideCountables')]
public function testCount ($expectedCount, $countable) {
$this->assertEquals(
$expectedCount, TraversableUtilities::count($countable)
);
}
- /**
- * @dataProvider provideNotCountables
- */
+ #[DataProvider('provideNotCountables')]
public function testCountWithNotCountables ($notCountable) {
$this->expectException("TypeError");
TraversableUtilities::count($notCountable);
}
- /**
- * @dataProvider providePureCountables
- */
+ #[DataProvider('providePureCountables')]
public function testIsCountable ($countable) {
$this->assertTrue(TraversableUtilities::isCountable($countable));
}
- /**
- * @dataProvider provideIterableAndFirst
- */
+ #[DataProvider('provideIterableAndFirst')]
public function testIsFirst($expected, $iterable) {
$this->assertEquals($expected, TraversableUtilities::first($iterable));
}
public function testIsFirstWithEmptyCollection() {
$this->expectException(InvalidArgumentException::class);
TraversableUtilities::first([]);
}
- /**
- * @dataProvider provideIterableAndFirst
- */
+ #[DataProvider('provideIterableAndFirst')]
public function testIsFirstOr($expected, $iterable) {
$actual = TraversableUtilities::firstOr($iterable, 666);
$this->assertEquals($expected, $actual);
}
public function testIsFirstOrWithEmptyCollection() {
$actual = TraversableUtilities::firstOr([], 666);
$this->assertEquals(666, $actual);
}
///
/// Data providers
///
- public function provideCountables () : iterable {
+ public static function provideCountables () : iterable {
yield [0, null];
yield [0, false];
yield [0, []];
yield [3, ["a", "b", "c"]];
yield [42, new class implements Countable {
public function count () : int {
return 42;
}
}
];
}
- public function providePureCountables () : iterable {
+ public static function providePureCountables () : iterable {
yield [[]];
yield [["a", "b", "c"]];
yield [new class implements Countable {
public function count () : int {
return 42;
}
}
];
}
- public function provideNotCountables () : iterable {
+ public static function provideNotCountables () : iterable {
yield [true];
yield [new \stdClass];
yield [0];
yield [""];
yield ["abc"];
}
- public function provideIterableAndFirst() : iterable {
+ public static function provideIterableAndFirst() : iterable {
yield ["a", ["a", "b", "c"]];
yield ["apple", ["fruit" => "apple", "vegetable" => "leeks"]];
yield [42, new class implements IteratorAggregate {
public function getIterator () : Traversable {
yield 42;
yield 100;
}
}];
}
}
diff --git a/tests/Collections/VectorTest.php b/tests/Collections/VectorTest.php
index b566313..49941b7 100644
--- a/tests/Collections/VectorTest.php
+++ b/tests/Collections/VectorTest.php
@@ -1,435 +1,432 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Collections;
+use Keruald\OmniTools\Collections\BaseVector;
use Keruald\OmniTools\Collections\HashMap;
use Keruald\OmniTools\Collections\Vector;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
use IteratorAggregate;
use OutOfRangeException;
use Traversable;
-/**
- * @covers \Keruald\OmniTools\Collections\Vector
- * @covers \Keruald\OmniTools\Collections\BaseVector
- */
+#[CoversClass(Vector::class)]
+#[CoversClass(BaseVector::class)]
class VectorTest extends TestCase {
private Vector $vector;
protected function setUp () : void {
$this->vector = new Vector([1, 2, 3, 4, 5]);
}
public function testConstructorWithIterable () : void {
$iterable = new class implements IteratorAggregate {
public function getIterator () : Traversable {
yield 42;
yield 100;
}
};
$vector = new Vector($iterable);
$this->assertEquals([42, 100], $vector->toArray());
}
public function testFrom () : void {
$this->assertEquals([42, 100], Vector::from([42, 100])->toArray());
}
public function testGet () : void {
$vector = new Vector(["a", "b", "c"]);
$this->assertEquals("b", $vector->get(1));
}
public function testGetOverflow () : void {
$this->expectException(InvalidArgumentException::class);
$this->vector->get(800);
}
public function testGetOr () : void {
$vector = new Vector(["a", "b", "c"]);
$this->assertEquals("X", $vector->getOr(800, "X"));
}
public function testSet () : void {
$vector = new Vector(["a", "b", "c"]);
$vector->set(1, "x"); // should replace "b"
$this->assertEquals(["a", "x", "c"], $vector->toArray());
}
public function testContains () : void {
$this->assertTrue($this->vector->contains(2));
$this->assertFalse($this->vector->contains(666));
}
public function testCount () : void {
$this->assertEquals(5, $this->vector->count());
$this->assertEquals(0, (new Vector)->count());
}
public function testClear () : void {
$this->vector->clear();
$this->assertEquals(0, $this->vector->count());
}
public function testIsEmpty () : void {
$this->vector->clear();
$this->assertTrue($this->vector->isEmpty());
}
public function testPush () : void {
$this->vector->push(6);
$this->assertEquals([1, 2, 3, 4, 5, 6], $this->vector->toArray());
}
public function testAppend () : void {
$this->vector->append([6, 7, 8]);
$this->assertEquals([1, 2, 3, 4, 5, 6, 7 ,8], $this->vector->toArray());
}
public function testUpdate () : void {
$this->vector->update([5, 5, 5, 6, 7, 8]); // 5 already exists
$this->assertEquals([1, 2, 3, 4, 5, 6, 7 ,8], $this->vector->toArray());
}
public function testMap () : void {
$actual = $this->vector
->map(function ($x) { return $x * $x; })
->toArray();
$this->assertEquals([1, 4, 9, 16, 25], $actual);
}
public function testMapKeys () : void {
$vector = new Vector(["foo", "bar", "quux", "xizzy"]);
$filter = function ($key) {
return 0; // Let's collapse our array
};
$actual = $vector->mapKeys($filter)->toArray();
$this->assertEquals(["xizzy"], $actual);
}
public function testFlatMap () : void {
$expected = [
// Squares and cubes
1, 1,
4, 8,
9, 27,
16, 64,
25, 125
];
$callback = function ($n) {
yield $n * $n;
yield $n * $n * $n;
};
$actual = $this->vector->flatMap($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFlatMapWithKeyValueCallback() : void {
$vector = new Vector(["foo", "bar", "quux", "xizzy"]);
$callback = function (int $key, string $value) {
yield "$key::$value";
yield "$value ($key)";
};
$expected = [
"0::foo",
"foo (0)",
"1::bar",
"bar (1)",
"2::quux",
"quux (2)",
"3::xizzy",
"xizzy (3)",
];
$actual = $vector->flatMap($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFlatMapWithCallbackWithoutArgument() : void {
$this->expectException(InvalidArgumentException::class);
$callback = function () {};
$this->vector->flatMap($callback);
}
public function testMapToHashMap () : void {
$expected = [
1 => 1,
2 => 4,
3 => 9,
4 => 16,
5 => 25,
];
$fn = fn($value) => [$value, $value * $value];
$map = $this->vector->mapToHashMap($fn);
$this->assertInstanceOf(HashMap::class, $map);
$this->assertEquals($expected, $map->toArray());
}
public function testMapToHashMapWithCallbackWithoutArgument() : void {
$this->expectException(InvalidArgumentException::class);
$callback = function () {};
$this->vector->mapToHashMap($callback);
}
public function testMapToHashMapWithBadCallback () : void {
$this->expectException(InvalidArgumentException::class);
$callback = fn($key, $value) : bool => false; // not an array
$this->vector->mapToHashMap($callback);
}
public function testFilter () : void {
$vector = new Vector(["foo", "bar", "quux", "xizzy"]);
$filter = function ($item) {
return strlen($item) === 3; // Let's keep 3-letters words
};
$actual = $vector->filter($filter)->toArray();
$this->assertEquals(["foo", "bar"], $actual);
}
public function testFilterWithBadCallback () : void {
$this->expectException(InvalidArgumentException::class);
$badFilter = function () {};
$this->vector->filter($badFilter);
}
public function testFilterKeys () : void {
$filter = function ($key) {
return $key % 2 === 0; // Let's keep even indices
};
$actual = $this->vector
->filterKeys($filter)
->toArray();
$this->assertEquals([0, 2, 4], array_keys($actual));
}
public function testChunk () : void {
$vector = new Vector([1, 2, 3, 4, 5, 6]);
$this->assertEquals(
[[1, 2], [3, 4], [5, 6]],
$vector->chunk(2)->toArray()
);
}
public function testSlice () : void {
$actual = $this->vector->slice(2, 3);
$this->assertEquals([3, 4, 5], $actual->toArray());
}
public function testImplode() : void {
$actual = (new Vector(["a", "b", "c"]))
->implode(".")
->__toString();
$this->assertEquals("a.b.c", $actual);
}
public function testImplodeWithoutDelimiter() : void {
$actual = (new Vector(["a", "b", "c"]))
->implode("")
->__toString();
$this->assertEquals("abc", $actual);
}
public function testExplode() : void {
$actual = Vector::explode(".", "a.b.c");
$this->assertEquals(["a", "b", "c"], $actual->toArray());
}
public function testExplodeWithoutDelimiter() : void {
$actual = Vector::explode("", "a.b.c");
$this->assertEquals(["a.b.c"], $actual->toArray());
}
///
/// n-grams
///
public function testBigrams() : void {
$expected = Vector::from([
[1, 2],
[2, 3],
[3, 4],
[4, 5],
]);
$this->assertEquals($expected, $this->vector->bigrams());
}
public function testTrigrams() : void {
$expected = Vector::from([
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
]);
$this->assertEquals($expected, $this->vector->trigrams());
}
public function testNgrams() : void {
$expected = Vector::from([
[1, 2, 3, 4],
[2, 3, 4, 5],
]);
$this->assertEquals($expected, $this->vector->ngrams(4));
}
public function testNgramsWithN1 () : void {
$expected = Vector::from([
[1],
[2],
[3],
[4],
[5],
]);
$this->assertEquals($expected, $this->vector->ngrams(1));
}
- private function provideLowN () : iterable {
+ public static function provideLowN () : iterable {
yield [0];
yield [-1];
yield [PHP_INT_MIN];
}
- /**
- * @dataProvider provideLowN
- */
+ #[DataProvider('provideLowN')]
public function testNgramsWithTooLowN ($n) : void {
$this->expectException(InvalidArgumentException::class);
$this->vector->ngrams($n);
}
- private function provideLargeN () : iterable {
+ public static function provideLargeN () : iterable {
yield [5];
yield [6];
yield [PHP_INT_MAX];
}
- /**
- * @dataProvider provideLargeN
- */
+ #[DataProvider('provideLargeN')]
public function testNgramsWithTooLargeN ($n) : void {
$expected = Vector::from([
[1, 2, 3, 4, 5],
]);
$this->assertEquals($expected, $this->vector->ngrams($n));
}
///
/// ArrayAccess
///
public function testArrayAccessFailsWithStringKey () : void {
$this->expectException(InvalidArgumentException::class);
$this->vector["foo"];
}
public function testOffsetExists () : void {
$this->assertTrue(isset($this->vector[0]));
$this->assertFalse(isset($this->vector[8]));
}
public function testOffsetSetWithoutOffset () : void {
$this->vector[] = 6;
$this->assertEquals(6, $this->vector[5]);
}
public function testOffsetSet () : void {
$this->vector[0] = 9;
$this->assertEquals(9, $this->vector[0]);
}
public function testOffsetUnset () : void {
unset($this->vector[2]);
$expected = [
0 => 1,
1 => 2,
// vector[2] has been unset
3 => 4,
4 => 5,
];
$this->assertEquals($expected, $this->vector->toArray());
}
///
/// IteratorAggregate
///
public function testGetIterator () : void {
$this->assertEquals([1, 2, 3, 4, 5], iterator_to_array($this->vector));
}
///
/// WithCollection trait
///
public function testFirst () : void {
$this->assertEquals(1, $this->vector->first());
}
public function testFirstWhenEmpty () : void {
$vector = new Vector;
$this->expectException(OutOfRangeException::class);
$vector->first();
}
public function testFirstOr () : void {
$this->assertEquals(1, $this->vector->firstOr(2));
}
public function testFirstOrWhenEmpty () : void {
$vector = new Vector;
$this->assertEquals(2, $vector->firstOr(2));
}
}
diff --git a/tests/Collections/WeightedValueTest.php b/tests/Collections/WeightedValueTest.php
index 06daca2..264ebab 100644
--- a/tests/Collections/WeightedValueTest.php
+++ b/tests/Collections/WeightedValueTest.php
@@ -1,101 +1,100 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Collections;
use Keruald\OmniTools\Collections\WeightedValue;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class WeightedValueTest extends TestCase {
/**
* @var WeightedValue
*/
private $lowValue;
/**
* @var WeightedValue
*/
private $highValue;
///
/// Fixtures
///
protected function setUp () : void {
$this->lowValue = new WeightedValue("LOW", 0.1);
$this->highValue = new WeightedValue("HIGH");
}
///
/// Tests
///
public function testGetWeight () : void {
$this->assertSame(0.1, $this->lowValue->getWeight());
$this->assertSame(
WeightedValue::DEFAULT_WEIGHT,
$this->highValue->getWeight()
);
}
public function testSetWeight () : void {
$this->lowValue->setWeight(0.2);
$this->assertSame(0.2, $this->lowValue->getWeight());
}
public function testGetValue () : void {
$this->assertEquals("LOW", $this->lowValue->getValue());
$this->assertEquals("HIGH", $this->highValue->getValue());
}
public function testSetValue () : void {
$this->lowValue->setValue("FOO");
$this->assertEquals("FOO", $this->lowValue->getValue());
}
public function testCompareTo () : void {
$this->assertEquals(
0,
$this->lowValue->compareTo($this->lowValue)
);
$this->assertEquals(
-1,
$this->lowValue->compareTo($this->highValue)
);
$this->assertEquals(
1,
$this->highValue->compareTo($this->lowValue)
);
}
public function testCompareToWithApplesAndPears () : void {
$this->expectException("TypeError");
$this->highValue->compareTo(new \stdClass);
}
- /**
- * @dataProvider provideExpressionsToParse
- */
+ #[DataProvider('provideExpressionsToParse')]
public function testParse ($expression, $expectedValue, $expectedWeight) : void {
$value = WeightedValue::Parse($expression);
$this->assertEquals($expectedValue, $value->getValue());
$this->assertEquals($expectedWeight, $value->getWeight());
}
///
/// Data providers
///
- public function provideExpressionsToParse () : iterable {
+ public static function provideExpressionsToParse () : iterable {
yield ["", "", 1.0];
yield ["de", "de", 1.0];
yield ["de;q=1.0", "de", 1.0];
yield ["de;q=0.7", "de", 0.7];
yield [";;q=0.7", ";", 0.7];
}
}
diff --git a/tests/Culture/Rome/RomanNumeralsTest.php b/tests/Culture/Rome/RomanNumeralsTest.php
index a129e1b..92bc03b 100644
--- a/tests/Culture/Rome/RomanNumeralsTest.php
+++ b/tests/Culture/Rome/RomanNumeralsTest.php
@@ -1,43 +1,42 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Culture\Rome;
use Keruald\OmniTools\Culture\Rome\RomanNumerals;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
class RomanNumeralsTest extends TestCase {
- /**
- * @dataProvider provideRomanAndHinduArabicNumerals
- */
+ #[DataProvider('provideRomanAndHinduArabicNumerals')]
public function testFromHindiArabicNumeral (
string $roman,
int $hinduArabic
) : void {
$this->assertEquals(
$roman,
RomanNumerals::fromHinduArabic($hinduArabic)
);
}
- public function provideRomanAndHinduArabicNumerals () : iterable {
+ public static function provideRomanAndHinduArabicNumerals () : iterable {
yield ['i', 1];
yield ['xi', 11];
yield ['xlii', 42];
yield ['mcmxcix', 1999];
yield ['mm', 2000];
}
public function testFromHindiArabicNumeralWithNegativeNumbers () : void {
$this->expectException(InvalidArgumentException::class);
RomanNumerals::fromHinduArabic(-1);
}
public function testFromHindiArabicNumeralWithZero () : void {
$this->expectException(InvalidArgumentException::class);
RomanNumerals::fromHinduArabic(0);
}
}
diff --git a/tests/DateTime/DateStampTest.php b/tests/DateTime/DateStampTest.php
index 1848eb8..3636e87 100644
--- a/tests/DateTime/DateStampTest.php
+++ b/tests/DateTime/DateStampTest.php
@@ -1,91 +1,90 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\DateTime;
use Keruald\OmniTools\DateTime\DateStamp;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use DateTime;
class DateStampTest extends TestCase {
///
/// Private members
///
/**
* @var DateStamp
*/
private $dateStamp;
///
/// Fixtures
///
protected function setUp () : void {
$this->dateStamp = new DateStamp(2010, 11, 25); // 25 November 2010
}
///
/// Tests
///
public function testToUnixTime () : void {
$this->assertEquals(1290643200, $this->dateStamp->toUnixTime());
}
public function testToDateTime () : void {
$expectedDateTime = new DateTime("2010-11-25");
$this->assertEquals($expectedDateTime, $this->dateStamp->toDateTime());
}
public function testToShortString () : void {
$this->assertEquals("20101125", $this->dateStamp->toShortString());
}
public function testToString () : void {
$this->assertEquals("2010-11-25", (string)$this->dateStamp);
}
public function testFromUnixTime () : void {
$this->assertEquals(
$this->dateStamp,
DateStamp::fromUnixTime(1290643200)
);
}
public function testParse () : void {
$this->assertEquals(
$this->dateStamp,
DateStamp::parse("2010-11-25")
);
$this->assertEquals(
$this->dateStamp,
DateStamp::parse("20101125")
);
}
- /**
- * @dataProvider provideInvalidDateStamps
- */
+ #[DataProvider('provideInvalidDateStamps')]
public function testParseWithInvalidFormat ($dateStamp) : void {
$this->expectException("InvalidArgumentException");
DateStamp::parse($dateStamp);
}
///
/// Data provider
///
- public function provideInvalidDateStamps () : iterable {
+ public static function provideInvalidDateStamps () : iterable {
yield ["10-11-25"];
yield ["2010-41-25"];
yield ["2010-11-99"];
yield ["20104125"];
yield ["20101199"];
}
}
diff --git a/tests/Debug/DebuggerTest.php b/tests/Debug/DebuggerTest.php
index 3433b92..ae2e81a 100644
--- a/tests/Debug/DebuggerTest.php
+++ b/tests/Debug/DebuggerTest.php
@@ -1,57 +1,55 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Debug;
use Keruald\OmniTools\Debug\Debugger;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class DebuggerTest extends TestCase {
///
/// Unit tests
///
public function testRegister () {
$this->assertTestSuiteStateIsValid();
Debugger::register();
$this->assertTrue(function_exists("dprint_r"));
}
private function assertTestSuiteStateIsValid() : void {
$this->assertFalse(
function_exists("dprint_r"),
"Configure the test suite so dprint_r isn't in global space first."
);
}
///
/// Integration tests
///
-
- /**
- * @dataProvider provideDebuggerScripts
- */
+ #[DataProvider('provideDebuggerScripts')]
public function testDebuggerScript ($script, $message) : void {
$this->assertProgramMatchesOutput($script, $message);
}
private function assertProgramMatchesOutput(string $script, string $message = "") : void {
$filename = __DIR__ . "/testers/$script";
$expected = file_get_contents($filename . ".txt");
$actual = `php $filename.php`;
$this->assertSame($expected, $actual, $message);
}
- public function provideDebuggerScripts () : iterable {
+ public static function provideDebuggerScripts () : iterable {
yield ["dump_integer", "Can't dump a variable"];
yield ["dump_array", "Can't dump an array"];
yield ["dump_object", "Can't dump an object"];
yield ["check_die", "printVariableAndDie doesn't die"];
}
}
diff --git a/tests/HTTP/Requests/RemoteAddressTest.php b/tests/HTTP/Requests/RemoteAddressTest.php
index 60aa490..c321d53 100644
--- a/tests/HTTP/Requests/RemoteAddressTest.php
+++ b/tests/HTTP/Requests/RemoteAddressTest.php
@@ -1,72 +1,59 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\HTTP\Requests;
use Keruald\OmniTools\HTTP\Requests\RemoteAddress;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class RemoteAddressTest extends TestCase {
///
/// Tests
///
- /**
- * @covers \Keruald\OmniTools\HTTP\Requests\RemoteAddress::getClientAddress
- * @covers \Keruald\OmniTools\HTTP\Requests\RemoteAddress::getAll
- * @covers \Keruald\OmniTools\HTTP\Requests\RemoteAddress::has
- */
public function testEmptyRequest () : void {
$address = new RemoteAddress;
$this->assertEmpty($address->getClientAddress());
$this->assertEmpty($address->getAll());
$this->assertFalse($address->has());
}
- /**
- * @covers \Keruald\OmniTools\HTTP\Requests\RemoteAddress::getClientAddress
- * @dataProvider provideTenZeroZeroThreeHeaderValues
- */
+ #[DataProvider("provideTenZeroZeroThreeHeaderValues")]
public function testGetOne (string $value) : void {
$address = new RemoteAddress($value);
$this->assertEquals('10.0.0.3', $address->getClientAddress());
}
- /**
- * @covers \Keruald\OmniTools\HTTP\Requests\RemoteAddress::getClientAddress
- * @dataProvider provideTenZeroZeroThreeHeaderValues
- */
+ #[DataProvider("provideTenZeroZeroThreeHeaderValues")]
public function testGetAll (string $value) : void {
$address = new RemoteAddress($value);
$this->assertEquals($value, $address->getAll());
}
- /**
- * @covers \Keruald\OmniTools\HTTP\Requests\RemoteAddress::has
- * @dataProvider provideTenZeroZeroThreeHeaderValues
- */
+ #[DataProvider("provideTenZeroZeroThreeHeaderValues")]
public function testHas (string $value) : void {
$address = new RemoteAddress($value);
$this->assertTrue($address->has());
}
///
/// Data provider
///
- public function provideTenZeroZeroThreeHeaderValues () : iterable {
+ public static function provideTenZeroZeroThreeHeaderValues () : iterable {
return [
// Each value should return 10.0.0.3
['10.0.0.3'],
['10.0.0.3,10.0.0.4'],
['10.0.0.3, 10.0.0.4'],
['10.0.0.3, 10.0.0.4, lorem ipsum dolor'],
];
}
}
diff --git a/tests/HTTP/Requests/RequestTest.php b/tests/HTTP/Requests/RequestTest.php
index 672f43f..8f8189c 100644
--- a/tests/HTTP/Requests/RequestTest.php
+++ b/tests/HTTP/Requests/RequestTest.php
@@ -1,155 +1,143 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\HTTP\Requests;
use Keruald\OmniTools\HTTP\Requests\Request;
+use PHPUnit\Framework\Attributes\BackupGlobals;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class RequestTest extends TestCase {
///
/// Tests
///
-
- /**
- * @covers \Keruald\OmniTools\HTTP\Requests\Request::getRemoteAddress
- * @backupGlobals enabled
- */
+ #[BackupGlobals(true)]
public function testGetRemoteAddress () : void {
$this->assertEmpty(Request::getRemoteAddress());
$_SERVER = [
'REMOTE_ADDR' => '10.0.0.2',
];
$this->assertEquals('10.0.0.2', Request::getRemoteAddress());
$_SERVER += [
'HTTP_X_FORWARDED_FOR' => '10.0.0.3',
'HTTP_CLIENT_IP' => '10.0.0.4',
];
$this->assertEquals(
'10.0.0.3', Request::getRemoteAddress(),
"HTTP_X_FORWARDED_FOR must be prioritized."
);
}
- /**
- * @covers \Keruald\OmniTools\HTTP\Requests\Request::getClientAddress
- * @backupGlobals enabled
- */
+ #[BackupGlobals(true)]
public function testGetRemoteAddressWithSeveralAddresses () : void {
$_SERVER = [
'HTTP_X_FORWARDED_FOR' => '10.0.0.2 10.0.0.3',
];
$this->assertEquals('10.0.0.2', Request::getRemoteAddress(),
"HTTP_X_FORWARDED_FOR could contain more than one address, the client one is the first"
);
$_SERVER = [
'HTTP_X_FORWARDED_FOR' => '10.0.0.2, 10.0.0.3',
];
$this->assertEquals('10.0.0.2', Request::getRemoteAddress(),
"HTTP_X_FORWARDED_FOR could contain more than one address, the client one is the first"
);
}
- /**
- * @covers \Keruald\OmniTools\HTTP\Requests\Request::getAcceptedLanguages
- * @backupGlobals enabled
- */
+ #[BackupGlobals(true)]
public function testGetAcceptedLanguages () : void {
$_SERVER = [
'HTTP_ACCEPT_LANGUAGE' => 'fr,en-US;q=0.7,en;q=0.3',
];
$this->assertEquals(
["fr", "en-US", "en"],
Request::getAcceptedLanguages()
);
}
- /**
- * @backupGlobals enabled
- * @dataProvider provideServerURLs
- */
+ #[DataProvider('provideServerURLs')]
+ #[BackupGlobals(true)]
public function testGetServerURL (array $server, string $url) : void {
$_SERVER = $server;
$this->assertEquals($url, Request::getServerURL());
}
- /**
- * @backupGlobals enabled
- * @dataProvider provideServerURLs
- */
+ #[DataProvider('provideServerURLs')]
+ #[BackupGlobals(true)]
public function testCreateLocalURL (array $server, string $url) : void {
$_SERVER = $server;
$this->assertEquals(
$url . "/",
Request::createLocalURL()->__toString()
);
$this->assertEquals(
$url . "/foo",
Request::createLocalURL("foo")->__toString()
);
}
///
/// Data providers
///
- public function provideServerURLs () : iterable {
+ public static function provideServerURLs () : iterable {
yield [[], "http://localhost"];
yield [["UNRELATED" => "ANYTHING"], "http://localhost"];
yield [
[
"SERVER_PORT" => "80",
"SERVER_NAME" => "acme.tld",
],
"http://acme.tld"
];
yield [
[
"SERVER_PORT" => "443",
"SERVER_NAME" => "acme.tld",
],
"https://acme.tld"
];
yield [
[
"SERVER_PORT" => "80",
"SERVER_NAME" => "acme.tld",
"HTTP_X_FORWARDED_PROTO" => "https",
],
"https://acme.tld"
];
yield [
[
"SERVER_PORT" => "80",
"SERVER_NAME" => "acme.tld",
"HTTP_FORWARDED" => "for=192.0.2.43, for=\"[2001:db8:cafe::17]\", proto=https, by=203.0.113.43",
],
"https://acme.tld"
];
yield [
[
"SERVER_PORT" => "8443",
"SERVER_NAME" => "acme.tld",
"HTTPS" => "on",
],
"https://acme.tld:8443"
];
}
}
diff --git a/tests/HTTP/URLTest.php b/tests/HTTP/URLTest.php
index 3b8802c..f7fce5d 100644
--- a/tests/HTTP/URLTest.php
+++ b/tests/HTTP/URLTest.php
@@ -1,90 +1,83 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\HTTP;
use Keruald\OmniTools\HTTP\URL;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class URLTest extends TestCase {
- /**
- * @dataProvider provideURLsAndComponents
- */
+ #[DataProvider('provideURLsAndComponents')]
public function testGetDomain ($url, $expectedDomain) : void {
$url = new URL($url);
$this->assertEquals($expectedDomain, $url->getDomain());
}
- /**
- * @dataProvider provideURLsAndComponents
- */
+ #[DataProvider('provideURLsAndComponents')]
public function testGetProtocol ($url, $_, $expectedProtocol) : void {
$url = new URL($url);
$this->assertEquals($expectedProtocol, $url->getProtocol());
}
- /**
- * @dataProvider provideURLsAndComponents
- */
+ #[DataProvider('provideURLsAndComponents')]
public function testGetQuery ($url, $_, $__, $expectedQuery) : void {
$url = new URL($url);
$this->assertEquals($expectedQuery, $url->getQuery());
}
public function testSetProtocol () : void {
$url = new URL("https://acme.tld/foo");
$url->setProtocol("xizzy");
$this->assertEquals("xizzy", $url->getProtocol());
}
public function testSetDomain () : void {
$url = new URL("https://acme.tld/foo");
$url->setDomain("xizzy");
$this->assertEquals("xizzy", $url->getDomain());
}
public function testSetQuery () : void {
$url = new URL("https://acme.tld/foo");
$url->setQuery("/xizzy");
$this->assertEquals("/xizzy", $url->getQuery());
}
public function testSetQueryWithSlashForgotten () : void {
$url = new URL("https://acme.tld/foo");
$url->setQuery("xizzy");
$this->assertEquals("/xizzy", $url->getQuery());
}
- /**
- * @dataProvider provideURLsAndComponents
- */
+ #[DataProvider('provideURLsAndComponents')]
public function testCompose ($url, $domain, $protocol, $query,
$expectedUrl = null) {
$this->assertEquals(
$expectedUrl ?? $url,
URL::compose($protocol, $domain, $query)->__toString()
);
}
- public function provideURLsAndComponents () : iterable {
+ public static function provideURLsAndComponents () : iterable {
// base URL, domain, protocol, query[, expected URL]
// When omitted, the expected URL is the base URL.
yield ["http://foo/bar", "foo", "http", "/bar"];
yield ["https://xn--dghrefn-mxa.nasqueron.org/", "dæghrefn.nasqueron.org", "https", "/"];
yield ["://foo/bar", "foo", "", "/bar"];
yield ["/bar", "", "", "/bar"];
yield ["http://foo/bar%20quux", "foo", "http", "/bar quux"];
yield ["https://foo/", "foo", "https", "/"];
yield ["https://foo", "foo", "https", "/", "https://foo/"];
}
}
diff --git a/tests/IO/FileTest.php b/tests/IO/FileTest.php
index 3d15e50..22667b7 100644
--- a/tests/IO/FileTest.php
+++ b/tests/IO/FileTest.php
@@ -1,101 +1,93 @@
<?php
namespace Keruald\OmniTools\Tests\IO;
use Keruald\OmniTools\IO\File;
use Keruald\OmniTools\OS\CurrentOS;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use TypeError;
class FileTest extends TestCase {
///
/// Tests
///
-
- /**
- * @dataProvider provideFilesAndDirectories
- */
+ #[DataProvider('provideFilesAndDirectories')]
public function testGetDirectory (string $filename, string $expected) : void {
if (CurrentOS::isPureWindows()) {
$this->markTestSkipped("This test is intended for UNIX systems.");
}
$this->assertSame($expected, File::from($filename)->getDirectory());
}
- /**
- * @dataProvider provideFilesAndFileNames
- */
+ #[DataProvider('provideFilesAndFileNames')]
public function testGetFileName (string $filename, string $expected) : void {
$this->assertSame($expected, File::from($filename)->getFileName());
}
- /**
- * @dataProvider provideFilesAndFileNamesWithoutExtension
- */
+ #[DataProvider('provideFilesAndFileNamesWithoutExtension')]
public function testGetFileNameWithoutExtension (string $filename, string $expected) : void {
$this->assertSame($expected, File::from($filename)->getFileNameWithoutExtension());
}
- /**
- * @dataProvider provideFilesAndExtensions
- */
+ #[DataProvider('provideFilesAndExtensions')]
public function testGetExtension (string $filename, string $expected) : void {
$this->assertSame($expected, File::from($filename)->getExtension());
}
///
/// Issues
///
/**
* @see https://devcentral.nasqueron.org/D2494
*/
public function testNullPathIsNotAllowed () : void {
$this->expectException(TypeError::class);
$file = new File(null);
}
///
/// Data providers
///
- public function provideFilesAndDirectories () : iterable {
+ public static function provideFilesAndDirectories () : iterable {
yield ['', ''];
yield ['/', '/'];
yield ['/foo', '/'];
yield ['foo/bar', 'foo'];
yield ['foo/', '.'];
yield ['/full/path/to/foo.php', '/full/path/to'];
}
- public function provideFilesAndFileNames () : iterable {
+ public static function provideFilesAndFileNames () : iterable {
yield ['', ''];
yield ['foo', 'foo'];
yield ['foo', 'foo'];
yield ['foo.php', 'foo.php'];
yield ['/full/path/to/foo.php', 'foo.php'];
}
- public function provideFilesAndFileNamesWithoutExtension () : iterable {
+ public static function provideFilesAndFileNamesWithoutExtension () : iterable {
yield ['', ''];
yield ['foo', 'foo'];
yield ['foo.php', 'foo'];
yield ['/full/path/to/foo.php', 'foo'];
yield ['foo.tar.gz', 'foo.tar'];
}
- public function provideFilesAndExtensions () : iterable {
+ public static function provideFilesAndExtensions () : iterable {
yield ['', ''];
yield ['foo', ''];
yield ['foo.php', 'php'];
yield ['/full/path/to/foo.php', 'php'];
yield ['foo.tar.gz', 'gz'];
}
}
diff --git a/tests/Identifiers/RandomTest.php b/tests/Identifiers/RandomTest.php
index 38a858e..3f76c5a 100644
--- a/tests/Identifiers/RandomTest.php
+++ b/tests/Identifiers/RandomTest.php
@@ -1,61 +1,60 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Identifiers;
use Keruald\OmniTools\Identifiers\Random;
-use Phpunit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\TestCase;
class RandomTest extends TestCase {
///
/// Tests
///
public function testGenerateHexadecimalHash () : void {
$hash = Random::generateHexHash();
$this->assertEquals(
32, strlen($hash),
"$hash size must be 32 characters"
);
$this->assertMatchesRegularExpression("/[0-9a-f]{32}/", $hash);
}
public function testHexadecimalHashesAreUnique() : void {
$this->assertNotEquals(
Random::generateHexHash(),
Random::generateHexHash()
);
}
- /**
- * @dataProvider provideRandomStringFormats
- */
+ #[DataProvider('provideRandomStringFormats')]
public function testRandomString($format, $re, $len) : void {
$string = Random::generateString($format);
$this->assertEquals($len, strlen($format));
$this->assertMatchesRegularExpression($re, $string);
}
public function testGenerateIdentifier() : void {
$identifier = Random::generateIdentifier(20);
$this->assertEquals(27, strlen($identifier));
$this->assertMatchesRegularExpression("/^[A-Z0-9\-_]*$/i", $identifier);
}
///
/// Data providers
///
- public function provideRandomStringFormats() : iterable {
+ public static function provideRandomStringFormats() : iterable {
yield ["AAA111", "/^[A-Z]{3}[0-9]{3}$/", 6];
yield ["AAA123", "/^[A-Z]{3}[0-9]{3}$/", 6];
yield ["ABC123", "/^[A-Z]{3}[0-9]{3}$/", 6];
yield ["", "/^$/", 0];
}
}
diff --git a/tests/Identifiers/UUIDTest.php b/tests/Identifiers/UUIDTest.php
index e5404c9..283f1a9 100644
--- a/tests/Identifiers/UUIDTest.php
+++ b/tests/Identifiers/UUIDTest.php
@@ -1,275 +1,268 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Identifiers;
use InvalidArgumentException;
use Keruald\OmniTools\Collections\BitsVector;
use Keruald\OmniTools\Collections\Vector;
use Keruald\OmniTools\DateTime\UUIDv1TimeStamp;
use Keruald\OmniTools\Identifiers\UUID;
-use Phpunit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\TestCase;
class UUIDTest extends TestCase {
public function testUUIDv1 () : void {
$uuid = UUID::UUIDv1();
$this->assertEquals(
36, strlen($uuid),
"UUID size must be 36 characters."
);
$re = "/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/";
$this->assertMatchesRegularExpression($re, $uuid);
$this->assertEquals(1, UUID::getVersion($uuid));
}
public function testUUIDV1WithMac () : void {
$uuid = UUID::UUIDv1("00-00-5E-00-53-00");
$macFromUUID = BitsVector::fromDecoratedHexString($uuid)
->slice(80, 48)
->toBytesArray();
$this->assertSame([0, 0, 0x5E, 0, 0x53, 0], $macFromUUID);
}
public function testUUIDv1FromValuesWithBadCount () : void {
$this->expectException(InvalidArgumentException::class);
$node = BitsVector::new(0); // too small, must be 48
UUID::UUIDv1FromValues(UUIDv1TimeStamp::now(), 0, 0, $node);
}
public function testUUIDv4 () : void {
$uuid = UUID::UUIDv4();
$this->assertEquals(
36, strlen($uuid),
"UUID size must be 36 characters."
);
$re = "/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/";
$this->assertMatchesRegularExpression($re, $uuid);
}
public function testUUIDv4WithoutHyphens () : void {
$uuid = UUID::UUIDv4WithoutHyphens();
$this->assertEquals(
32, strlen($uuid),
"UUID size must be 36 characters, and there are 4 hyphens, so here 32 characters are expected."
);
$re = "/[0-9a-f]/";
$this->assertMatchesRegularExpression($re, $uuid);
}
public function testUUIDv4AreUnique () : void {
$this->assertNotEquals(UUID::UUIDv4(), UUID::UUIDv4());
}
public function testUUIDv6 () : void {
$uuid = UUID::UUIDv6();
$this->assertEquals(
36, strlen($uuid),
"UUID size must be 36 characters."
);
$re = "/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/";
$this->assertMatchesRegularExpression($re, $uuid);
$this->assertEquals(6, UUID::getVersion($uuid));
}
public function testUUIDV6WithMac () : void {
$uuid = UUID::UUIDv6("00-00-5E-00-53-00");
$macFromUUID = BitsVector::fromDecoratedHexString($uuid)
->slice(80, 48)
->toBytesArray();
$this->assertSame([0, 0, 0x5E, 0, 0x53, 0], $macFromUUID);
}
public function testUUIDv6FromValuesWithBadCount () : void {
$this->expectException(InvalidArgumentException::class);
$node = BitsVector::new(0); // too small, must be 48
UUID::UUIDv6FromValues(UUIDv1TimeStamp::now(), 0, 0, $node);
}
public function testUUIDv8 () : void {
$this->assertEquals(
"320c3d4d-cc00-875b-8ec9-32d5f69181c0",
UUID::UUIDv8(0x320C3D4DCC00, 0x75B, 0xEC932D5F69181C0)
);
}
- public function provideUUIDV8OverflowValues () : iterable {
+ public static function provideUUIDV8OverflowValues () : iterable {
yield [PHP_INT_MAX, 0x75B, 0xEC932D5F69181C0];
yield [0x320C3D4DCC00, PHP_INT_MAX, 0xEC932D5F69181C0];
yield [0x320C3D4DCC00, 0x75B, PHP_INT_MAX];
}
- /**
- * @dataProvider provideUUIDV8OverflowValues
- */
+ #[DataProvider('provideUUIDV8OverflowValues')]
public function testUUIDV8WithOverflowValues ($a, $b, $c) : void {
$this->expectException(InvalidArgumentException::class);
UUID::UUIDv8($a, $b, $c);
}
public function testUUIDv7FromValues () : void {
$this->assertEquals(
"017f21cf-d130-7cc3-98c4-dc0c0c07398f",
UUID::UUIDv7FromValues(0x017F21CFD130, 0xCC3, 0x18C4DC0C0C07398F)
);
}
public function testUUIDv7 () : void {
$uuid = UUID::UUIDv7();
$this->assertEquals(
36, strlen($uuid),
"UUID size must be 36 characters."
);
$re = "/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/";
$this->assertMatchesRegularExpression($re, $uuid);
}
public function testUUIDv7FromBitsWithBadCount () : void {
$this->expectException(InvalidArgumentException::class);
UUID::UUIDv7FromBits(BitsVector::new(0), 0xCC3, 0x18C4DC0C0C07398F);
}
///
/// Tests for convert between UUID methods
///
public function testUUIDv1ToUUIDv6 () : void {
$this->assertEquals(
"1ec9414c-232a-6b00-b3c8-9e6bdeced846",
UUID::UUIDv1ToUUIDv6("c232ab00-9414-11ec-b3c8-9e6bdeced846")
);
}
public function testUUIDv6ToUUIDv1 () : void {
$this->assertEquals(
"c232ab00-9414-11ec-b3c8-9e6bdeced846",
UUID::UUIDv6ToUUIDv1("1ec9414c-232a-6b00-b3c8-9e6bdeced846")
);
}
///
/// Tests for helper methods
///
- public function provideFormattedUUID () : iterable {
+ public static function provideFormattedUUID () : iterable {
yield [
"320c3d4dcc00875b8ec932d5f69181c0",
"320c3d4d-cc00-875b-8ec9-32d5f69181c0",
];
yield [
"320c3d4d-cc00-875b-8ec9-32d5f69181c0",
"320c3d4d-cc00-875b-8ec9-32d5f69181c0",
];
yield [
"320C3D4D-CC00-875B-8EC9-32D5F69181C0",
"320c3d4d-cc00-875b-8ec9-32d5f69181c0",
];
}
- /**
- * @dataProvider provideFormattedUUID
- */
+ #[DataProvider('provideFormattedUUID')]
public function testReformat($uuidToReformat, $expected) {
$this->assertEquals($expected, UUID::reformat($uuidToReformat));
}
public function testIsUUID () : void {
$this->assertTrue(UUID::isUUID("e14d5045-4959-11e8-a2e6-0007cb03f249"));
$this->assertFalse(
UUID::isUUID("e14d5045-4959-11e8-a2e6-0007cb03f249c"),
"The method shouldn't allow arbitrary size strings."
);
$this->assertFalse(UUID::isUUID("d825a90a27e7f161a07161c3a37dce8e"));
}
- private function provideUUIDsWithVersionAndVariant () : iterable {
+ public static function provideUUIDsWithVersionAndVariant () : iterable {
// RFC 4122
yield ["c232ab00-9414-11ec-b3c8-9e6bdeced846", 1, 2];
yield ["f6244210-bbc3-3689-bb54-76528802d4d5", 3, 2];
yield ["23b50a2e-0543-4eaa-a53f-2a9dd02606e7", 4, 2];
yield ["2f8c2178-9c05-55ba-9b69-f4e076017270", 5, 2];
// draft-peabody-dispatch-new-uuid-format-03
yield ["1ec9414c-232a-6b00-b3c8-9e6bdeced846", 6, 2];
yield ["018003e1-0e46-7c62-9e4e-63cda74165ea", 7, 2];
yield ["320c3d4d-cc00-875b-8ec9-32d5f69181c0", 8, 2];
// Special values from both RFC
yield [UUID::NIL, 0, 0];
yield [UUID::MAX, 15, 3];
}
- /**
- * @dataProvider provideUUIDsWithVersionAndVariant
- */
+ #[DataProvider('provideUUIDsWithVersionAndVariant')]
public function testGetVersion (string $uuid, int $version, int $variant) : void {
$this->assertEquals($version, UUID::getVersion($uuid));
}
- /**
- * @dataProvider provideUUIDsWithVersionAndVariant
- */
+ #[DataProvider('provideUUIDsWithVersionAndVariant')]
public function testGetVariant (string $uuid, int $version, int $variant) : void {
$this->assertEquals($variant, UUID::getVariant($uuid));
}
///
/// Monotonicity :: UUIDv6 UUIDv7
///
private function assertMonotonicity (iterable $series) : void {
$bigrams = Vector::from($series)->bigrams();
foreach ($bigrams as $bigram) {
$this->assertGreaterThan($bigram[0], $bigram[1]);
}
}
public function testMonotonicityForUUIDv6 () {
$series = Vector::range(0, 99)->map(fn($_) => UUID::UUIDv6());
$this->assertMonotonicity($series);
}
public function testMonotonicityForSlowlyGeneratedUUIDv7 () {
$series = Vector::range(0, 99)->map(function ($_) {
usleep(1000);
return UUID::UUIDv7();
});
$this->assertMonotonicity($series);
}
public function testMonotonicityForBatchesOfUUIDv7WhenBatchQuantityIsSmallEnough () {
$series = UUID::batchOfUUIDv7(63);
$this->assertMonotonicity($series);
}
public function testMonotonicityForBatchesOfUUIDv7 () {
$series = UUID::batchOfUUIDv7(1000);
$this->assertCount(1000, $series);
$this->assertMonotonicity($series);
}
}
diff --git a/tests/Network/IPTest.php b/tests/Network/IPTest.php
index e1b3b4e..5885570 100644
--- a/tests/Network/IPTest.php
+++ b/tests/Network/IPTest.php
@@ -1,148 +1,125 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Network;
use Keruald\OmniTools\Network\IP;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class IPTest extends TestCase {
///
/// Data providers for IP addresses
///
/// These data providers methods allow providing IP addresses
/// to validate or invalidate.
///
/// The advanced IPv6 tests have been curated by Stephen Ryan
/// Source: https://web.archive.org/web/20110515134717/http://forums.dartware.com/viewtopic.php?t=452
///
- public function provideValidIP () : iterable {
+ public static function provideValidIP () : iterable {
yield ["0.0.0.0"];
yield ["17.17.17.17"];
yield ["fe80:0000:0000:0000:0204:61ff:fe9d:f156"];
}
- public function provideInvalidIP () : iterable {
+ public static function provideInvalidIP () : iterable {
yield [""];
yield ["1"];
yield ["17.17"];
yield ["17.17.17.256"];
}
- public function provideValidIPv4 () : iterable {
+ public static function provideValidIPv4 () : iterable {
return [["0.0.0.0"], ["17.17.17.17"]];
}
- public function provideInvalidIPv4 () : iterable {
+ public static function provideInvalidIPv4 () : iterable {
yield [""];
yield ["1"];
yield ["17.17"];
yield ["17.17.17.256"];
yield ["fe80:0000:0000:0000:0204:61ff:fe9d:f156"];
}
- public function provideValidIPv6 () : iterable {
+ public static function provideValidIPv6 () : iterable {
yield ["::1"];
yield ["::ffff:192.0.2.128"];
yield ["fe80:0000:0000:0000:0204:61ff:fe9d:f156"];
yield ["::ffff:192.0.2.128", "IPv4 represented as dotted-quads"];
}
- public function provideInvalidIPv6 () : iterable {
+ public static function provideInvalidIPv6 () : iterable {
yield ["0.0.0.0"];
yield [""];
yield ["1"];
yield ["17.17"];
yield ["17.17.17.17"];
yield ["::fg", "Valid IPv6 digits are 0-f, ie 0-9 and a-f"];
yield ["02001:0000:1234:0000:0000:C1C0:ABCD:0876", "Extra 0"];
yield ["2001:0000:1234:0000:00001:C1C0:ABCD:0876", "Extra 0"];
yield ["1.2.3.4:1111:2222:3333:4444::5555"];
}
- public function provideValidLoopbackIP () : iterable {
+ public static function provideValidLoopbackIP () : iterable {
yield ["127.0.0.1"];
yield ["127.0.0.3"];
yield ["::1"];
}
- public function provideInvalidLoopbackIP () : iterable {
+ public static function provideInvalidLoopbackIP () : iterable {
yield ["0.0.0.0"];
yield ["1.2.3.4"];
yield ["192.168.1.1"];
yield ["::2"];
}
///
/// Test cases
///
- /**
- * @covers \Keruald\OmniTools\Network\IP::isIP
- * @dataProvider provideValidIP
- */
+ #[DataProvider("provideValidIP")]
public function testIsIP ($ip) {
$this->assertTrue(IP::isIP($ip));
}
- /**
- * @covers \Keruald\OmniTools\Network\IP::isIP
- * @dataProvider provideInvalidIP
- */
+ #[DataProvider("provideInvalidIP")]
public function testIsIPWhenItIsNot ($ip) {
$this->assertFalse(IP::isIP($ip));
}
- /**
- * @covers \Keruald\OmniTools\Network\IP::isIPv4
- * @dataProvider provideValidIPv4
- */
+ #[DataProvider("provideValidIPv4")]
public function testIsIPv4 ($ip) {
$this->assertTrue(IP::isIPv4($ip));
}
- /**
- * @covers \Keruald\OmniTools\Network\IP::isIPv4
- * @dataProvider provideInvalidIPv4
- */
+ #[DataProvider("provideInvalidIPv4")]
public function testIsIPv4WhenItIsNot ($ip) {
$this->assertFalse(IP::isIPv4($ip));
}
- /**
- * @covers \Keruald\OmniTools\Network\IP::isIPv6
- * @dataProvider provideValidIPv6
- */
+ #[DataProvider("provideValidIPv6")]
public function testIsIPv6 (string $ip, string $message = "") {
$this->assertTrue(IP::isIPv6($ip), $message);
}
- /**
- * @covers \Keruald\OmniTools\Network\IP::isIPv6
- * @dataProvider provideInvalidIPv6
- */
+ #[DataProvider("provideInvalidIPv6")]
public function testIsIPv6WhenItIsNot (string $ip, string $message = "") : void {
$this->assertFalse(IP::isIPv6($ip), $message);
}
- /**
- * @covers \Keruald\OmniTools\Network\IP::isLoopback
- * @dataProvider provideValidLoopbackIP
- */
+ #[DataProvider("provideValidLoopbackIP")]
public function testIsLoopback (string $ip) : void {
$this->assertTrue(IP::isLoopback($ip));
}
- /**
- * @covers \Keruald\OmniTools\Network\IP::isLoopback
- * @dataProvider provideInvalidLoopbackIP
- */
+ #[DataProvider("provideInvalidLoopbackIP")]
public function testIsLoopbackWhenItIsNot (string $ip) : void {
$this->assertFalse(IP::isLoopback($ip));
}
}
diff --git a/tests/OS/EnvironmentTest.php b/tests/OS/EnvironmentTest.php
index 9c3f5d4..8214363 100644
--- a/tests/OS/EnvironmentTest.php
+++ b/tests/OS/EnvironmentTest.php
@@ -1,70 +1,65 @@
<?php
namespace Keruald\OmniTools\Tests\OS;
use InvalidArgumentException;
use Keruald\OmniTools\OS\Environment;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class EnvironmentTest extends TestCase {
protected function setUp () : void {
// Keep in sync with provideEnvironment data provider
$_ENV['foo'] = "bar";
$_SERVER['foo'] = "baz";
$_ENV['bar'] = "lorem";
$_SERVER['baz'] = "ipsum";
// And quux isn't defined.
}
- public function provideEnvironment () : iterable {
+ public static function provideEnvironment () : iterable {
yield ["foo", "bar"];
yield ["bar", "lorem"];
yield ["baz", "ipsum"];
}
- public function provideEnvironmentKeys () : iterable {
- foreach ($this->provideEnvironment() as $kv) {
+ public static function provideEnvironmentKeys () : iterable {
+ foreach (self::provideEnvironment() as $kv) {
yield [$kv[0]];
}
}
- /**
- * @dataProvider provideEnvironmentKeys
- */
+ #[DataProvider('provideEnvironmentKeys')]
public function testHas (string $key) : void {
self::assertTrue(Environment::has($key));
}
- /**
- * @dataProvider provideEnvironment
- */
+ #[DataProvider('provideEnvironment')]
public function testGet (string $key, string $value) : void {
self::assertSame($value, Environment::get($key));
}
- /**
- * @dataProvider provideEnvironment
- */
+ #[DataProvider('provideEnvironment')]
public function testGetOrWhenKeyExists (string $key, string $value) : void {
self::assertSame($value, Environment::getOr($key, "default"));
}
public function testHasWhenKeyDoesNotExist () : void {
self::assertFalse(Environment::has("quux"));
}
public function testGetWhenKeyDoesNotExist () : void {
$this->expectException(InvalidArgumentException::class);
Environment::get("quux");
}
public function testGetOrWhenKeyDoesNotExist () : void {
self::assertSame("default", Environment::getOr("quux", "default"));
}
}
diff --git a/tests/Reflection/CodeFunctionTest.php b/tests/Reflection/CodeFunctionTest.php
index 1b319f6..64d009e 100644
--- a/tests/Reflection/CodeFunctionTest.php
+++ b/tests/Reflection/CodeFunctionTest.php
@@ -1,46 +1,45 @@
<?php
namespace Keruald\OmniTools\Tests\Reflection;
use Keruald\OmniTools\Reflection\CodeFunction;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
use ReflectionFunction;
use ReflectionParameter;
class CodeFunctionTest extends TestCase {
- /**
- * @dataProvider provideFunctionParameters
- */
+ #[DataProvider('provideFunctionParameters')]
public function testGetParameterType (ReflectionParameter $parameter, string $type) {
$this->assertEquals($type, CodeFunction::getParameterType($parameter));
}
public function testGetParameterTypeWhenNoTypeIsDefined () {
$this->expectException(InvalidArgumentException::class);
$function = new ReflectionFunction("Keruald\OmniTools\Tests\Reflection\doSomething");
$parameters = $function->getParameters();
CodeFunction::getParameterType($parameters[0]);
}
///
/// Data provider
///
- public function provideFunctionParameters () : iterable {
+ public static function provideFunctionParameters () : iterable {
// array_change_key_case(array $array, int $case = CASE_LOWER): array
$function = new ReflectionFunction("array_change_key_case");
$parameters = $function->getParameters();
yield [$parameters[0], "array"];
yield [$parameters[1], "int"];
}
}
function doSomething ($mixed) : void {
}
diff --git a/tests/Reflection/CodeVariableTest.php b/tests/Reflection/CodeVariableTest.php
index 11a5a10..1a8eade 100644
--- a/tests/Reflection/CodeVariableTest.php
+++ b/tests/Reflection/CodeVariableTest.php
@@ -1,66 +1,63 @@
<?php
namespace Keruald\OmniTools\Tests\Reflection;
use Keruald\OmniTools\Collections\Vector;
use Keruald\OmniTools\Reflection\CodeVariable;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class CodeVariableTest extends TestCase {
public function testHasTypeWithObject () {
$object = new Vector;
$variable = CodeVariable::from($object);
$this->assertTrue($variable->hasType(Vector::class));
}
- /**
- * @dataProvider provideScalarsAndTypes
- */
+ #[DataProvider('provideScalarsAndTypes')]
public function testHasTypeWithScalar (mixed $scalar, string $type) {
$variable = CodeVariable::from($scalar);
$this->assertTrue($variable->hasType($type));
}
- /**
- * @dataProvider provideScalars
- */
+ #[DataProvider('provideScalars')]
public function testFromWithScalar (mixed $scalar) {
$variable = CodeVariable::from($scalar);
$this->assertInstanceOf(CodeVariable::class, $variable);
}
public function testFromWithObject () {
$object = new Vector;
$variable = CodeVariable::from($object);
$this->assertInstanceOf(CodeVariable::class, $variable);
}
///
/// Data providers
///
- private function provideScalars () : iterable {
+ public static function provideScalars () : iterable {
yield [0];
yield [""];
yield [19];
yield ["This is Sparta."];
yield [true];
yield [false];
yield [null];
}
- private function provideScalarsAndTypes () : iterable {
+ public static function provideScalarsAndTypes () : iterable {
yield [0, "integer"];
yield ["", "string"];
yield [19, "integer"];
yield ["This is Sparta.", "string"];
yield [true, "boolean"];
yield [false, "boolean"];
yield [null, "NULL"];
}
}
diff --git a/tests/Registration/PSR4/PSR4NamespaceTest.php b/tests/Registration/PSR4/PSR4NamespaceTest.php
index 93dffc5..0ec53f2 100644
--- a/tests/Registration/PSR4/PSR4NamespaceTest.php
+++ b/tests/Registration/PSR4/PSR4NamespaceTest.php
@@ -1,84 +1,83 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Registration\PSR4;
use Keruald\OmniTools\Registration\PSR4\PSR4Namespace;
use Keruald\OmniTools\Tests\WithData;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class PSR4NamespaceTest extends TestCase {
use WithData;
///
/// Discovery tests
///
const ALL_CLASSES = [
"Acme\\SolarSystemLib\\Sun",
"Acme\\SolarSystemLib\\Planets\\Pluton",
"Acme\\SolarSystemLib\\Planets\\Inner\\Mercure",
"Acme\\SolarSystemLib\\Planets\\Inner\\Venus",
];
- /**
- * @dataProvider provideClasses
- */
+ #[DataProvider('provideClasses')]
public function testDiscover (
string $path, string $prefix, array $expected
) : void {
$ns = new PSR4Namespace($prefix, $this->getDataPath($path));
$this->assertEquals($expected, $ns->discover());
}
public function testDiscoverRecursive () : void {
$baseDirectory = $this->getDataPath("SolarSystemLib");
$ns = new PSR4Namespace("Acme\\SolarSystemLib", $baseDirectory);
$this->assertEquals(self::ALL_CLASSES, $ns->discoverRecursive());
}
public function testDiscoverAllClasses () : void {
$actual = PSR4Namespace::discoverAllClasses(
"Acme\\SolarSystemLib",
$this->getDataPath("SolarSystemLib"),
);
$this->assertEquals(self::ALL_CLASSES, $actual);
}
///
/// Data providers
///
- public function provideClasses () : iterable {
+ public static function provideClasses () : iterable {
// [string $path, string $prefix, string[] $expectedClasses]
yield ["MockLib", "Acme\\MockLib", [
"Acme\\MockLib\\Bar",
"Acme\\MockLib\\Foo",
]];
yield ["SolarSystemLib", "Acme\\SolarSystemLib", [
"Acme\\SolarSystemLib\\Sun",
]];
yield ["SolarSystemLib/Planets", "Acme\\SolarSystemLib\\Planets", [
"Acme\\SolarSystemLib\\Planets\\Pluton",
]];
yield [
"SolarSystemLib/Planets/Inner",
"Acme\\SolarSystemLib\\Planets\\Inner",
[
"Acme\\SolarSystemLib\\Planets\\Inner\\Mercure",
"Acme\\SolarSystemLib\\Planets\\Inner\\Venus",
]
];
yield ["NotExisting", "AnyPrefix", []];
}
}
diff --git a/tests/Registration/PSR4AutoloaderTest.php b/tests/Registration/PSR4AutoloaderTest.php
index 7d21da5..c8fa5e7 100644
--- a/tests/Registration/PSR4AutoloaderTest.php
+++ b/tests/Registration/PSR4AutoloaderTest.php
@@ -1,34 +1,32 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Registration;
use Keruald\OmniTools\Registration\PSR4\Solver;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class PSR4AutoloaderTest extends TestCase {
///
/// Tests
///
-
- /**
- * @dataProvider providePaths
- */
+ #[DataProvider('providePaths')]
public function testGetPathFor (string $class, string $expected) : void {
$this->assertEquals($expected, Solver::getPathFor($class));
}
///
/// Data provider
///
- public function providePaths () : iterable {
+ public static function providePaths () : iterable {
// Example from PSR-4 canonical document
yield ['File_Writer', 'File_Writer.php'];
yield ['Response\Status', 'Response/Status.php'];
yield ['Request', 'Request.php'];
}
}
diff --git a/tests/Strings/Multibyte/OmniStringTest.php b/tests/Strings/Multibyte/OmniStringTest.php
index cf7d364..993fa89 100644
--- a/tests/Strings/Multibyte/OmniStringTest.php
+++ b/tests/Strings/Multibyte/OmniStringTest.php
@@ -1,124 +1,119 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Strings\Multibyte;
use Keruald\OmniTools\Strings\Multibyte\OmniString;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class OmniStringTest extends TestCase {
/**
* @var OmniString
*/
private $string;
protected function setUp () : void {
$this->string = new OmniString("foo");
}
public function testToString () : void {
$this->assertEquals("foo", (string)$this->string);
$this->assertEquals("foo", $this->string->__toString());
}
public function testPad () : void {
$paddedString = $this->string->pad(9, '-=-', STR_PAD_BOTH);
$this->assertEquals("-=-foo-=-", $paddedString);
}
public function testStartsWith () : void {
$this->assertTrue($this->string->startsWith("fo"));
$this->assertTrue($this->string->startsWith(""));
$this->assertTrue($this->string->startsWith("foo"));
$this->assertFalse($this->string->startsWith("Fo"));
$this->assertFalse($this->string->startsWith("bar"));
}
public function testEndsWith () : void {
$this->assertTrue($this->string->endsWith("oo"));
$this->assertTrue($this->string->endsWith(""));
$this->assertTrue($this->string->endsWith("foo"));
$this->assertFalse($this->string->endsWith("oO"));
$this->assertFalse($this->string->endsWith("bar"));
}
public function testLen () : void {
$this->assertEquals(3, $this->string->len());
}
- /**
- * @dataProvider provideCharactersArrays
- */
+ #[DataProvider('provideCharactersArrays')]
public function testGetChars (string $string, array $expectedCharacters) : void {
$actualCharacters = (new OmniString($string))->getChars();
$this->assertEquals($expectedCharacters, $actualCharacters);
}
- /**
- * @dataProvider provideCharactersBigrams
- */
+ #[DataProvider('provideCharactersBigrams')]
public function testBigrams (string $string, array $expectedBigrams) : void {
$actualBigrams = (new OmniString($string))->getBigrams();
$this->assertEquals($expectedBigrams, $actualBigrams);
}
- /**
- * @dataProvider provideExplosions
- */
+ #[DataProvider('provideExplosions')]
public function testExplode (string $delimiter, string $imploded, array $exploded) : void {
$actual = (new OmniString($imploded))
->explode($delimiter)
->toArray();
$this->assertEquals($exploded, $actual);
}
public function testExplodeWithEmptyOmniArray () : void {
$array = (new OmniString("foo"))
->explode("", -1);
$this->assertEquals(0, count($array->toArray()));
}
///
/// Data providers
///
- public function provideCharactersArrays () : iterable {
+ public static function provideCharactersArrays () : iterable {
yield ["foo", ['f', 'o', 'o']];
yield [
'àèòàFOOàèòà',
['à', 'è', 'ò', 'à', 'F', 'O', 'O', 'à', 'è', 'ò', 'à']
];
yield ["🇩🇪", ["🇩", "🇪"]];
yield ["", []];
}
- public function provideCharactersBigrams () : iterable {
+ public static function provideCharactersBigrams () : iterable {
yield ["foo", ['fo', 'oo']];
yield ["night", ['ni', 'ig', 'gh', 'ht']];
yield ["🇩🇪", ["🇩🇪"]];
yield ["", []];
}
- public function provideExplosions () : iterable {
+ public static function provideExplosions () : iterable {
yield ["/", "a/b/c", ['a', 'b', 'c']];
yield ["/", "abc", ['abc']];
yield ["/", "/b/c", ['', 'b', 'c']];
yield ["/", "a/b/", ['a', 'b', '']];
yield ["", "a/b/c", ['a/b/c']];
yield ["x", "a/b/c", ['a/b/c']];
}
}
diff --git a/tests/Strings/Multibyte/StringUtilitiesTest.php b/tests/Strings/Multibyte/StringUtilitiesTest.php
index 1bbdffe..77c8092 100644
--- a/tests/Strings/Multibyte/StringUtilitiesTest.php
+++ b/tests/Strings/Multibyte/StringUtilitiesTest.php
@@ -1,122 +1,116 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Strings\Multibyte;
use Keruald\OmniTools\Strings\Multibyte\StringUtilities;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class StringUtilitiesTest extends TestCase {
///
/// Tests
///
-
- /**
- * @dataProvider providePadding
- */
+ #[DataProvider('providePadding')]
public function testPad (
string $expected,
string $input, int $padLength, string $padString, int $padType
) : void {
$paddedString = StringUtilities::pad(
$input, $padLength, $padString, $padType, "UTF-8"
);
$this->assertEquals($expected, $paddedString);
}
public function testPadWithDefaultArguments () : void {
$this->assertEquals("foo ", StringUtilities::pad("foo", 4));
$this->assertEquals("foo_", StringUtilities::pad("foo", 4, '_'));
$this->assertEquals("_foo", StringUtilities::pad("foo", 4, '_', STR_PAD_LEFT));
}
public function testSupportedEncoding () : void {
$this->assertTrue(StringUtilities::isSupportedEncoding("UTF-8"));
$this->assertFalse(StringUtilities::isSupportedEncoding("notexisting"));
}
public function testStartsWith () : void {
$this->assertTrue(StringUtilities::startsWith("foo", "fo"));
$this->assertTrue(StringUtilities::startsWith("foo", ""));
$this->assertTrue(StringUtilities::startsWith("foo", "foo"));
$this->assertFalse(StringUtilities::startsWith("foo", "bar"));
}
public function testEndsWith () : void {
$this->assertTrue(StringUtilities::endsWith("foo", "oo"));
$this->assertTrue(StringUtilities::endsWith("foo", ""));
$this->assertTrue(StringUtilities::endsWith("foo", "foo"));
$this->assertFalse(StringUtilities::endsWith("foo", "oO"));
$this->assertFalse(StringUtilities::endsWith("foo", "bar"));
}
- /**
- * @dataProvider provideBase64
- */
+ #[DataProvider('provideBase64')]
public function testEncodeInBase64 (string $decoded, string $encoded) : void {
$actual = StringUtilities::encodeInBase64($decoded);
$this->assertEquals($encoded, $actual);
}
- /**
- * @dataProvider provideBase64
- */
+ #[DataProvider('provideBase64')]
public function testDecodeFromBase64 (string $decoded, string $encoded) : void {
$actual = StringUtilities::decodeFromBase64($encoded);
$this->assertEquals($decoded, $actual);
}
///
/// Data providers
///
- public function providePadding () : iterable {
+ public static function providePadding () : iterable {
// Tests from http://3v4l.org/UnXTF
// http://web.archive.org/web/20150711100913/http://3v4l.org/UnXTF
yield ['àèòàFOOàèòà', "FOO", 11, "àèò", STR_PAD_BOTH];
yield ['àèòFOOàèòà', "FOO", 10, "àèò", STR_PAD_BOTH];
yield ['àèòBAAZàèòà', "BAAZ", 11, "àèò", STR_PAD_BOTH];
yield ['àèòBAAZàèò', "BAAZ", 10, "àèò", STR_PAD_BOTH];
yield ['FOOBAR', "FOOBAR", 6, "àèò", STR_PAD_BOTH];
yield ['FOOBAR', "FOOBAR", 1, "àèò", STR_PAD_BOTH];
yield ['FOOBAR', "FOOBAR", 0, "àèò", STR_PAD_BOTH];
yield ['FOOBAR', "FOOBAR", -10, "àèò", STR_PAD_BOTH];
yield ['àèòàèòàèFOO', "FOO", 11, "àèò", STR_PAD_LEFT];
yield ['àèòàèòàFOO', "FOO", 10, "àèò", STR_PAD_LEFT];
yield ['àèòàèòàBAAZ', "BAAZ", 11, "àèò", STR_PAD_LEFT];
yield ['àèòàèòBAAZ', "BAAZ", 10, "àèò", STR_PAD_LEFT];
yield ['FOOBAR', "FOOBAR", 6, "àèò", STR_PAD_LEFT];
yield ['FOOBAR', "FOOBAR", 1, "àèò", STR_PAD_LEFT];
yield ['FOOBAR', "FOOBAR", 0, "àèò", STR_PAD_LEFT];
yield ['FOOBAR', "FOOBAR", -10, "àèò", STR_PAD_LEFT];
yield ['FOOàèòàèòàè', "FOO", 11, "àèò", STR_PAD_RIGHT];
yield ['FOOàèòàèòà', "FOO", 10, "àèò", STR_PAD_RIGHT];
yield ['BAAZàèòàèòà', "BAAZ", 11, "àèò", STR_PAD_RIGHT];
yield ['BAAZàèòàèò', "BAAZ", 10, "àèò", STR_PAD_RIGHT];
yield ['FOOBAR', "FOOBAR", 6, "àèò", STR_PAD_RIGHT];
yield ['FOOBAR', "FOOBAR", 1, "àèò", STR_PAD_RIGHT];
yield ['FOOBAR', "FOOBAR", 0, "àèò", STR_PAD_RIGHT];
yield ['FOOBAR', "FOOBAR", -10, "àèò", STR_PAD_RIGHT];
}
- public function provideBase64 () : iterable {
+ public static function provideBase64 () : iterable {
yield ['foo', 'Zm9v', "This is the regular base test without any exception."];
yield ['', '', "An empty string should remain an empty string."];
yield [
"J'ai fait mes 60 prières par terre dans la poudrière.",
'SidhaSBmYWl0IG1lcyA2MCBwcmnDqHJlcyBwYXIgdGVycmUgZGFucyBsYSBwb3VkcmnDqHJlLg',
"No padding should be used."
];
yield [
"àèòàFOOàèòà", "w6DDqMOyw6BGT0_DoMOow7LDoA",
"Slashes / should be replaced by underscores _."
];
}
}
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Thu, Sep 18, 18:55 (3 h, 33 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2991296
Default Alt Text
(99 KB)
Attached To
Mode
rKOT Keruald OmniTools
Attached
Detach File
Event Timeline
Log In to Comment