PhpStorageTestBase.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Drupal\Tests\Component\PhpStorage;
  3. use Drupal\Component\PhpStorage\PhpStorageInterface;
  4. use Drupal\Component\Utility\Random;
  5. use org\bovigo\vfs\vfsStream;
  6. use PHPUnit\Framework\TestCase;
  7. /**
  8. * Base test for PHP storages.
  9. */
  10. abstract class PhpStorageTestBase extends TestCase {
  11. /**
  12. * A unique per test class directory path to test php storage.
  13. *
  14. * @var string
  15. */
  16. protected $directory;
  17. /**
  18. * {@inheritdoc}
  19. */
  20. protected function setUp() {
  21. parent::setUp();
  22. vfsStream::setup('exampleDir');
  23. $this->directory = vfsStream::url('exampleDir');
  24. }
  25. /**
  26. * Assert that a PHP storage's load/save/delete operations work.
  27. */
  28. public function assertCRUD($php) {
  29. // Random generator.
  30. $random_generator = new Random();
  31. $name = $random_generator->name(8, TRUE) . '/' . $random_generator->name(8, TRUE) . '.php';
  32. // Find a global that doesn't exist.
  33. do {
  34. $random = mt_rand(10000, 100000);
  35. } while (isset($GLOBALS[$random]));
  36. // Write out a PHP file and ensure it's successfully loaded.
  37. $code = "<?php\n\$GLOBALS[$random] = TRUE;";
  38. $success = $php->save($name, $code);
  39. $this->assertTrue($success, 'Saved php file');
  40. $php->load($name);
  41. $this->assertTrue($GLOBALS[$random], 'File saved correctly with correct value');
  42. // Run additional asserts.
  43. $this->additionalAssertCRUD($php, $name);
  44. // If the file was successfully loaded, it must also exist, but ensure the
  45. // exists() method returns that correctly.
  46. $this->assertTrue($php->exists($name), 'Exists works correctly');
  47. // Delete the file, and then ensure exists() returns FALSE.
  48. $this->assertTrue($php->delete($name), 'Delete succeeded');
  49. $this->assertFalse($php->exists($name), 'Delete deleted file');
  50. // Ensure delete() can be called on a non-existing file. It should return
  51. // FALSE, but not trigger errors.
  52. $this->assertFalse($php->delete($name), 'Delete fails on missing file');
  53. unset($GLOBALS[$random]);
  54. }
  55. /**
  56. * Additional asserts to be run.
  57. *
  58. * @param \Drupal\Component\PhpStorage\PhpStorageInterface $php
  59. * The PHP storage object.
  60. * @param string $name
  61. * The name of an object. It should exist in the storage.
  62. */
  63. protected function additionalAssertCRUD(PhpStorageInterface $php, $name) {
  64. // By default do not do any additional asserts. This is a way of extending
  65. // tests in contrib.
  66. }
  67. }