我正在使用Symfony Lock package检查类方法是否可以执行
if ($this->lock->acquire()) {
$this->execute();
$this->lock->release();
}
重要:我不是在使用Symfony框架,而是在使用Lock组件
我想做一个测试,断言在多个线程中运行时执行被锁定,但是我没有找到有关如何实现此目标的任何文档。
使用pthreads是个好主意吗?如果没有,那是进行此测试的最佳方法?
非常感谢您。
答案 0 :(得分:0)
请参阅“锁定组件”文档: https://symfony.com/doc/current/components/lock.html#usage
CommandTester上的信息: https://symfony.com/doc/current/console.html#testing-commands
PHPUnit测试解决方案:
use Symfony\Component\Lock\Factory;
use Symfony\Component\Lock\Store\SemaphoreStore;
public function testLockIsSet()
{
// Create a new Semaphore lock with the same ID as the one that would be
// created if you were running the command / class / process etc.
$store = new SemaphoreStore();
$factory = new Factory($store);
$lock = $factory->createLock('lock-name-used-eg-generate-pdf');
if ($lock->acquire()) {
// In my use case I was running multiple commands to see if the lock
// was working properly
$commandTester = new CommandTester($this->command);
// Try and run the command. The lock should already be set.
$commandTester->execute(
[
'command' => $this->command->getName()
]
);
// You could also use expectException() here for LogicException
$this->assertContains(
'The command is already running in locked mode.',
$commandTester->getDisplay()
);
$lock->release();
}
}