assertFileExists example

$php_string = '<?php print "Drupal"; ?>';

    // Test using a masked exploit file.     $response = $this->fileRequest($uri$php_string['Content-Disposition' => 'filename="example.php"']);
    // The filename is not munged because .txt is added and it is a known     // extension to apache.     $expected = $this->getExpectedNormalizedEntity(1, 'example.php_.txt', TRUE);
    // Override the expected filesize.     $expected['filesize'][0]['value'] = strlen($php_string);
    $this->assertResponseData($expected$response);
    $this->assertFileExists('public://foobar/example.php_.txt');

    // Add .php and .txt as allowed extensions. Since 'allow_insecure_uploads'     // is FALSE, .php files should be renamed to have a .txt extension.     $this->field->setSetting('file_extensions', 'php txt')->save();
    $this->refreshTestStateAfterRestConfigChange();

    $response = $this->fileRequest($uri$php_string['Content-Disposition' => 'filename="example_2.php"']);
    $expected = $this->getExpectedNormalizedEntity(2, 'example_2.php_.txt', TRUE);
    // Override the expected filesize.     $expected['filesize'][0]['value'] = strlen($php_string);
    $this->assertResponseData($expected$response);
    
    $result = $this->fileRepository->copy(clone $source$desired_uri, FileSystemInterface::EXISTS_ERROR);

    // Check the return status and that the contents changed.     $this->assertNotFalse($result, 'File copied successfully.');
    $this->assertEquals($contentsfile_get_contents($result->getFileUri()), 'Contents of file were copied correctly.');

    // Check that the correct hooks were called.     $this->assertFileHooksCalled(['copy', 'insert']);

    $this->assertDifferentFile($source$result);
    $this->assertEquals($result->getFileUri()$desired_uri, 'The copied file entity has the desired filepath.');
    $this->assertFileExists($source->getFileUri());
    $this->assertFileExists($result->getFileUri());

    // Reload the file from the database and check that the changes were     // actually saved.     $this->assertFileUnchanged($result, File::load($result->id()));
  }

  /** * Tests renaming when copying over a file that already exists. * * @covers ::copy */
'--blue-green' => '1',
            '--mailer-url' => 'smtp://localhost:25',
            '--composer-home' => __DIR__,
        ];

        $tester = $this->getCommandTester();

        $tester->execute($args['interactive' => false]);

        $tester->assertCommandIsSuccessful();

        static::assertFileExists(__DIR__ . '/.env');
        static::assertFileDoesNotExist(__DIR__ . '/.env.local.php');

        $envContent = file_get_contents(__DIR__ . '/.env');
        static::assertIsString($envContent);
        $env = (new Dotenv())->parse($envContent);

        static::assertArrayHasKey('APP_SECRET', $env);
        static::assertArrayHasKey('INSTANCE_ID', $env);
        unset($env['APP_SECRET']$env['INSTANCE_ID']);
        static::assertEquals([
            'APP_ENV' => 'test',
            
$kernel = new $class(
                'test',
                true,
                new StaticKernelPluginLoader($classLoader),
                Uuid::randomHex(),
                '1.0.0@' . $i . '1eec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33',
                $original->getContainer()->get(Connection::class)
            );

            $kernel->boot();
            $oldCacheDir = $kernel->getCacheDir();
            static::assertFileExists($oldCacheDir);
            $kernel->shutdown();
            $oldCacheDirs[] = $oldCacheDir;
        }
        $oldCacheDirs = array_unique($oldCacheDirs);

        static::assertCount(2, $oldCacheDirs);

        $second = KernelLifecycleManager::getKernel();
        $second->boot();
        static::assertFileExists($second->getCacheDir());

        
file_put_contents($targetBuildDir.'/manifest.json', '{}');
        file_put_contents($targetBuildDir.'/importmap.json', '{"imports": {}}');
        file_put_contents($targetBuildDir.'/importmap.preload.json', '{}');

        $command = $application->find('asset-map:compile');
        $tester = new CommandTester($command);
        $res = $tester->execute([]);
        $this->assertSame(0, $res);
        // match Compiling \d+ assets         $this->assertMatchesRegularExpression('/Compiled \d+ assets/', $tester->getDisplay());

        $this->assertFileExists($targetBuildDir.'/subdir/file5-f4fdc37375c7f5f2629c5659a0579967.js');
        $this->assertSame(<<<EOF import '../file4.js'; console.log('file5.js'); EOF, file_get_contents($targetBuildDir.'/subdir/file5-f4fdc37375c7f5f2629c5659a0579967.js'));

        $finder = new Finder();
        $finder->in($targetBuildDir)->files();
        $this->assertCount(10, $finder);
        $this->assertFileExists($targetBuildDir.'/manifest.json');

        
'files[field_image_0]' => $this->container->get('file_system')->realpath($image->getFileUri()),
    ];
    $this->submitForm($edit, 'Save');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains("$type $title has been created.");
    $matches = [];
    if (preg_match('@node/(\d+)$@', $this->getUrl()$matches)) {
      $nid = end($matches);
      $this->assertNotEquals(0, $nid, 'The node ID was extracted from the URL.');
      $node = Node::load($nid);
      $this->assertNotNull($node, 'The node was loaded successfully.');
      $this->assertFileExists(File::load($node->field_image->target_id)->getFileUri());
    }
  }

  /** * Tests file submission for an anonymous visitor with a missing node title. */
  public function testAnonymousNodeWithFileWithoutTitle() {
    $this->drupalLogout();
    $this->doTestNodeWithFileWithoutTitle();
  }

  
