1ea8fcc3326caeb705b4a68f776af16f8a2dba95
[yaffs-website] / web / core / modules / node / tests / src / Functional / NodeCreationTest.php
1 <?php
2
3 namespace Drupal\Tests\node\Functional;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Language\LanguageInterface;
7 use Drupal\node\Entity\Node;
8
9 /**
10  * Create a node and test saving it.
11  *
12  * @group node
13  */
14 class NodeCreationTest extends NodeTestBase {
15
16   /**
17    * Modules to enable.
18    *
19    * Enable dummy module that implements hook_ENTITY_TYPE_insert() for
20    * exceptions (function node_test_exception_node_insert() ).
21    *
22    * @var array
23    */
24   public static $modules = ['node_test_exception', 'dblog', 'test_page_test'];
25
26   protected function setUp() {
27     parent::setUp();
28
29     $web_user = $this->drupalCreateUser(['create page content', 'edit own page content']);
30     $this->drupalLogin($web_user);
31   }
32
33   /**
34    * Creates a "Basic page" node and verifies its consistency in the database.
35    */
36   public function testNodeCreation() {
37     $node_type_storage = \Drupal::entityManager()->getStorage('node_type');
38
39     // Test /node/add page with only one content type.
40     $node_type_storage->load('article')->delete();
41     $this->drupalGet('node/add');
42     $this->assertResponse(200);
43     $this->assertUrl('node/add/page');
44     // Create a node.
45     $edit = [];
46     $edit['title[0][value]'] = $this->randomMachineName(8);
47     $edit['body[0][value]'] = $this->randomMachineName(16);
48     $this->drupalPostForm('node/add/page', $edit, t('Save'));
49
50     // Check that the Basic page has been created.
51     $this->assertText(t('@post @title has been created.', ['@post' => 'Basic page', '@title' => $edit['title[0][value]']]), 'Basic page created.');
52
53     // Verify that the creation message contains a link to a node.
54     $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'node/']);
55     $this->assert(isset($view_link), 'The message area contains a link to a node');
56
57     // Check that the node exists in the database.
58     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
59     $this->assertTrue($node, 'Node found in database.');
60
61     // Verify that pages do not show submitted information by default.
62     $this->drupalGet('node/' . $node->id());
63     $this->assertNoText($node->getOwner()->getUsername());
64     $this->assertNoText(format_date($node->getCreatedTime()));
65
66     // Change the node type setting to show submitted by information.
67     /** @var \Drupal\node\NodeTypeInterface $node_type */
68     $node_type = $node_type_storage->load('page');
69     $node_type->setDisplaySubmitted(TRUE);
70     $node_type->save();
71
72     $this->drupalGet('node/' . $node->id());
73     $this->assertText($node->getOwner()->getUsername());
74     $this->assertText(format_date($node->getCreatedTime()));
75
76     // Check if the node revision checkbox is not rendered on node creation form.
77     $admin_user = $this->drupalCreateUser(['administer nodes', 'create page content']);
78     $this->drupalLogin($admin_user);
79     $this->drupalGet('node/add/page');
80     $this->assertNoFieldById('edit-revision', NULL, 'The revision checkbox is not present.');
81   }
82
83   /**
84    * Verifies that a transaction rolls back the failed creation.
85    */
86   public function testFailedPageCreation() {
87     // Create a node.
88     $edit = [
89       'uid'      => $this->loggedInUser->id(),
90       'name'     => $this->loggedInUser->name,
91       'type'     => 'page',
92       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
93       'title'    => 'testing_transaction_exception',
94     ];
95
96     try {
97       // An exception is generated by node_test_exception_node_insert() if the
98       // title is 'testing_transaction_exception'.
99       Node::create($edit)->save();
100       $this->fail(t('Expected exception has not been thrown.'));
101     }
102     catch (\Exception $e) {
103       $this->pass(t('Expected exception has been thrown.'));
104     }
105
106     if (Database::getConnection()->supportsTransactions()) {
107       // Check that the node does not exist in the database.
108       $node = $this->drupalGetNodeByTitle($edit['title']);
109       $this->assertFalse($node, 'Transactions supported, and node not found in database.');
110     }
111     else {
112       // Check that the node exists in the database.
113       $node = $this->drupalGetNodeByTitle($edit['title']);
114       $this->assertTrue($node, 'Transactions not supported, and node found in database.');
115
116       // Check that the failed rollback was logged.
117       $records = static::getWatchdogIdsForFailedExplicitRollback();
118       $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
119     }
120
121     // Check that the rollback error was logged.
122     $records = static::getWatchdogIdsForTestExceptionRollback();
123     $this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.');
124   }
125
126   /**
127    * Creates an unpublished node and confirms correct redirect behavior.
128    */
129   public function testUnpublishedNodeCreation() {
130     // Set the front page to the test page.
131     $this->config('system.site')->set('page.front', '/test-page')->save();
132
133     // Set "Basic page" content type to be unpublished by default.
134     $fields = \Drupal::entityManager()->getFieldDefinitions('node', 'page');
135     $fields['status']->getConfig('page')
136       ->setDefaultValue(FALSE)
137       ->save();
138
139     // Create a node.
140     $edit = [];
141     $edit['title[0][value]'] = $this->randomMachineName(8);
142     $edit['body[0][value]'] = $this->randomMachineName(16);
143     $this->drupalPostForm('node/add/page', $edit, t('Save'));
144
145     // Check that the user was redirected to the home page.
146     $this->assertUrl('');
147     $this->assertText(t('Test page text'));
148
149     // Confirm that the node was created.
150     $this->assertText(t('@post @title has been created.', ['@post' => 'Basic page', '@title' => $edit['title[0][value]']]));
151
152     // Verify that the creation message contains a link to a node.
153     $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'node/']);
154     $this->assert(isset($view_link), 'The message area contains a link to a node');
155   }
156
157   /**
158    * Tests the author autocompletion textfield.
159    */
160   public function testAuthorAutocomplete() {
161     $admin_user = $this->drupalCreateUser(['administer nodes', 'create page content']);
162     $this->drupalLogin($admin_user);
163
164     $this->drupalGet('node/add/page');
165
166     $result = $this->xpath('//input[@id="edit-uid-0-value" and contains(@data-autocomplete-path, "user/autocomplete")]');
167     $this->assertEqual(count($result), 0, 'No autocompletion without access user profiles.');
168
169     $admin_user = $this->drupalCreateUser(['administer nodes', 'create page content', 'access user profiles']);
170     $this->drupalLogin($admin_user);
171
172     $this->drupalGet('node/add/page');
173
174     $result = $this->xpath('//input[@id="edit-uid-0-target-id" and contains(@data-autocomplete-path, "/entity_reference_autocomplete/user/default")]');
175     $this->assertEqual(count($result), 1, 'Ensure that the user does have access to the autocompletion');
176   }
177
178   /**
179    * Check node/add when no node types exist.
180    */
181   public function testNodeAddWithoutContentTypes() {
182     $this->drupalGet('node/add');
183     $this->assertResponse(200);
184     $this->assertNoLinkByHref('/admin/structure/types/add');
185
186     // Test /node/add page without content types.
187     foreach (\Drupal::entityManager()->getStorage('node_type')->loadMultiple() as $entity) {
188       $entity->delete();
189     }
190
191     $this->drupalGet('node/add');
192     $this->assertResponse(403);
193
194     $admin_content_types = $this->drupalCreateUser(['administer content types']);
195     $this->drupalLogin($admin_content_types);
196
197     $this->drupalGet('node/add');
198
199     $this->assertLinkByHref('/admin/structure/types/add');
200   }
201
202   /**
203    * Gets the watchdog IDs of the records with the rollback exception message.
204    *
205    * @return int[]
206    *   Array containing the IDs of the log records with the rollback exception
207    *   message.
208    */
209   protected static function getWatchdogIdsForTestExceptionRollback() {
210     // PostgreSQL doesn't support bytea LIKE queries, so we need to unserialize
211     // first to check for the rollback exception message.
212     $matches = [];
213     $query = db_query("SELECT wid, variables FROM {watchdog}");
214     foreach ($query as $row) {
215       $variables = (array) unserialize($row->variables);
216       if (isset($variables['@message']) && $variables['@message'] === 'Test exception for rollback.') {
217         $matches[] = $row->wid;
218       }
219     }
220     return $matches;
221   }
222
223   /**
224    * Gets the log records with the explicit rollback failed exception message.
225    *
226    * @return \Drupal\Core\Database\StatementInterface
227    *   A prepared statement object (already executed), which contains the log
228    *   records with the explicit rollback failed exception message.
229    */
230   protected static function getWatchdogIdsForFailedExplicitRollback() {
231     return db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
232   }
233
234 }