diff --git a/core/lib/Drupal/Core/DrupalKernel.php b/core/lib/Drupal/Core/DrupalKernel.php
index fdb3d86..b9b5974 100644
--- a/core/lib/Drupal/Core/DrupalKernel.php
+++ b/core/lib/Drupal/Core/DrupalKernel.php
@@ -320,10 +320,13 @@ public function __construct($environment, $class_loader, $allow_dumping = TRUE)
    * @param \Symfony\Component\HttpFoundation\Request $request
    *   The current request.
    * @param bool $require_settings
-   *   Only directories with an existing settings.php file will be recognized.
-   *   Defaults to TRUE. During initial installation, this is set to FALSE so
-   *   that Drupal can detect a matching directory, then create a new
+   *   (optional) Only directories with an existing settings.php file will be
+   *   recognized. Defaults to TRUE. During initial installation, this is set to
+   *   FALSE so that Drupal can detect a matching directory, then create a new
    *   settings.php file in it.
+   * @param string|null $drupal_root
+   *   (optional) Path to the Drupal root. Defaults to NULL. NULL means use the
+   *   DRUPAL_ROOT constant, provided for backwards-compatibility.
    *
    * @return string
    *   The path of the matching directory.
@@ -336,7 +339,7 @@ public function __construct($environment, $class_loader, $allow_dumping = TRUE)
    * @see default.settings.php
    * @see example.sites.php
    */
