FileCacheLockTest.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Illuminate\Tests\Integration\Cache;
  3. use Exception;
  4. use Illuminate\Support\Carbon;
  5. use Illuminate\Support\Facades\Cache;
  6. use Orchestra\Testbench\TestCase;
  7. class FileCacheLockTest extends TestCase
  8. {
  9. /**
  10. * Define environment setup.
  11. *
  12. * @param \Illuminate\Foundation\Application $app
  13. * @return void
  14. */
  15. protected function getEnvironmentSetUp($app)
  16. {
  17. $app['config']->set('cache.default', 'file');
  18. }
  19. public function testLocksCanBeAcquiredAndReleased()
  20. {
  21. Cache::lock('foo')->forceRelease();
  22. $lock = Cache::lock('foo', 10);
  23. $this->assertTrue($lock->get());
  24. $this->assertFalse(Cache::lock('foo', 10)->get());
  25. $lock->release();
  26. $lock = Cache::lock('foo', 10);
  27. $this->assertTrue($lock->get());
  28. $this->assertFalse(Cache::lock('foo', 10)->get());
  29. Cache::lock('foo')->release();
  30. }
  31. public function testLocksCanBlockForSeconds()
  32. {
  33. Carbon::setTestNow();
  34. Cache::lock('foo')->forceRelease();
  35. $this->assertSame('taylor', Cache::lock('foo', 10)->block(1, function () {
  36. return 'taylor';
  37. }));
  38. Cache::lock('foo')->forceRelease();
  39. $this->assertTrue(Cache::lock('foo', 10)->block(1));
  40. }
  41. public function testConcurrentLocksAreReleasedSafely()
  42. {
  43. Cache::lock('foo')->forceRelease();
  44. $firstLock = Cache::lock('foo', 1);
  45. $this->assertTrue($firstLock->get());
  46. sleep(2);
  47. $secondLock = Cache::lock('foo', 10);
  48. $this->assertTrue($secondLock->get());
  49. $firstLock->release();
  50. $this->assertFalse(Cache::lock('foo')->get());
  51. }
  52. public function testLocksWithFailedBlockCallbackAreReleased()
  53. {
  54. Cache::lock('foo')->forceRelease();
  55. $firstLock = Cache::lock('foo', 10);
  56. try {
  57. $firstLock->block(1, function () {
  58. throw new Exception('failed');
  59. });
  60. } catch (Exception $e) {
  61. // Not testing the exception, just testing the lock
  62. // is released regardless of the how the exception
  63. // thrown by the callback was handled.
  64. }
  65. $secondLock = Cache::lock('foo', 1);
  66. $this->assertTrue($secondLock->get());
  67. }
  68. public function testLocksCanBeReleasedUsingOwnerToken()
  69. {
  70. Cache::lock('foo')->forceRelease();
  71. $firstLock = Cache::lock('foo', 10);
  72. $this->assertTrue($firstLock->get());
  73. $owner = $firstLock->owner();
  74. $secondLock = Cache::store('file')->restoreLock('foo', $owner);
  75. $secondLock->release();
  76. $this->assertTrue(Cache::lock('foo')->get());
  77. }
  78. }