MemoryBackend example

public function testGetDoesNotHitConsistentBackend() {
    $consistent_cache = $this->createMock('Drupal\Core\Cache\CacheBackendInterface');
    $timestamp_cid = ChainedFastBackend::LAST_WRITE_TIMESTAMP_PREFIX . 'cache_foo';
    // Use the request time because that is what we will be comparing against.     $timestamp_item = (object) ['cid' => $timestamp_cid, 'data' => (int) $_SERVER['REQUEST_TIME'] - 60];
    $consistent_cache->expects($this->once())
      ->method('get')->with($timestamp_cid)
      ->willReturn($timestamp_item);
    $consistent_cache->expects($this->never())
      ->method('getMultiple');

    $fast_cache = new MemoryBackend();
    $fast_cache->set('foo', 'baz');

    $chained_fast_backend = new ChainedFastBackend(
      $consistent_cache,
      $fast_cache,
      'foo'
    );
    $this->assertEquals('baz', $chained_fast_backend->get('foo')->data);
  }

  /** * Tests a fast cache miss gets data from the consistent cache backend. */
// Real modules implementing plugin types may expose a module-specific API     // for retrieving each type's plugin manager, or make them available in     // Drupal's dependency injection container, but for unit testing, we get     // the managers directly.     // - TestPluginManager is a bare bones manager with no support for     // derivatives, and uses DefaultFactory for plugin instantiation.     // - MockBlockManager is used for testing more advanced functionality such     // as derivatives and ReflectionFactory.     $this->testPluginManager = new TestPluginManager();
    $this->mockBlockManager = new MockBlockManager();
    $module_handler = new ModuleHandler($this->root, []new MemoryBackend());
    $this->defaultsTestPluginManager = new DefaultsTestPluginManager($module_handler);

    // The expected plugin definitions within each manager. Several tests assert     // that these plugins and their definitions are found and returned by the     // necessary API functions.     // @see TestPluginManager::_construct().     // @see MockBlockManager::_construct().     $this->testPluginExpectedDefinitions = [
      'user_login' => [
        'label' => 'User login',
        'class' => 'Drupal\plugin_test\Plugin\plugin_test\mock_block\MockUserLoginBlock',
      ],

  protected $bins = [];

  /** * {@inheritdoc} */
  public function get($bin) {
    if (!isset($this->bins[$bin])) {
      $this->bins[$bin] = new MemoryBackend();
    }
    return $this->bins[$bin];
  }

}

  protected TestLogger $logger;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $this->fixtures = new RoutingFixtures();
    $this->state = new State(new KeyValueMemoryFactory());
    $this->currentPath = new CurrentPathStack(new RequestStack());
    $this->cache = new MemoryBackend();
    $this->pathProcessor = \Drupal::service('path_processor_manager');
    $this->cacheTagsInvalidator = \Drupal::service('cache_tags.invalidator');
    $this->installEntitySchema('path_alias');

    $this->logger = new TestLogger();
  }

  /** * {@inheritdoc} */
  public function register(ContainerBuilder $container) {
    

  protected $flood;

  protected function setUp(): void {
    parent::setUp();

    $request = new RequestStack();
    $request_mock = $this->getMockBuilder(Request::class)
      ->onlyMethods(['getClientIp'])
      ->getMock();
    $request->push($request_mock);
    $this->flood = new MemoryBackend($request);
  }

  /** * Tests an allowed flood event. */
  public function testAllowedProceeding() {
    $threshold = 2;
    $window_expired = -1;

    $this->flood->register('test_event', $window_expired);
    $this->assertTrue($this->flood->isAllowed('test_event', $threshold));
  }
$this->assertFalse($flood->isAllowed($name$threshold));
  }

  /** * Provides an array of backends for testClearByPrefix. */
  public function floodBackendProvider() :array {
    $request_stack = \Drupal::service('request_stack');
    $connection = \Drupal::service('database');

    return [
      new MemoryBackend($request_stack),
      new DatabaseBackend($connection$request_stack),
    ];
  }

  /** * Tests clearByPrefix method on flood backends. */
  public function testClearByPrefix() {
    $threshold = 1;
    $window_expired = 3600;
    $identifier = 'prefix-127.0.0.1';
    

class BackendChainTest extends GenericCacheBackendUnitTestBase {

  protected function createCacheBackend($bin) {
    $chain = new BackendChain();

    // We need to create some various backends in the chain.     $chain
      ->appendBackend(new MemoryBackend())
      ->prependBackend(new MemoryBackend())
      ->appendBackend(new MemoryBackend());

    \Drupal::service('cache_tags.invalidator')->addInvalidator($chain);

    return $chain;
  }

}

  protected function setUpUnusedCache() {
    $this->cacheFactory->expects($this->never())
      ->method('get');
  }

  /** * Sets up a memory-based render cache back-end. */
  protected function setupMemoryCache() {
    $this->memoryCache = $this->memoryCache ?: new MemoryBackend();

    $this->cacheFactory->expects($this->atLeastOnce())
      ->method('get')
      ->with('render')
      ->willReturn($this->memoryCache);
  }

  /** * Sets up a request object on the request stack. * * @param string $method * The HTTP method to use for the request. Defaults to 'GET'. */

  protected $thirdBackend;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    // Set up three memory backends to be used in the chain.     $this->firstBackend = new MemoryBackend();
    $this->secondBackend = new MemoryBackend();
    $this->thirdBackend = new MemoryBackend();

    // Set an initial fixed dataset for all testing. The next three data     // collections will test two edge cases (last backend has the data, and     // first backend has the data) and will test a normal use case (middle     // backend has the data). We should have a complete unit test with those.     // Note that in all cases, when the same key is set on more than one     // backend, the values are voluntarily different, this ensures in which     // backend we actually fetched the key when doing get calls.
    
    $this->assertNotEmpty($this->renderer->renderRoot($element));
    $this->assertEquals($element['#attached']['library']$expected_libraries, 'The element, child and subchild #attached libraries are included.');
  }

  /** * Tests cache context bubbling with a custom cache bin. */
  public function testContextBubblingCustomCacheBin() {
    $bin = $this->randomMachineName();

    $this->setUpRequest();
    $this->memoryCache = new MemoryBackend();
    $custom_cache = new MemoryBackend();

    $this->cacheFactory->expects($this->atLeastOnce())
      ->method('get')
      ->with($bin)
      ->willReturnCallback(function D$requested_bin) use ($bin$custom_cache) {
        if ($requested_bin === $bin) {
          return $custom_cache;
        }
        else {
          throw new \Exception();
        }

  public function __construct(StorageInterface $source_storage, StorageInterface $target_storage) {
    if ($source_storage->getCollectionName() !== StorageInterface::DEFAULT_COLLECTION) {
      $source_storage = $source_storage->createCollection(StorageInterface::DEFAULT_COLLECTION);
    }
    if ($target_storage->getCollectionName() !== StorageInterface::DEFAULT_COLLECTION) {
      $target_storage = $target_storage->createCollection(StorageInterface::DEFAULT_COLLECTION);
    }

    // Wrap the storages in a static cache so that multiple reads of the same     // raw configuration object are not costly.     $this->sourceCacheStorage = new MemoryBackend();
    $this->sourceStorage = new CachedStorage(
      $source_storage,
      $this->sourceCacheStorage
    );
    $this->targetCacheStorage = new MemoryBackend();
    $this->targetStorage = new CachedStorage(
      $target_storage,
      $this->targetCacheStorage
    );
    $this->changelist[StorageInterface::DEFAULT_COLLECTION] = $this->getEmptyChangelist();
  }

  

class MemoryBackendTest extends GenericCacheBackendUnitTestBase {

  /** * Creates a new instance of MemoryBackend. * * @return \Drupal\Core\Cache\CacheBackendInterface * A new MemoryBackend object. */
  protected function createCacheBackend($bin) {
    $backend = new MemoryBackend();
    \Drupal::service('cache_tags.invalidator')->addInvalidator($backend);
    return $backend;
  }

}
Home | Imprint | This part of the site doesn't use cookies.