-  public static function findSitePath(Request $request, $require_settings = TRUE) {
+  public static function findSitePath(Request $request, $require_settings = TRUE, $drupal_root = NULL) {
     if (static::validateHostname($request) === FALSE) {
       throw new BadRequestHttpException();
     }
@@ -346,12 +349,16 @@ public static function findSitePath(Request $request, $require_settings = TRUE)
       return 'sites/simpletest/' . substr($test_prefix, 10);
     }
 
+    if ($drupal_root === NULL) {
+      $drupal_root = DRUPAL_ROOT;
+    }
+
     // Determine whether multi-site functionality is enabled.
-    if (!file_exists(DRUPAL_ROOT . '/sites/sites.php')) {
+    if (!file_exists($drupal_root . '/sites/sites.php')) {
       return 'sites/default';
     }
 
-    // Otherwise, use find the site path using the request.
+    // Otherwise, find the site path using the request.
     $script_name = $request->server->get('SCRIPT_NAME');
     if (!$script_name) {
       $script_name = $request->server->get('SCRIPT_FILENAME');
@@ -359,17 +366,17 @@ public static function findSitePath(Request $request, $require_settings = TRUE)
     $http_host = $request->getHttpHost();
 
     $sites = array();
-    include DRUPAL_ROOT . '/sites/sites.php';
+    include $drupal_root . '/sites/sites.php';
 
     $uri = explode('/', $script_name);
     $server = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
     for ($i = count($uri) - 1; $i > 0; $i--) {
       for ($j = count($server); $j > 0; $j--) {
         $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
-        if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/sites/' . $sites[$dir])) {
+        if (isset($sites[$dir]) && file_exists($drupal_root . '/sites/' . $sites[$dir])) {
           $dir = $sites[$dir];
         }
-        if (file_exists(DRUPAL_ROOT . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/sites/' . $dir))) {
+        if (file_exists($drupal_root . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists($drupal_root . '/sites/' . $dir))) {
           return "sites/$dir";
         }
       }
diff --git a/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php b/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php
index c088eed..0fcd077 100644
--- a/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php
+++ b/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php
@@ -63,6 +63,13 @@ class ExtensionDiscovery {
   protected $infoParser;
 
   /**
+   * Static root path, useful for invalidating static::$files when needed.
+   *
+   * @var string
+   */
+  protected static $cacheRoot;
+
+  /**
    * Previously discovered files keyed by origin directory and extension type.
    *
    * @var array
@@ -77,7 +84,7 @@ class ExtensionDiscovery {
   protected $profileDirectories;
 
   /**
-   * The app root.
+   * The app root for the current operation.
    *
    * @var string
    */
@@ -103,17 +110,27 @@ class ExtensionDiscovery {
    * @param string $root
    *   The app root.
    * @param bool $use_file_cache
-   *   Whether file cache should be used.
-   * @param string[] $profile_directories
-   *   The available profile directories
-   * @param string $site_path
-   *   The path to the site.
+   *   (optional) Whether file cache should be used. Defaults to TRUE.
+   * @param string[]|null $profile_directories
+   *   (optional) The available profile directories. Defaults to NULL, which
+   *   will cause this object to search for profile directories based on
+   *   settings.
+   * @param string|null $site_path
+   *   (optional) The site path within the Drupal installation. Defaults to
+   *   NULL, which will cause this object to determine the site based on the
+   *   request information.
    */
   public function __construct($root, $use_file_cache = TRUE, $profile_directories = NULL, $site_path = NULL) {
     $this->root = $root;
     $this->fileCache = $use_file_cache ? FileCacheFactory::get('extension_discovery') : NULL;
     $this->profileDirectories = $profile_directories;
     $this->sitePath = $site_path;
+    // Invalidate the cache if we're using a new root directory. We must do this
+    // since $files is static.
+    if ($this->root != static::$cacheRoot) {
+      static::$files = [];
+      static::$cacheRoot = $this->root;
+    }
   }
 
   /**
@@ -152,8 +169,9 @@ public function __construct($root, $use_file_cache = TRUE, $profile_directories
   public function scan($type, $include_tests = NULL) {
     // Determine the installation profile directories to scan for extensions,
     // unless explicit profile directories have been set. Exclude profiles as we
-    // cannot have profiles within profiles.
-    if (!isset($this->profileDirectories) && $type != 'profile') {
+    // cannot have profiles within profiles. If no profiles are specified in the
+    // constructor, profileDirectories will be NULL.
+    if (($this->profileDirectories === NULL) && $type != 'profile') {
       $this->setProfileDirectoriesFromSettings();
     }
 
@@ -187,7 +205,7 @@ public function scan($type, $include_tests = NULL) {
       $searchdirs[static::ORIGIN_SITE] = \Drupal::service('site.path');
     }
     else {
-      $searchdirs[static::ORIGIN_SITE] = $this->sitePath ?: DrupalKernel::findSitePath(Request::createFromGlobals());
+      $searchdirs[static::ORIGIN_SITE] = $this->sitePath ? : DrupalKernel::findSitePath(Request::createFromGlobals());
     }
 
     // Unless an explicit value has been passed, manually check whether we are
@@ -198,6 +216,7 @@ public function scan($type, $include_tests = NULL) {
       $include_tests = Settings::get('extension_discovery_scan_tests') || drupal_valid_test_ua();
     }
 
+    // Scan for extensions.
     $files = array();
     foreach ($searchdirs as $dir) {
       // Discover all extensions in the directory, unless we did already.
diff --git a/core/lib/Drupal/Core/Update/UpdateRegistry.php b/core/lib/Drupal/Core/Update/UpdateRegistry.php
index cc2f8b0..1eed538 100644
--- a/core/lib/Drupal/Core/Update/UpdateRegistry.php
+++ b/core/lib/Drupal/Core/Update/UpdateRegistry.php
@@ -241,11 +241,11 @@ public function getModuleUpdateFunctions($module_name) {
    */
   protected function scanExtensionsAndLoadUpdateFiles() {
     // Scan the module list.
-    $extension_discovery = new ExtensionDiscovery($this->root, FALSE, [], $this->sitePath);
-    $module_extensions = $extension_discovery->scan('module');
-
-    $profile_extensions = $extension_discovery->scan('profile');
-    $extensions = array_merge($module_extensions, $profile_extensions);
+    $extension_discovery = new ExtensionDiscovery($this->root, FALSE, NULL, $this->sitePath);
+    $extensions = array_merge(
+      $extension_discovery->scan('profile'),
+      $extension_discovery->scan('module')
+    );
 
     $this->loadUpdateFiles($extensions);
   }
diff --git a/core/modules/aggregator/src/Form/SettingsForm.php b/core/modules/aggregator/src/Form/SettingsForm.php
index 6af1b35..113fd8f 100644
--- a/core/modules/aggregator/src/Form/SettingsForm.php
+++ b/core/modules/aggregator/src/Form/SettingsForm.php
@@ -62,7 +62,7 @@ class SettingsForm extends ConfigFormBase {
    */
   public function __construct(ConfigFactoryInterface $config_factory, AggregatorPluginManager $fetcher_manager, AggregatorPluginManager $parser_manager, AggregatorPluginManager $processor_manager, TranslationInterface $string_translation) {
     parent::__construct($config_factory);
-    $this->stringTranslation = $string_translation;
+    $this->setStringTranslation($string_translation);
     $this->managers = array(
       'fetcher' => $fetcher_manager,
       'parser' => $parser_manager,
diff --git a/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php b/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php
index 1c4eb17..f99ad08 100644
--- a/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php
+++ b/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php
@@ -5,7 +5,7 @@
  * Contains \Drupal\Tests\aggregator\Unit\Plugin\AggregatorPluginSettingsBaseTest.
  */
 
-namespace Drupal\Tests\aggregator\Unit\Plugin {
+namespace Drupal\Tests\aggregator\Unit\Plugin;
 
 use Drupal\aggregator\Form\SettingsForm;
 use Drupal\Core\Form\FormState;
@@ -76,6 +76,26 @@ protected function setUp() {
    * plugins that extend AggregatorPluginSettingsBase.
    */
   public function testSettingsForm() {
+    // Eventually, this form will call drupal_set_message(), which requires a
+    // service from the DI container, which it accesses using the static \Drupal
+    // discovery object. Since \Drupal::setContainer() performs class checking,
+    // we can't use the mocked container we already have. Luckily, we're able to
+    // feed a different container to \Drupal, since it has different
+    // expectations than our settings form.
+    // @todo Change after https://www.drupal.org/node/2278383 is in.
+    $mock_drupal_container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')
+      ->disableOriginalConstructor()
+      ->getMockForAbstractClass();
+    $mock_kill_switch = $this->getMockBuilder('Drupal\Core\PageCache\ResponsePolicy\KillSwitch')
+      ->disableOriginalConstructor()
+      ->setMethods(['trigger'])
+      ->getMock();
+    $mock_drupal_container->expects($this->once())
+      ->method('get')
+      ->with($this->equalTo('page_cache_kill_switch'))
+      ->willReturn($mock_kill_switch);
+    \Drupal::setContainer($mock_drupal_container);
+
     // Emulate a form state of a submitted form.
     $form_state = (new FormState())->setValues([
       'dummy_length' => '',
@@ -109,12 +129,3 @@ public function testSettingsForm() {
   }
 
 }
-
-}
-
-namespace {
-  // @todo Delete after https://www.drupal.org/node/1858196 is in.
-  if (!function_exists('drupal_set_message')) {
-    function drupal_set_message() {}
-  }
-}
diff --git a/core/modules/views/tests/src/Unit/EntityViewsDataTest.php b/core/modules/views/tests/src/Unit/EntityViewsDataTest.php
index 9a65d6e..7240ac4 100644
--- a/core/modules/views/tests/src/Unit/EntityViewsDataTest.php
+++ b/core/modules/views/tests/src/Unit/EntityViewsDataTest.php
@@ -5,7 +5,7 @@
  * Contains \Drupal\Tests\views\Unit\EntityViewsDataTest.
  */
 
-namespace Drupal\Tests\views\Unit {
+namespace Drupal\Tests\views\Unit;
 
 use Drupal\Core\Config\Entity\ConfigEntityType;
 use Drupal\Core\Entity\ContentEntityType;
@@ -117,6 +117,7 @@ protected function setUp() {
     $container->set('plugin.manager.field.field_type', $field_type_manager);
     $container->set('entity.manager', $this->entityManager);
     $container->set('typed_data_manager', $typed_data_manager);
+    $container->set('string_translation', $this->translationManager);
     \Drupal::setContainer($container);
   }
 
@@ -927,13 +928,3 @@ public function setKey($key, $value) {
   }
 
 }
-
-}
-
-namespace {
-  if (!function_exists('t')) {
-    function t($string, array $args = []) {
-      return strtr($string, $args);
-    }
-  }
-}
diff --git a/core/scripts/run-tests.sh b/core/scripts/run-tests.sh
index 9ca309f..63067a4 100755
--- a/core/scripts/run-tests.sh
+++ b/core/scripts/run-tests.sh
@@ -47,7 +47,7 @@
 if ($args['list']) {
   // Display all available tests.
   echo "\nAvailable test groups & classes\n";
-  echo   "-------------------------------\n\n";
+  echo "-------------------------------\n\n";
   $groups = simpletest_test_get_all($args['module']);
   foreach ($groups as $group => $tests) {
     echo $group . "\n";
@@ -239,7 +239,8 @@ function simpletest_script_help() {
 /**
  * Parse execution argument and ensure that all are valid.
  *
- * @return The list of arguments.
+ * @return array
+ *   The list of arguments.
  */
 function simpletest_script_parse_args() {
   // Set default values.
@@ -305,7 +306,7 @@ function simpletest_script_parse_args() {
     }
   }
 
-  // Validate the concurrency argument
+  // Validate the concurrency argument.
   if (!is_numeric($args['concurrency']) || $args['concurrency'] <= 0) {
     simpletest_script_print_error("--concurrency must be a strictly positive integer.");
     exit;
@@ -338,7 +339,7 @@ function simpletest_script_init() {
   elseif ($sudo = getenv('SUDO_COMMAND')) {
     // 'SUDO_COMMAND' is an environment variable set by the sudo program.
     // Extract only the PHP interpreter, not the rest of the command.
-    list($php, ) = explode(' ', $sudo, 2);
+    list($php,) = explode(' ', $sudo, 2);
   }
   else {
     simpletest_script_print_error('Unable to automatically determine the path to the PHP interpreter. Supply the --php command line argument.');
@@ -379,11 +380,11 @@ function simpletest_script_init() {
   $_SERVER['SERVER_PORT'] = $port;
   $_SERVER['SERVER_SOFTWARE'] = NULL;
   $_SERVER['SERVER_NAME'] = 'localhost';
-  $_SERVER['REQUEST_URI'] = $path .'/';
+  $_SERVER['REQUEST_URI'] = $path . '/';
   $_SERVER['REQUEST_METHOD'] = 'GET';
-  $_SERVER['SCRIPT_NAME'] = $path .'/index.php';
-  $_SERVER['SCRIPT_FILENAME'] = $path .'/index.php';
-  $_SERVER['PHP_SELF'] = $path .'/index.php';
+  $_SERVER['SCRIPT_NAME'] = $path . '/index.php';
+  $_SERVER['SCRIPT_FILENAME'] = $path . '/index.php';
+  $_SERVER['PHP_SELF'] = $path . '/index.php';
   $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
 
   if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
@@ -563,9 +564,9 @@ function simpletest_script_execute_batch($test_classes) {
         if ($status['exitcode']) {
           echo 'FATAL ' . $child['class'] . ': test runner returned a non-zero error code (' . $status['exitcode'] . ').' . "\n";
           if ($args['die-on-fail']) {
-            list($db_prefix, ) = simpletest_last_test_get($child['test_id']);
+            list($db_prefix,) = simpletest_last_test_get($child['test_id']);
             $test_directory = 'sites/simpletest/' . substr($db_prefix, 10);
-            echo 'Simpletest database and files kept and test exited immediately on fail so should be reproducible if you change settings.php to use the database prefix '. $db_prefix . ' and config directories in '. $test_directory . "\n";
+            echo 'Simpletest database and files kept and test exited immediately on fail so should be reproducible if you change settings.php to use the database prefix ' . $db_prefix . ' and config directories in ' . $test_directory . "\n";
             $args['keep-results'] = TRUE;
             // Exit repeat loop immediately.
             $args['repeat'] = -1;
@@ -584,7 +585,7 @@ function simpletest_script_execute_batch($test_classes) {
 }
 
 /**
- * Run a group of phpunit tests.
+ * Run a PHPUnit-based test.
  */
 function simpletest_script_run_phpunit($test_id, $class) {
 
@@ -613,12 +614,15 @@ function simpletest_script_run_phpunit($test_id, $class) {
       case 'pass':
         $summaries[$result['test_class']]['#pass']++;
         break;
+
       case 'fail':
         $summaries[$result['test_class']]['#fail']++;
         break;
+
       case 'exception':
         $summaries[$result['test_class']]['#exception']++;
         break;
+
       case 'debug':
         $summaries[$result['test_class']]['#debug']++;
         break;
@@ -631,7 +635,7 @@ function simpletest_script_run_phpunit($test_id, $class) {
 }
 
 /**
- * Bootstrap Drupal and run a single test.
+ * Run a single test, bootstraping Drupal if needed.
  */
 function simpletest_script_run_one_test($test_id, $test_class) {
   global $args;
@@ -671,10 +675,13 @@ function simpletest_script_run_one_test($test_id, $test_class) {
 /**
  * Return a command used to run a test in a separate process.
  *
- * @param $test_id
- *  The current test ID.
- * @param $test_class
- *  The name of the test class to run.
+ * @param string $test_id
+ *   The current test ID.
+ * @param string $test_class
+ *   The name of the test class to run.
+ *
+ * @return string
+ *   The assembled command string.
  */
 function simpletest_script_command($test_id, $test_class) {
   global $args, $php;
@@ -726,7 +733,7 @@ function simpletest_script_cleanup($test_id, $test_class, $exitcode) {
     return;
   }
   // Retrieve the last database prefix used for testing.
-  list($db_prefix, ) = simpletest_last_test_get($test_id);
+  list($db_prefix,) = simpletest_last_test_get($test_id);
 
   // If no database prefix was found, then the test was not set up correctly.
   if (empty($db_prefix)) {
@@ -780,12 +787,15 @@ function simpletest_script_cleanup($test_id, $test_class, $exitcode) {
 }
 
 /**
- * Get list of tests based on arguments. If --all specified then
- * returns all available tests, otherwise reads list of tests.
+ * Get list of tests based on arguments.
+ *
+ * If --all specified then return all available tests, otherwise reads list of
+ * tests.
  *
  * Will print error and exit if no valid tests were found.
  *
- * @return List of tests.
+ * @return array
+ *   List of tests.
  */
 function simpletest_script_get_test_list() {
   global $args;
@@ -803,7 +813,7 @@ function simpletest_script_get_test_list() {
     if ($args['class']) {
       $test_list = array();
       foreach ($args['test_names'] as $test_class) {
-        list($class_name, ) = explode('::', $test_class, 2);
+        list($class_name,) = explode('::', $test_class, 2);
         if (class_exists($class_name)) {
           $test_list[] = $test_class;
         }
@@ -873,8 +883,8 @@ function simpletest_script_get_test_list() {
         //   ./foo/tests/Drupal/foo/Tests/FooTest.php
         //   ./foo/tests/src/FooTest.php
         // $file->filename doesn't give us a directory, so we use $file->uri
-        // Strip the drupal root directory and trailing slash off the URI
-        $filename = substr($file->uri, strlen(DRUPAL_ROOT)+1);
+        // Strip the drupal root directory and trailing slash off the URI.
+        $filename = substr($file->uri, strlen(DRUPAL_ROOT) + 1);
         if (stripos($filename, '/Tests/')) {
           $files[$filename] = $filename;
         }
@@ -1104,10 +1114,10 @@ function simpletest_script_reporter_display_results() {
 }
 
 /**
- * Format the result so that it fits within the default 80 character
- * terminal size.
+ * Format the result so that it fits within 80 characters.
  *
- * @param $result The result object to format.
+ * @param string $result
+ *   The result object to format.
  */
 function simpletest_script_format_result($result) {
   global $args, $results_map, $color;
@@ -1128,21 +1138,25 @@ function simpletest_script_format_result($result) {
 }
 
 /**
- * Print error message prefixed with "  ERROR: " and displayed in fail color
- * if color output is enabled.
+ * Print error messages so the user will notice them.
  *
- * @param $message The message to print.
+ * Print error message prefixed with "  ERROR: " and displayed in fail color if
+ * color output is enabled.
+ *
+ * @param string $message
+ *   The message to print.
  */
 function simpletest_script_print_error($message) {
   simpletest_script_print("  ERROR: $message\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
 }
 
 /**
- * Print a message to the console, if color is enabled then the specified
- * color code will be used.
+ * Print a message to the console, using a color.
  *
- * @param $message The message to print.
- * @param $color_code The color code to use for coloring.
+ * @param string $message
+ *   The message to print.
+ * @param int $color_code
+ *   The color code to use for coloring.
  */
 function simpletest_script_print($message, $color_code) {
   global $args;
@@ -1157,19 +1171,26 @@ function simpletest_script_print($message, $color_code) {
 /**
  * Get the color code associated with the specified status.
  *
- * @param $status The status string to get code for.
- * @return Color code.
+ * @param string $status
+ *   The status string to get code for. Special cases are: 'pass', 'fail', or
+ *   'exception'.
+ *
+ * @return int
+ *   Color code. Returns 0 for default case.
  */
 function simpletest_script_color_code($status) {
   switch ($status) {
     case 'pass':
       return SIMPLETEST_SCRIPT_COLOR_PASS;
+
     case 'fail':
       return SIMPLETEST_SCRIPT_COLOR_FAIL;
+
     case 'exception':
       return SIMPLETEST_SCRIPT_COLOR_EXCEPTION;
   }
-  return 0; // Default formatting.
+  // Default formatting.
+  return 0;
 }
 
 /**
@@ -1178,8 +1199,6 @@ function simpletest_script_color_code($status) {
  * Searches the provided array of string values for close matches based on the
  * Levenshtein algorithm.
  *
- * @see http://php.net/manual/en/function.levenshtein.php
- *
  * @param string $string
  *   A string to test.
  * @param array $array
@@ -1189,6 +1208,8 @@ function simpletest_script_color_code($status) {
  *   4 means that the function will return strings from $array if the candidate
  *   string in $array would be identical to $string by changing 1/4 or fewer of
  *   its characters.
+ *
+ * @see http://php.net/manual/en/function.levenshtein.php
  */
 function simpletest_script_print_alternatives($string, $array, $degree = 4) {
   $alternatives = array();
@@ -1275,14 +1296,14 @@ function simpletest_script_open_browser() {
 
   // Make the html page to write to disk.
   $render_service = \Drupal::service('renderer');
-  $html = '<head>' . $render_service->renderPlain($js_assets_header) . $render_service->renderPlain($css_assets) . '</head><body>' . $render_service->renderPlain($form) . $render_service->renderPlain($js_assets_footer) .'</body>';
+  $html = '<head>' . $render_service->renderPlain($js_assets_header) . $render_service->renderPlain($css_assets) . '</head><body>' . $render_service->renderPlain($form) . $render_service->renderPlain($js_assets_footer) . '</body>';
 
   // Ensure we have assets verbose directory - tests with no verbose output will not
   // have created one.
   $directory = PublicStream::basePath() . '/simpletest/verbose';
   file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
   $uuid = new Php();
-  $filename = $directory .'/results-'. $uuid->generate() .'.html';
+  $filename = $directory . '/results-' . $uuid->generate() . '.html';
   file_put_contents($filename, $html);
 
   // See if we can find an OS helper to open URLs in default browser.
diff --git a/core/tests/Drupal/Tests/Core/DrupalKernel/DrupalKernelTest.php b/core/tests/Drupal/Tests/Core/DrupalKernel/DrupalKernelTest.php
index d923f9a..5f70e49 100644
--- a/core/tests/Drupal/Tests/Core/DrupalKernel/DrupalKernelTest.php
+++ b/core/tests/Drupal/Tests/Core/DrupalKernel/DrupalKernelTest.php
@@ -5,148 +5,135 @@
  * Contains \Drupal\Tests\Core\DrupalKernel\DrupalKernelTest.
  */
 
-namespace Drupal\Tests\Core\DrupalKernel {
+namespace Drupal\Tests\Core\DrupalKernel;
 
-  use Drupal\Core\DrupalKernel;
-  use Drupal\Tests\UnitTestCase;
-  use org\bovigo\vfs\vfsStream;
-  use Symfony\Component\HttpFoundation\Request;
+use Drupal\Core\DrupalKernel;
+use Drupal\Tests\UnitTestCase;
+use org\bovigo\vfs\vfsStream;
+use Symfony\Component\HttpFoundation\Request;
+
+/**
+ * @coversDefaultClass \Drupal\Core\DrupalKernel
+ * @group DrupalKernel
+ */
+class DrupalKernelTest extends UnitTestCase {
 
   /**
-   * @coversDefaultClass \Drupal\Core\DrupalKernel
-   * @group DrupalKernel
+   * Tests hostname validation with settings.
+   *
+   * @covers ::setupTrustedHosts
+   * @dataProvider providerTestTrustedHosts
    */
-  class DrupalKernelTest extends UnitTestCase {
-
-    /**
-     * Tests hostname validation with settings.
-     *
-     * @covers ::setupTrustedHosts
-     * @dataProvider providerTestTrustedHosts
-     */
-    public function testTrustedHosts($host, $server_name, $message, $expected = FALSE) {
-      $request = new Request();
-
-      $trusted_host_patterns = [
-        '^example\.com$',
-        '^.+\.example\.com$',
-        '^example\.org',
-        '^.+\.example\.org',
-      ];
-
-      if (!empty($host)) {
-        $request->headers->set('HOST', $host);
-      }
-
-      $request->server->set('SERVER_NAME', $server_name);
-
-      $method = new \ReflectionMethod('Drupal\Core\DrupalKernel', 'setupTrustedHosts');
-      $method->setAccessible(TRUE);
-      $valid_host = $method->invoke(null, $request, $trusted_host_patterns);
-
-      $this->assertSame($expected, $valid_host, $message);
-
-      // Reset the trusted hosts because it is statically stored on the request.
-      $method->invoke(null, $request, []);
-      // Reset the request factory because it is statically stored on the request.
-      Request::setFactory(NULL);
+  public function testTrustedHosts($host, $server_name, $message, $expected = FALSE) {
+    $request = new Request();
+
+    $trusted_host_patterns = [
+      '^example\.com$',
+      '^.+\.example\.com$',
+      '^example\.org',
+      '^.+\.example\.org',
+    ];
+
+    if (!empty($host)) {
+      $request->headers->set('HOST', $host);
     }
 
-    /**
-     * Provides test data for testTrustedHosts().
-     */
-    public function providerTestTrustedHosts() {
-      $data = [];
-
-      // Tests canonical URL.
-      $data[] = [
-        'www.example.com',
-        'www.example.com',
-        'canonical URL is trusted',
-        TRUE
-      ];
-
-      // Tests missing hostname for HTTP/1.0 compatibility where the Host
-      // header is optional.
-      $data[] = [NULL, 'www.example.com', 'empty Host is valid', TRUE];
-
-      // Tests the additional patterns from the settings.
-      $data[] = [
-        'example.com',
-        'www.example.com',
-        'host from settings is trusted',
-        TRUE
-      ];
-      $data[] = [
-        'subdomain.example.com',
-        'www.example.com',
-        'host from settings is trusted',
-        TRUE
-      ];
-      $data[] = [
-        'www.example.org',
-        'www.example.com',
-        'host from settings is trusted',
-        TRUE
-      ];
-      $data[] = [
-        'example.org',
-        'www.example.com',
-        'host from settings is trusted',
-        TRUE
-      ];
-
-      // Tests mismatch.
-      $data[] = [
-        'www.blackhat.com',
-        'www.example.com',
-        'unspecified host is untrusted',
-        FALSE
-      ];
-
-      return $data;
-    }
+    $request->server->set('SERVER_NAME', $server_name);
 
-    /**
-     * Tests site path finding.
-     *
-     * This test is run in a separate process since it defines DRUPAL_ROOT. This
-     * stops any possible pollution of other tests.
-     *
-     * @covers ::findSitePath
-     * @runInSeparateProcess
-     */
-    public function testFindSitePath() {
-      $vfs_root = vfsStream::setup('drupal_root');
-      $sites_php = <<<'EOD'
-<?php
-$sites['8888.www.example.org'] = 'example';
-EOD;
+    $method = new \ReflectionMethod('Drupal\Core\DrupalKernel', 'setupTrustedHosts');
+    $method->setAccessible(TRUE);
+    $valid_host = $method->invoke(null, $request, $trusted_host_patterns);
 
-      // Create the expected directory structure.
-      vfsStream::create(['sites' => [
-        'sites.php' => $sites_php,
-        'example' => [
-          'settings.php' => 'test'
-        ]
-      ]]);
-
-      define('DRUPAL_ROOT', $vfs_root->url('drupal_root'));
-      $request = new Request();
-      $request->server->set('SERVER_NAME', 'www.example.org');
-      $request->server->set('SERVER_PORT', '8888');
-      $request->server->set('SCRIPT_NAME', '/index.php');
-      $this->assertEquals('sites/example', DrupalKernel::findSitePath($request));
-    }
+    $this->assertSame($expected, $valid_host, $message);
+
+    // Reset the trusted hosts because it is statically stored on the request.
+    $method->invoke(null, $request, []);
+    // Reset the request factory because it is statically stored on the request.
+    Request::setFactory(NULL);
   }
 
-}
+  /**
+   * Provides test data for testTrustedHosts().
+   */
+  public function providerTestTrustedHosts() {
+    $data = [];
+
+    // Tests canonical URL.
+    $data[] = [
+      'www.example.com',
+      'www.example.com',
+      'canonical URL is trusted',
+      TRUE
+    ];
+
+    // Tests missing hostname for HTTP/1.0 compatibility where the Host
+    // header is optional.
+    $data[] = [NULL, 'www.example.com', 'empty Host is valid', TRUE];
+
+    // Tests the additional patterns from the settings.
+    $data[] = [
+      'example.com',
+      'www.example.com',
+      'host from settings is trusted',
+      TRUE
+    ];
+    $data[] = [
+      'subdomain.example.com',
+      'www.example.com',
+      'host from settings is trusted',
+      TRUE
+    ];
+    $data[] = [
+      'www.example.org',
+      'www.example.com',
+      'host from settings is trusted',
+      TRUE
+    ];
+    $data[] = [
+      'example.org',
+      'www.example.com',
+      'host from settings is trusted',
+      TRUE
+    ];
+
+    // Tests mismatch.
+    $data[] = [
+      'www.blackhat.com',
+      'www.example.com',
+      'unspecified host is untrusted',
+      FALSE
+    ];
+
+    return $data;
+  }
 
+  /**
+   * Tests site path finding.
+   *
+   * This test is run in a separate process since it defines DRUPAL_ROOT. This
+   * stops any possible pollution of other tests.
+   *
+   * @covers ::findSitePath
+   */
+  public function testFindSitePath() {
+    $vfs_root = vfsStream::setup('drupal_root');
+    $sites_php = <<<'EOD'
+<?php
+$sites['8888.www.example.org'] = 'example';
+EOD;
 
-namespace {
-  if (!function_exists('drupal_valid_test_ua')) {
-    function drupal_valid_test_ua($new_prefix = NULL) {
-      return FALSE;
-    }
+    // Create the expected directory structure.
+    vfsStream::create(['sites' => [
+      'sites.php' => $sites_php,
+      'example' => [
+        'settings.php' => 'test'
+      ]
+    ]]);
+
+    $request = new Request();
+    $request->server->set('SERVER_NAME', 'www.example.org');
+    $request->server->set('SERVER_PORT', '8888');
+    $request->server->set('SCRIPT_NAME', '/index.php');
+    $this->assertEquals('sites/example', DrupalKernel::findSitePath($request, TRUE, $vfs_root->url('drupal_root')));
   }
-}
\ No newline at end of file
+}
diff --git a/core/tests/bootstrap.php b/core/tests/bootstrap.php
index 626f4ba..d42a9a3 100644
--- a/core/tests/bootstrap.php
+++ b/core/tests/bootstrap.php
@@ -7,57 +7,14 @@
  * @see phpunit.xml.dist
  */
 
-/**
- * Finds all valid extension directories recursively within a given directory.
- *
- * @param string $scan_directory
- *   The directory that should be recursively scanned.
- * @return array
- *   An associative array of extension directories found within the scanned
- *   directory, keyed by extension name.
- */
-function drupal_phpunit_find_extension_directories($scan_directory) {
-  $extensions = array();
-  $dirs = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($scan_directory, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS));
-  foreach ($dirs as $dir) {
-    if (strpos($dir->getPathname(), '.info.yml') !== FALSE) {
-      // Cut off ".info.yml" from the filename for use as the extension name.
-      $extensions[substr($dir->getFilename(), 0, -9)] = $dir->getPathInfo()
-        ->getRealPath();
-    }
-  }
-  return $extensions;
-}
+$loader = require __DIR__ . '/../../autoload.php';
+require __DIR__ . '/../includes/bootstrap.inc';
 
-/**
- * Returns directories under which contributed extensions may exist.
- *
- * @return array
- *   An array of directories under which contributed extensions may exist.
- */
-function drupal_phpunit_contrib_extension_directory_roots() {
-  $root = dirname(dirname(__DIR__));
-  $paths = array(
-    $root . '/core/modules',
-    $root . '/core/profiles',
-    $root . '/modules',
-    $root . '/profiles',
-  );
-  $sites_path = $root . '/sites';
-  // Note this also checks sites/../modules and sites/../profiles.
-  foreach (scandir($sites_path) as $site) {
-    if ($site[0] === '.' || $site === 'simpletest') {
-      continue;
-    }
-    $path = "$sites_path/$site";
-    $paths[] = is_dir("$path/modules") ? realpath("$path/modules") : NULL;
-    $paths[] = is_dir("$path/profiles") ? realpath("$path/profiles") : NULL;
-  }
-  return array_filter($paths);
-}
+use Drupal\Core\Extension\Extension;
+use Drupal\Core\Extension\ExtensionDiscovery;
 
 /**
- * Registers the namespace for each extension directory with the autoloader.
+ * Create a classmap for the namespace within each extension directory.
  *
  * @param array $dirs
  *   An associative array of extension directories, keyed by extension name.
@@ -69,11 +26,11 @@ function drupal_phpunit_get_extension_namespaces($dirs) {
   $namespaces = array();
   foreach ($dirs as $extension => $dir) {
     if (is_dir($dir . '/src')) {
-      // Register the PSR-4 directory for module-provided classes.
+      // Create PSR-4 classmap for module-provided classes.
       $namespaces['Drupal\\' . $extension . '\\'][] = $dir . '/src';
     }
     if (is_dir($dir . '/tests/src')) {
-      // Register the PSR-4 directory for PHPUnit test classes.
+      // Create PSR-4 classmap for PHPUnit test classes.
       $namespaces['Drupal\\Tests\\' . $extension . '\\'][] = $dir . '/tests/src';
     }
   }
@@ -88,16 +45,25 @@ function drupal_phpunit_get_extension_namespaces($dirs) {
   define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/../../autoload.php');
 }
 // Start with classes in known locations.
-$loader = require __DIR__ . '/../../autoload.php';
 $loader->add('Drupal\\Tests', __DIR__);
 $loader->add('Drupal\\KernelTests', __DIR__);
 
 if (!isset($GLOBALS['namespaces'])) {
   // Scan for arbitrary extension namespaces from core and contrib.
-  $extension_roots = drupal_phpunit_contrib_extension_directory_roots();
-
-  $dirs = array_map('drupal_phpunit_find_extension_directories', $extension_roots);
-  $dirs = array_reduce($dirs, 'array_merge', array());
+  $root = dirname(dirname(__DIR__));
+  $extension_discovery = new ExtensionDiscovery($root, FALSE);
+  $extension_discovery->setProfileDirectories([$root . '/profiles']);
+  $extensions = [];
+  foreach(['profile', 'module'] as $type) {
+    // We must include test modules because some tests use them.
+    $extensions = array_merge($extension_discovery->scan($type, TRUE), $extensions);
+  }
+  // Grab only the directory path.
+  $dirs = [];
+  foreach ($extensions as $extension_name => $extension) {
+    // Use full path.
+    $dirs[$extension_name] = $root . '/' . $extension->getPath();
+  };
   $GLOBALS['namespaces'] = drupal_phpunit_get_extension_namespaces($dirs);
 }
 foreach ($GLOBALS['namespaces'] as $prefix => $paths) {
