function InputTest::testFallbackValueForUndefinedEnvironmentVariable

Tests getting a fallback value for an undefined environment variable.

@covers \Drupal\Core\Recipe\InputConfigurator::getDefaultValue

File

core/tests/Drupal/KernelTests/Core/Recipe/InputTest.php, line 390

Class

InputTest
@group Recipe @covers \Drupal\Core\Recipe\InputConfigurator[[api-linebreak]]

Namespace

Drupal\KernelTests\Core\Recipe

Code

public function testFallbackValueForUndefinedEnvironmentVariable() : void {
  $recipe_data = [
    'name' => 'Default value from undefined environment variable',
    'input' => [
      'capital' => [
        'data_type' => 'string',
        'description' => 'This will use the fallback value.',
        'default' => [
          'source' => 'env',
          'env' => 'NO_SUCH_THING',
          'fallback' => 'fallback',
        ],
      ],
    ],
  ];
  // Mock an input collector that will return the default value.
  $collector = $this->createMock(InputCollectorInterface::class);
  $collector->expects($this->atLeastOnce())
    ->method('collectValue')
    ->withAnyParameters()
    ->willReturnArgument(2);
  $recipe = $this->createRecipe($recipe_data);
  $recipe->input
    ->collectAll($collector);
  $this->assertSame([
    'capital' => 'fallback',
  ], $recipe->input
    ->getValues());
  // NULL is an allowable fallback value.
  $recipe_data['input']['capital']['default']['fallback'] = NULL;
  $recipe = $this->createRecipe($recipe_data);
  $recipe->input
    ->collectAll($collector);
  $this->assertSame([
    'capital' => NULL,
  ], $recipe->input
    ->getValues());
  // If there's no fallback value at all, we should get an exception.
  unset($recipe_data['input']['capital']['default']['fallback']);
  $recipe = $this->createRecipe($recipe_data);
  $this->expectException(\RuntimeException::class);
  $this->expectExceptionMessage("The 'NO_SUCH_THING' environment variable is not defined.");
  $recipe->input
    ->collectAll($collector);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.