Skip to content

Instantly share code, notes, and snippets.

@alphaolomi
Created November 3, 2022 21:36
Show Gist options
  • Save alphaolomi/e5f8ed90628b921ed4e647caaa0cf7fa to your computer and use it in GitHub Desktop.
Save alphaolomi/e5f8ed90628b921ed4e647caaa0cf7fa to your computer and use it in GitHub Desktop.
Make PestPHP Tests for all files in src/
<?php
//
// Generate tests according to files in src/
// usefull on writin tests for packages
//
// Author: Alpha Olomi
// Date: 4 Nov 2022
//
<?php
function get_files($source_dir = 'src')
{
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source_dir),
RecursiveIteratorIterator::SELF_FIRST
);
return $files;
}
function test_stub($path, $test = "test", $isFull = false)
{
$full = <<<EOT
<?php
$test('$path', function () {
expect(true)->toBeTrue();
});
EOT;
$incomplete = <<<EOT
<?php
$test('$path');
EOT;
return $isFull ? $full : $incomplete;
}
function make_tests($files, $dry = true)
{
foreach ($files as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$path = $file->getPathname();
$testPath = str_replace('src', 'tests', $path);
$testPath = str_replace('.php', 'Test.php', $testPath);
$testContent = test_stub($testPath);
if (false == $dry) {
$dir = dirname($testPath);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($testPath, $testContent);
} else {
echo $testPath . PHP_EOL;
}
}
}
}
echo "====================" . PHP_EOL;
echo "Make Tests" . PHP_EOL;
echo "";
$handle = fopen("php://stdin", "r");
echo "Dry run? (Y/n): ";
$line = fgets($handle);
$isDry = false;
$isDry = trim($line) === 'Y';
fclose($handle);
make_tests(get_files(), $isDry);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment