function NodeSaveTest::testImport

Same name and namespace in other branches
  1. 8.9.x core/modules/node/tests/src/Functional/NodeSaveTest.php \Drupal\Tests\node\Functional\NodeSaveTest::testImport()
  2. 10 core/modules/node/tests/src/Functional/NodeSaveTest.php \Drupal\Tests\node\Functional\NodeSaveTest::testImport()
  3. 11.x core/modules/node/tests/src/Functional/NodeSaveTest.php \Drupal\Tests\node\Functional\NodeSaveTest::testImport()

Checks whether custom node IDs are saved properly during an import operation.

Workflow:

  • first create a piece of content
  • save the content
  • check if node exists

File

core/modules/node/tests/src/Functional/NodeSaveTest.php, line 53

Class

NodeSaveTest
Tests $node->save() for saving content.

Namespace

Drupal\Tests\node\Functional

Code

public function testImport() {
    // Node ID must be a number that is not in the database.
    $nids = \Drupal::entityTypeManager()->getStorage('node')
        ->getQuery()
        ->accessCheck(FALSE)
        ->sort('nid', 'DESC')
        ->range(0, 1)
        ->execute();
    $max_nid = reset($nids);
    $test_nid = $max_nid + mt_rand(1000, 1000000);
    $title = $this->randomMachineName(8);
    $node = [
        'title' => $title,
        'body' => [
            [
                'value' => $this->randomMachineName(32),
            ],
        ],
        'uid' => $this->webUser
            ->id(),
        'type' => 'article',
        'nid' => $test_nid,
    ];
    
    /** @var \Drupal\node\NodeInterface $node */
    $node = Node::create($node);
    $node->enforceIsNew();
    $this->assertEquals($this->webUser
        ->id(), $node->getOwnerId());
    $node->save();
    // Test the import.
    $node_by_nid = Node::load($test_nid);
    $this->assertNotEmpty($node_by_nid, 'Node load by node ID.');
    $node_by_title = $this->drupalGetNodeByTitle($title);
    $this->assertNotEmpty($node_by_title, 'Node load by node title.');
}

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