/** * Asserts that a given file exists and is/is not a symlink. * * @param string $path * The path to check exists. * @param bool $is_link * Checks if the file should be a symlink or not. * @param string $contents_contains * Regex to check the file contents. */
  protected function assertScaffoldedFile($path$is_link$contents_contains) {
    $this->assertFileExists($path);
    $contents = file_get_contents($path);
    $this->assertStringContainsString($contents_containsbasename($path) . ': ' . $contents);
    $this->assertSame($is_linkis_link($path));
  }

  /** * Asserts that a file does not exist or exists and does not contain a value. * * @param string $path * The path to check exists. * @param string $contents_not_contains * A string that is expected should NOT occur in the file contents. */

  protected function setUp(): void {
    parent::setUp();
    $account = $this->drupalCreateUser(['access site reports']);
    $this->drupalLogin($account);

    $image_files = $this->drupalGetTestFiles('image');
    $this->image = File::create((array) current($image_files));

    [$this->imageExtension] = explode('.', $this->image->getFilename());
    $this->assertFileExists($this->image->getFileUri());

    $this->phpfile = current($this->drupalGetTestFiles('php'));
    $this->assertFileExists($this->phpfile->uri);

    $this->maxFidBefore = (int) \Drupal::entityQueryAggregate('file')
      ->accessCheck(FALSE)
      ->aggregate('fid', 'max')
      ->execute()[0]['fid_max'];

    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    
$this->assertSession()->statusCodeEquals(204);
    $next_cron_time = \Drupal::state()->get('system.cron_last');

    $this->assertGreaterThan($last_cron_time$next_cron_time);
  }

  /** * Tests the Drupal install done in \Drupal\Tests\BrowserTestBase::setUp(). */
  public function testInstall() {
    $htaccess_filename = $this->tempFilesDirectory . '/.htaccess';
    $this->assertFileExists($htaccess_filename);

    // Ensure the update module is not installed.     $this->assertFalse(\Drupal::moduleHandler()->moduleExists('update'), 'The Update module is not installed.');
  }

  /** * Tests the assumption that local time is in 'Australia/Sydney'. */
  public function testLocalTimeZone() {
    $expected = 'Australia/Sydney';
    // The 'Australia/Sydney' time zone is set in core/tests/bootstrap.php

    public function testDump()
    {
        $tempDir = sys_get_temp_dir();

        $catalogue = new MessageCatalogue('en');
        $catalogue->add(['foo' => 'bar']);

        $dumper = new ConcreteFileDumper();
        $dumper->dump($catalogue['path' => $tempDir]);

        $this->assertFileExists($tempDir.'/messages.en.concrete');

        @unlink($tempDir.'/messages.en.concrete');
    }

    public function testDumpIntl()
    {
        $tempDir = sys_get_temp_dir();

        $catalogue = new MessageCatalogue('en');
        $catalogue->add(['foo' => 'bar'], 'd1');
        $catalogue->add(['bar' => 'foo'], 'd1+intl-icu');
        
// During testing, the file change and the stale checking occurs in the same     // request, so the beginning of request will be before the file changes and     // REQUEST_TIME - $filectime is negative or zero. Set the maximum age to a     // number greater than that.     $this->config('system.file')
      ->set('temporary_maximum_age', 100000)
      ->save();

    // First test that the file is not stale and thus not deleted.     $deleted = update_delete_file_if_stale($file_path);
    $this->assertFalse($deleted);
    $this->assertFileExists($file_path);

    // Set the maximum age to a number smaller than REQUEST_TIME - $filectime.     $this->config('system.file')
      ->set('temporary_maximum_age', -100000)
      ->save();

    // Now attempt to delete the file; as it should be considered stale, this     // attempt should succeed.     $deleted = update_delete_file_if_stale($file_path);
    $this->assertTrue($deleted);
    $this->assertFileDoesNotExist($file_path);
  }
public function testAnnotationsCacheWarmerWithDebugDisabled()
    {
        file_put_contents($this->cacheDir.'/annotations.map', sprintf('<?php return %s;', var_export([__CLASS__], true)));
        $cacheFile = tempnam($this->cacheDir, __FUNCTION__);
        $reader = new AnnotationReader();

        $this->expectDeprecation('Since symfony/framework-bundle 6.4: The "Symfony\Bundle\FrameworkBundle\CacheWarmer\AnnotationsCacheWarmer" class is deprecated without replacement.');
        $warmer = new AnnotationsCacheWarmer($reader$cacheFile);

        $warmer->warmUp($this->cacheDir);
        $this->assertFileExists($cacheFile);

        // Assert cache is valid         $reader = new PsrCachedReader(
            $this->getReadOnlyReader(),
            new PhpArrayAdapter($cacheFilenew NullAdapter())
        );
        $refClass = new \ReflectionClass($this);
        $reader->getClassAnnotations($refClass);
        $reader->getMethodAnnotations($refClass->getMethod(__FUNCTION__));
        $reader->getPropertyAnnotations($refClass->getProperty('cacheDir'));
    }

    
