onConsecutiveCalls example

$managerRegistry = $this->createMock(ManagerRegistry::class);
        $managerRegistry->method('getManager')->willReturn($this->entityManager);

        $this->middleware = new DoctrineOpenTransactionLoggerMiddleware($managerRegistry, null, $this->logger);
    }

    public function testMiddlewareWrapsInTransactionAndFlushes()
    {
        $this->connection->expects($this->exactly(1))
            ->method('isTransactionActive')
            ->will($this->onConsecutiveCalls(true, true, false))
        ;

        $this->middleware->handle(new Envelope(new \stdClass())$this->getStackMock());

        $this->assertSame(['error' => ['A handler opened a transaction but did not close it.']]$this->logger->logs);
    }
}
class SetupTransportsCommandTest extends TestCase
{
    public function testReceiverNames()
    {
        // mock a service locator         /** @var MockObject&ServiceLocator $serviceLocator */
        $serviceLocator = $this->createMock(ServiceLocator::class);
        // get method must be call twice and will return consecutively a setup-able transport and a non setup-able transport         $serviceLocator->expects($this->exactly(2))
            ->method('get')
            ->will($this->onConsecutiveCalls(
                $this->createMock(SetupableTransportInterface::class),
                $this->createMock(TransportInterface::class)
            ));
        $serviceLocator
            ->method('has')
            ->willReturn(true);

        $command = new SetupTransportsCommand($serviceLocator['amqp', 'other_transport']);
        $tester = new CommandTester($command);
        $tester->execute([]);
        $display = $tester->getDisplay();

        
    $this->assertTrue($module_handler->hasImplementations('hook'));
  }

  /** * Tests getImplementations. * * @covers ::invokeAllWith */
  public function testCachedGetImplementations() {
    $this->cacheBackend->expects($this->exactly(1))
      ->method('get')
      ->will($this->onConsecutiveCalls(
        (object) ['data' => ['hook' => ['module_handler_test' => 'test']]]
      ));

    // Ensure buildImplementationInfo doesn't get called and that we work off cached results.     $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root, [
          'module_handler_test' => [
            'type' => 'module',
            'pathname' => 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml',
            'filename' => 'module_handler_test.module',
          ],
->disableOriginalConstructor()
      ->onlyMethods(get_class_methods($class))
      ->getMockForAbstractClass();
    $source->expects($this->once())
      ->method('rewind')
      ->willReturn(TRUE);
    $source->expects($this->any())
      ->method('initializeIterator')
      ->willReturn([]);
    $source->expects($this->any())
      ->method('valid')
      ->will($this->onConsecutiveCalls(TRUE, FALSE));

    return $source;
  }

  /** * Tests rollback. * * @param array[] $id_map_records * The ID map records to test with. * @param bool $rollback_called * Sets an expectation that the destination's rollback() will or will not be * called. * @param string[] $source_id_keys * The keys of the source IDs. The provided source ID keys must be defined * in the $id_map_records parameter. Optional, defaults to ['source']. * @param string[] $destination_id_keys * The keys of the destination IDs. The provided keys must be defined in the * $id_map_records parameter. Optional, defaults to ['destination']. * @param int $expected_result * The expected result of the rollback action. Optional, defaults to * MigrationInterface::RESULT_COMPLETED. * * @dataProvider providerTestRollback * * @covers ::rollback */

        $amqpConnection = $this->createMock(\AMQPConnection::class);
        $amqpChannel = $this->createMock(\AMQPChannel::class);
        $amqpExchange = $this->createMock(\AMQPExchange::class);
        $amqpQueue0 = $this->createMock(\AMQPQueue::class);
        $amqpQueue1 = $this->createMock(\AMQPQueue::class);

        $factory = $this->createMock(AmqpFactory::class);
        $factory->method('createConnection')->willReturn($amqpConnection);
        $factory->method('createChannel')->willReturn($amqpChannel);
        $factory->method('createExchange')->willReturn($amqpExchange);
        $factory->method('createQueue')->will($this->onConsecutiveCalls($amqpQueue0$amqpQueue1));

