Problem/Motivation
Noticed in a test that the temp directory in a kernel test points to /tmp, which could cause conflicts between tests or accidentally delete things there. It also means that the folder is not isoalted and you can't assume that it is empty (in our test, we want to ensure that our logic leaves no temporary files behind).
There is \Drupal\Core\Test\TestSetupTrait::$tempFilesDirectory and \Drupal\Core\Test\FunctionalTestSetupTrait::prepareSettings that sets it up for functional test, but \Drupal\KernelTests\KernelTestBase::setUpFilesystem only prepares the public directory. and \Drupal\KernelTests\KernelTestBase::bootEnvironment() only defines the file_public_path setting but not file_temp_path, so \Drupal\Core\File\FileSystem::getTempDirectory() falls back to the system default
Steps to reproduce
Proposed resolution
We did this for our test, because we also can't use vfs:// as that's not supported.
// Create a test-specific but real (no vfs://) temp directory so we can
// assume that no other files are created during this test.
$file_system = \Drupal::service('file_system');
$test_db = new TestDatabase();
$tmp_directory = $test_db->getTestSitePath() . '/tmp';
$file_system->prepareDirectory($tmp_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
$this->setSetting('file_temp_path', $tmp_directory);
For backwards compatibility, i think it would be better to keep this out of vfs:// as well, or test might break. Getting the site path again can be avoided if it's set up in \Drupal\KernelTests\KernelTestBase::setUpFilesystem before overriding $this->siteDirectory.