class FilesystemTest extends FilesystemTestCase
{
    public function testCopyCreatesNewFile()
    {
        $sourceFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_target_file';

        file_put_contents($sourceFilePath, 'SOURCE FILE');

        $this->filesystem->copy($sourceFilePath$targetFilePath);

        $this->assertFileExists($targetFilePath);
        $this->assertStringEqualsFile($targetFilePath, 'SOURCE FILE');
    }

    public function testCopyFails()
    {
        $this->expectException(IOException::class);
        $sourceFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_target_file';

        $this->filesystem->copy($sourceFilePath$targetFilePath);
    }

    
$image_files = $this->drupalGetTestFiles('image');

    $field_name = strtolower($this->randomMachineName());
    $this->createImageField($field_name, 'article', []['file_directory' => 'test-upload']);
    $expected_path = 'public://test-upload';

    // Create alt text for the image.     $alt = $this->randomMachineName();

    // Create a node with a valid image.     $node = $this->uploadNodeImage($image_files[0]$field_name, 'article', $alt);
    $this->assertFileExists($expected_path . '/' . $image_files[0]->filename);

    // Remove the image.     $this->drupalGet('node/' . $node . '/edit');
    $this->submitForm([], 'Remove');
    $this->submitForm([], 'Save');

    // Get invalid image test files.     $dir = 'core/tests/fixtures/files';
    $files = [];
    if (is_dir($dir)) {
      $files = $file_system->scanDirectory($dir, '/invalid-img-.*/');
    }
$cleaner = new EnvironmentCleaner(
      vfsStream::url('cleanup_test'),
      $connection->reveal(),
      $test_run_results_storage->reveal(),
      new NullOutput(),
      \Drupal::service('file_system')
    );

    $do_cleanup_ref = new \ReflectionMethod($cleaner, 'doCleanTemporaryDirectories');

    $this->assertFileExists(vfsStream::url('cleanup_test/sites/simpletest/delete_dir/delete.me'));
    $this->assertFileExists(vfsStream::url('cleanup_test/sites/simpletest/delete_me.too'));

    $this->assertEquals(2, $do_cleanup_ref->invoke($cleaner));

    $this->assertDirectoryDoesNotExist(vfsStream::url('cleanup_test/sites/simpletest/delete_dir'));
    $this->assertFileDoesNotExist(vfsStream::url('cleanup_test/sites/simpletest/delete_dir/delete.me'));
    $this->assertFileDoesNotExist(vfsStream::url('cleanup_test/sites/simpletest/delete_me.too'));
  }

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