The Trait
<?php
declare(strict_types=1);
namespace App\Lib\Help\Traits;
trait HelpServiceShellExecTrait
{
protected function shellExec(string $cmd)
{
// redirect stderr so we can see the output
// if the command fails
return trim((string) shell_exec(sprintf('%s 2>&1', $cmd)));
}
}
The Test
<?php
namespace App\Test\TestCase\Lib\Help;
use App\Lib\Help\Traits\HelpServiceShellExecTrait;
use Cake\TestSuite\TestCase;
use ReflectionObject;
class HelpServiceTest extends TestCase
{
public function testShellExecOnHelpServiceServer()
{
$class = new class {
use HelpServiceShellExecTrait;
};
$reflected = new ReflectionObject($class);
$myMethod = $reflected->getMethod('shellExec');
$myMethod->setAccessible(true);
$result = $myMethod->invokeArgs($class, ["echo \"hi\"\n\n"]);
$this->assertEquals("hi", $result);
}
}
0 Comments