-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortPropertyTest.php
More file actions
82 lines (68 loc) · 2.45 KB
/
Copy pathSortPropertyTest.php
File metadata and controls
82 lines (68 loc) · 2.45 KB
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
<?php
declare(strict_types=1);
namespace Examples;
use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;
use Rasuvaeff\PropertyTesting\Assume;
use Rasuvaeff\PropertyTesting\Classify;
use Rasuvaeff\PropertyTesting\Gen;
use Rasuvaeff\PropertyTesting\PhpUnit\PropertyTesting;
/**
* Canonical usage of the PHPUnit adapter: mix the PropertyTesting trait into a
* TestCase and describe properties with the fluent forAll()->check() API.
*
* Run it from the package root:
*
* vendor/bin/phpunit examples/SortPropertyTest.php
*/
#[CoversNothing]
final class SortPropertyTest extends TestCase
{
use PropertyTesting;
public function testSortIsIdempotent(): void
{
$this->forAll(['values' => Gen::arrayOf(Gen::int())])
->runs(300)
->check(static function (array $values): void {
$once = self::sorted($values);
self::assertSame($once, self::sorted($once));
});
}
public function testSortKeepsEveryElement(): void
{
$this->forAll(['values' => Gen::arrayOf(Gen::intBetween(-100, 100), maxSize: 30)])
->runs(200)
->check(static function (array $values): void {
Classify::when(count($values) > 10, 'long');
$sorted = self::sorted($values);
self::assertCount(count($values), $sorted);
foreach ($values as $value) {
self::assertContains($value, $sorted);
}
});
}
public function testMedianStaysBetweenMinAndMax(): void
{
$this->forAll(['values' => Gen::nonEmptyArrayOf(Gen::intBetween(-1_000, 1_000))])
->runs(200)
->check(static function (array $values): void {
// A one-element list makes min === median === max; still valid,
// but Assume shows how a discard works: it is a retried run,
// never a skipped test.
Assume::that(count($values) > 1);
$sorted = self::sorted($values);
$median = $sorted[intdiv(count($sorted), 2)];
self::assertGreaterThanOrEqual($sorted[0], $median);
self::assertLessThanOrEqual($sorted[count($sorted) - 1], $median);
});
}
/**
* @param list<int> $values
* @return list<int>
*/
private static function sorted(array $values): array
{
sort($values);
return $values;
}
}