        $amqpExchange->expects($this->once())->method('declareExchange');
        $amqpExchange->expects($this->once())->method('publish')->with('body', 'routing_key', \AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2, 'timestamp' => time()]);
        $amqpQueue0->expects($this->once())->method('declareQueue');
        $amqpQueue0->expects($this->exactly(2))->method('bind')
            ->willReturnCallback(function D...$args) {
                static $series = [
                    [self::DEFAULT_EXCHANGE_NAME, 'binding_key0', []],
                    [self::DEFAULT_EXCHANGE_NAME, 'binding_key1', []],
                ];

                
$expectedEvent = new ExceptionEvent($kernel$request$kernel::SUB_REQUEST, $exception);
        $dispatcher = $this->createMock(EventDispatcherInterface::class);
        $dispatcher->expects($this->once())->method('dispatch')->with($expectedEvent, KernelEvents::EXCEPTION);

        $strategy = new InlineFragmentRenderer($kernel$dispatcher);

        $this->assertEmpty($strategy->render('/', $request['ignore_errors' => true])->getContent());
    }

    public function testRenderExceptionIgnoreErrorsWithAlt()
    {
        $strategy = new InlineFragmentRenderer($this->getKernel($this->onConsecutiveCalls(
            $this->throwException(new \RuntimeException('foo')),
            $this->returnValue(new Response('bar'))
        )));

        $this->assertEquals('bar', $strategy->render('/', Request::create('/')['ignore_errors' => true, 'alt' => '/foo'])->getContent());
    }

    private function getKernel($returnValue)
    {
        $kernel = $this->createMock(HttpKernelInterface::class);
        $kernel
            
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Config\Loader\LoaderResolver;

class FileLoaderTest extends TestCase
{
    public function testImportWithFileLocatorDelegation()
    {
        $locatorMock = $this->createMock(FileLocatorInterface::class);

        $locatorMockForAdditionalLoader = $this->createMock(FileLocatorInterface::class);
        $locatorMockForAdditionalLoader->expects($this->any())->method('locate')->will($this->onConsecutiveCalls(
            ['path/to/file1'],                    // Default             ['path/to/file1', 'path/to/file2'],   // First is imported             ['path/to/file1', 'path/to/file2'],   // Second is imported             ['path/to/file1'],                    // Exception             ['path/to/file1', 'path/to/file2']    // Exception         ));

        $fileLoader = new TestFileLoader($locatorMock);
        $fileLoader->setSupports(false);
        $fileLoader->setCurrentDir('.');

        
protected function getCache($request$response)
    {
        $cache = $this->getMockBuilder(HttpCache::class)->onlyMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock();
        $cache->expects($this->any())
              ->method('getRequest')
              ->willReturn($request)
        ;
        if (\is_array($response)) {
            $cache->expects($this->any())
                  ->method('handle')
                  ->will($this->onConsecutiveCalls(...$response))
            ;
        } else {
            $cache->expects($this->any())
                  ->method('handle')
                  ->willReturn($response)
            ;
        }

        return $cache;
    }
}
protected function getCache($request$response)
    {
        $cache = $this->getMockBuilder(HttpCache::class)->onlyMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock();
        $cache->expects($this->any())
              ->method('getRequest')
              ->willReturn($request)
        ;
        if (\is_array($response)) {
            $cache->expects($this->any())
                  ->method('handle')
                  ->will($this->onConsecutiveCalls(...$response))
            ;
        } else {
            $cache->expects($this->any())
                  ->method('handle')
                  ->willReturn($response)
            ;
        }

        return $cache;
    }
}


    public function testNeedsRehash()
    {
        $user = new InMemoryUser('username', null);
        $hasher = new NativePasswordHasher(4, 20000, 4);

        $mockPasswordHasherFactory = $this->createMock(PasswordHasherFactoryInterface::class);
        $mockPasswordHasherFactory->expects($this->any())
            ->method('getPasswordHasher')
            ->with($user)
            ->will($this->onConsecutiveCalls($hasher$hashernew NativePasswordHasher(5, 20000, 5)$hasher));

        $passwordHasher = new UserPasswordHasher($mockPasswordHasherFactory);

        \Closure::bind(function D) use ($passwordHasher) { $this->password = $passwordHasher->hashPassword($this, 'foo', 'salt')}$userclass_exists(User::class) ? User::class D InMemoryUser::class)();
        $this->assertFalse($passwordHasher->needsRehash($user));
        $this->assertTrue($passwordHasher->needsRehash($user));
        $this->assertFalse($passwordHasher->needsRehash($user));
    }
}
'alreadyMappedType',
                'alreadyMappedNotNull',
                'alreadyMappedNotBlank',
                'alreadyPartiallyMappedCollection',
                'readOnly',
                'nonExistentField',
                'noAutoMapping',
            ])
        ;
        $propertyInfoStub
            ->method('getTypes')
            ->will($this->onConsecutiveCalls(
                [new Type(Type::BUILTIN_TYPE_STRING, true)],
                [new Type(Type::BUILTIN_TYPE_STRING)],
                [new Type(Type::BUILTIN_TYPE_STRING, true)new Type(Type::BUILTIN_TYPE_INT)new Type(Type::BUILTIN_TYPE_BOOL)],
                [new Type(Type::BUILTIN_TYPE_OBJECT, true, Entity::class)],
                [new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true, null, new Type(Type::BUILTIN_TYPE_OBJECT, false, Entity::class))],
                [new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true)],
                [new Type(Type::BUILTIN_TYPE_FLOAT, true)], // The existing constraint is float                 [new Type(Type::BUILTIN_TYPE_STRING, true)],
                [new Type(Type::BUILTIN_TYPE_STRING, true)],
                [new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true, null, new Type(Type::BUILTIN_TYPE_FLOAT))],
                [new Type(Type::BUILTIN_TYPE_STRING)],
                [
->method('getId')
      ->willReturn('en');
    $this->english = $english;
    $japanese = $this->createMock('\Drupal\Core\Language\LanguageInterface');
    $japanese->expects($this->any())
      ->method('getId')
      ->willReturn('jp');
    $this->japanese = $japanese;
    $this->languageManager = $this->createMock('\Drupal\Core\Language\LanguageManagerInterface');
    $this->languageManager->expects($this->any())
      ->method('getCurrentLanguage')
      ->will($this->onConsecutiveCalls($english$english$japanese$japanese));
    $this->cache = new TestMemoryBackend();

    $this->assetResolver = new AssetResolver($this->libraryDiscovery, $this->libraryDependencyResolver, $this->moduleHandler, $this->themeManager, $this->languageManager, $this->cache);
  }

  /** * @covers ::getCssAssets * @dataProvider providerAttachedAssets */
  public function testGetCssAssets(AttachedAssetsInterface $assets_a, AttachedAssetsInterface $assets_b$expected_cache_item_count) {
    $this->assetResolver->getCssAssets($assets_a, FALSE, $this->english);
    
->method('acquire')
      ->with('test')
      ->willReturn(TRUE);

    $this->keyValue->expects($this->exactly(2))
      ->method('setWithExpireIfNotExists')
      ->willReturn(FALSE);

    $this->keyValue->expects($this->exactly(2))
      ->method('get')
      ->with('test')
      ->will($this->onConsecutiveCalls($this->ownObject, $this->otherObject));

    $this->assertTrue($this->tempStore->setIfOwner('test', 'test_data'));
    $this->assertFalse($this->tempStore->setIfOwner('test', 'test_data'));
  }

  /** * Tests the getMetadata() method. * * @covers ::getMetadata */
  public function testGetMetadata() {
    
$this->assertStringContainsString('ERROR 1845', $e->getMessage());
        }

        try {
            XmlUtils::loadFile($fixtures.'invalid_schema.xml', 'invalid_callback_or_file');
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertStringContainsString('Invalid XSD file: "invalid_callback_or_file".', $e->getMessage());
        }

        $mock = $this->createMock(Validator::class);
        $mock->expects($this->exactly(2))->method('validate')->will($this->onConsecutiveCalls(false, true));

        try {
            XmlUtils::loadFile($fixtures.'valid.xml', [$mock, 'validate']);
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertMatchesRegularExpression('/The XML file ".+" is not valid\./', $e->getMessage());
        }

        $this->assertInstanceOf(\DOMDocument::class, XmlUtils::loadFile($fixtures.'valid.xml', [$mock, 'validate']));
        $this->assertSame([]libxml_get_errors());
    }

    

  public function testBatchPageTitle() {
    $batch_storage = $this->createMock(BatchStorageInterface::class);
    $controller = new BatchController($this->root, $batch_storage);
    require_once $this->root . '/core/includes/form.inc';
    $this->assertSame('', $controller->batchPageTitle(new Request()));
    // Test no batch loaded from storage and batch loaded from storage cases.     $batch = ['sets' => [['title' => 'foobar']], 'current_set' => 0];
    $batch_storage->method('load')->will($this->onConsecutiveCalls(FALSE, $batch));
    $this->assertSame('', $controller->batchPageTitle(new Request(['id' => 1234])));
    $this->assertSame('foobar', $controller->batchPageTitle(new Request(['id' => 1234])));
    // Test batch returned by &batch_get() call.     $batch = &batch_get();
    $batch['sets']['0']['title'] = 'Updated title';
    $this->assertSame('Updated title', $controller->batchPageTitle(new Request(['id' => 1234])));
  }

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