a3646f0c0b38561baecc0069280baef4b5a9e95f
[yaffs-website] / web / core / modules / views / tests / src / Functional / Handler / FieldWebTest.php
1 <?php
2
3 namespace Drupal\Tests\views\Functional\Handler;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Component\Utility\UrlHelper;
8 use Drupal\Core\Render\RenderContext;
9 use Drupal\Core\Url;
10 use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
11 use Drupal\Tests\views\Functional\ViewTestBase;
12 use Drupal\views\Views;
13
14 /**
15  * Tests fields from within a UI.
16  *
17  * @group views
18  * @see \Drupal\views\Plugin\views\field\FieldPluginBase
19  */
20 class FieldWebTest extends ViewTestBase {
21
22   use AssertPageCacheContextsAndTagsTrait;
23
24   /**
25    * Views used by this test.
26    *
27    * @var array
28    */
29   public static $testViews = ['test_view', 'test_field_classes', 'test_field_output', 'test_click_sort'];
30
31   /**
32    * {@inheritdoc}
33    */
34   public static $modules = ['node'];
35
36   /**
37    * Maps between the key in the expected result and the query result.
38    *
39    * @var array
40    */
41   protected $columnMap = [
42     'views_test_data_name' => 'name',
43   ];
44
45   protected function setUp($import_test_views = TRUE) {
46     parent::setUp($import_test_views);
47
48     $this->enableViewsTestModule();
49   }
50
51   /**
52    * {@inheritdoc}
53    */
54   protected function viewsData() {
55     $data = parent::viewsData();
56     $data['views_test_data']['job']['field']['id'] = 'test_field';
57     return $data;
58   }
59
60   /**
61    * Tests the click sorting functionality.
62    */
63   public function testClickSorting() {
64     $this->drupalGet('test_click_sort');
65     $this->assertResponse(200);
66
67     // Only the id and name should be click sortable, but not the name.
68     $this->assertLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'id', 'sort' => 'asc']]));
69     $this->assertLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'name', 'sort' => 'desc']]));
70     $this->assertNoLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'created']]));
71
72     // Check that the view returns the click sorting cache contexts.
73     $expected_contexts = [
74       'languages:language_interface',
75       'theme',
76       'url.query_args',
77     ];
78     $this->assertCacheContexts($expected_contexts);
79
80     // Clicking a click sort should change the order.
81     $this->clickLink(t('ID'));
82     $this->assertLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'id', 'sort' => 'desc']]));
83     // Check that the output has the expected order (asc).
84     $ids = $this->clickSortLoadIdsFromOutput();
85     $this->assertEqual($ids, range(1, 5));
86
87     $this->clickLink(t('ID Sort descending'));
88     // Check that the output has the expected order (desc).
89     $ids = $this->clickSortLoadIdsFromOutput();
90     $this->assertEqual($ids, range(5, 1, -1));
91   }
92
93   /**
94    * Small helper function to get all ids in the output.
95    *
96    * @return array
97    *   A list of beatle ids.
98    */
99   protected function clickSortLoadIdsFromOutput() {
100     $fields = $this->xpath("//td[contains(@class, 'views-field-id')]");
101     $ids = [];
102     foreach ($fields as $field) {
103       $ids[] = (int) $field->getText();
104     }
105     return $ids;
106   }
107
108   /**
109    * Assertion helper which checks whether a string is part of another string.
110    *
111    * @param string $haystack
112    *   The value to search in.
113    * @param string $needle
114    *   The value to search for.
115    * @param string $message
116    *   The message to display along with the assertion.
117    * @param string $group
118    *   The type of assertion - examples are "Browser", "PHP".
119    * @return bool
120    *   TRUE if the assertion succeeded, FALSE otherwise.
121    */
122   protected function assertSubString($haystack, $needle, $message = '', $group = 'Other') {
123     return $this->assertTrue(strpos($haystack, $needle) !== FALSE, $message, $group);
124   }
125
126   /**
127    * Assertion helper which checks whether a string is not part of another string.
128    *
129    * @param string $haystack
130    *   The value to search in.
131    * @param string $needle
132    *   The value to search for.
133    * @param string $message
134    *   The message to display along with the assertion.
135    * @param string $group
136    *   The type of assertion - examples are "Browser", "PHP".
137    * @return bool
138    *   TRUE if the assertion succeeded, FALSE otherwise.
139    */
140   protected function assertNotSubString($haystack, $needle, $message = '', $group = 'Other') {
141     return $this->assertTrue(strpos($haystack, $needle) === FALSE, $message, $group);
142   }
143
144   /**
145    * Parse a content and return the html element.
146    *
147    * @param string $content
148    *   The html to parse.
149    *
150    * @return array
151    *   An array containing simplexml objects.
152    */
153   protected function parseContent($content) {
154     $htmlDom = new \DOMDocument();
155     @$htmlDom->loadHTML('<?xml encoding="UTF-8">' . $content);
156     $elements = simplexml_import_dom($htmlDom);
157
158     return $elements;
159   }
160
161   /**
162    * Performs an xpath search on a certain content.
163    *
164    * The search is relative to the root element of the $content variable.
165    *
166    * @param string $content
167    *   The html to parse.
168    * @param string $xpath
169    *   The xpath string to use in the search.
170    * @param array $arguments
171    *   Some arguments for the xpath.
172    *
173    * @return array|false
174    *   The return value of the xpath search. For details on the xpath string
175    *   format and return values see the SimpleXML documentation,
176    *   http://php.net/manual/function.simplexml-element-xpath.php.
177    */
178   protected function xpathContent($content, $xpath, array $arguments = []) {
179     if ($elements = $this->parseContent($content)) {
180       $xpath = $this->buildXPathQuery($xpath, $arguments);
181       $result = $elements->xpath($xpath);
182       // Some combinations of PHP / libxml versions return an empty array
183       // instead of the documented FALSE. Forcefully convert any falsish values
184       // to an empty array to allow foreach(...) constructions.
185       return $result ? $result : [];
186     }
187     else {
188       return FALSE;
189     }
190   }
191
192   /**
193    * Tests rewriting the output to a link.
194    */
195   public function testAlterUrl() {
196     /** @var \Drupal\Core\Render\RendererInterface $renderer */
197     $renderer = \Drupal::service('renderer');
198
199     $view = Views::getView('test_view');
200     $view->setDisplay();
201     $view->initHandlers();
202     $this->executeView($view);
203     $row = $view->result[0];
204     $id_field = $view->field['id'];
205
206     // Setup the general settings required to build a link.
207     $id_field->options['alter']['make_link'] = TRUE;
208     $id_field->options['alter']['path'] = $path = $this->randomMachineName();
209
210     // Tests that the suffix/prefix appears on the output.
211     $id_field->options['alter']['prefix'] = $prefix = $this->randomMachineName();
212     $id_field->options['alter']['suffix'] = $suffix = $this->randomMachineName();
213     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
214       return $id_field->theme($row);
215     });
216     $this->assertSubString($output, $prefix);
217     $this->assertSubString($output, $suffix);
218     unset($id_field->options['alter']['prefix']);
219     unset($id_field->options['alter']['suffix']);
220
221     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
222       return $id_field->theme($row);
223     });
224     $this->assertSubString($output, $path, 'Make sure that the path is part of the output');
225
226     // Some generic test code adapted from the UrlTest class, which tests
227     // mostly the different options for the path.
228     foreach ([FALSE, TRUE] as $absolute) {
229       $alter = &$id_field->options['alter'];
230       $alter['path'] = 'node/123';
231
232       $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['absolute' => $absolute]);
233       $alter['absolute'] = $absolute;
234       $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
235         return $id_field->theme($row);
236       });
237       $this->assertSubString($result, $expected_result);
238
239       $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['fragment' => 'foo', 'absolute' => $absolute]);
240       $alter['path'] = 'node/123#foo';
241       $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
242         return $id_field->theme($row);
243       });
244       $this->assertSubString($result, $expected_result);
245
246       $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => NULL], 'absolute' => $absolute]);
247       $alter['path'] = 'node/123?foo';
248       $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
249         return $id_field->theme($row);
250       });
251       $this->assertSubString($result, $expected_result);
252
253       $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => 'bar', 'bar' => 'baz'], 'absolute' => $absolute]);
254       $alter['path'] = 'node/123?foo=bar&bar=baz';
255       $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
256         return $id_field->theme($row);
257       });
258       $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));
259
260       // @todo The route-based URL generator strips out NULL attributes.
261       // $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => NULL], 'fragment' => 'bar', 'absolute' => $absolute]);
262       $expected_result = Url::fromUserInput('/node/123', ['query' => ['foo' => NULL], 'fragment' => 'bar', 'absolute' => $absolute])->toString();
263       $alter['path'] = 'node/123?foo#bar';
264       $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
265         return $id_field->theme($row);
266       });
267       $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));
268
269       $expected_result = \Drupal::url('<front>', [], ['absolute' => $absolute]);
270       $alter['path'] = '<front>';
271       $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
272         return $id_field->theme($row);
273       });
274       $this->assertSubString($result, $expected_result);
275     }
276
277     // Tests the replace spaces with dashes feature.
278     $id_field->options['alter']['replace_spaces'] = TRUE;
279     $id_field->options['alter']['path'] = $path = $this->randomMachineName() . ' ' . $this->randomMachineName();
280     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
281       return $id_field->theme($row);
282     });
283     $this->assertSubString($output, str_replace(' ', '-', $path));
284     $id_field->options['alter']['replace_spaces'] = FALSE;
285     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
286       return $id_field->theme($row);
287     });
288     // The url has a space in it, so to check we have to decode the url output.
289     $this->assertSubString(urldecode($output), $path);
290
291     // Tests the external flag.
292     // Switch on the external flag should output an external url as well.
293     $id_field->options['alter']['external'] = TRUE;
294     $id_field->options['alter']['path'] = $path = 'www.drupal.org';
295     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
296       return $id_field->theme($row);
297     });
298     $this->assertSubString($output, 'http://www.drupal.org');
299
300     // Setup a not external url, which shouldn't lead to an external url.
301     $id_field->options['alter']['external'] = FALSE;
302     $id_field->options['alter']['path'] = $path = 'www.drupal.org';
303     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
304       return $id_field->theme($row);
305     });
306     $this->assertNotSubString($output, 'http://www.drupal.org');
307
308     // Tests the transforming of the case setting.
309     $id_field->options['alter']['path'] = $path = $this->randomMachineName();
310     $id_field->options['alter']['path_case'] = 'none';
311     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
312       return $id_field->theme($row);
313     });
314     $this->assertSubString($output, $path);
315
316     // Switch to uppercase and lowercase.
317     $id_field->options['alter']['path_case'] = 'upper';
318     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
319       return $id_field->theme($row);
320     });
321     $this->assertSubString($output, strtoupper($path));
322     $id_field->options['alter']['path_case'] = 'lower';
323     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
324       return $id_field->theme($row);
325     });
326     $this->assertSubString($output, strtolower($path));
327
328     // Switch to ucfirst and ucwords.
329     $id_field->options['alter']['path_case'] = 'ucfirst';
330     $id_field->options['alter']['path'] = 'drupal has a great community';
331     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
332       return $id_field->theme($row);
333     });
334     $this->assertSubString($output, UrlHelper::encodePath('Drupal has a great community'));
335
336     $id_field->options['alter']['path_case'] = 'ucwords';
337     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
338       return $id_field->theme($row);
339     });
340     $this->assertSubString($output, UrlHelper::encodePath('Drupal Has A Great Community'));
341     unset($id_field->options['alter']['path_case']);
342
343     // Tests the linkclass setting and see whether it actually exists in the
344     // output.
345     $id_field->options['alter']['link_class'] = $class = $this->randomMachineName();
346     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
347       return $id_field->theme($row);
348     });
349     $elements = $this->xpathContent($output, '//a[contains(@class, :class)]', [':class' => $class]);
350     $this->assertTrue($elements);
351     // @fixme link_class, alt, rel cannot be unset, which should be fixed.
352     $id_field->options['alter']['link_class'] = '';
353
354     // Tests the alt setting.
355     $id_field->options['alter']['alt'] = $rel = $this->randomMachineName();
356     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
357       return $id_field->theme($row);
358     });
359     $elements = $this->xpathContent($output, '//a[contains(@title, :alt)]', [':alt' => $rel]);
360     $this->assertTrue($elements);
361     $id_field->options['alter']['alt'] = '';
362
363     // Tests the rel setting.
364     $id_field->options['alter']['rel'] = $rel = $this->randomMachineName();
365     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
366       return $id_field->theme($row);
367     });
368     $elements = $this->xpathContent($output, '//a[contains(@rel, :rel)]', [':rel' => $rel]);
369     $this->assertTrue($elements);
370     $id_field->options['alter']['rel'] = '';
371
372     // Tests the target setting.
373     $id_field->options['alter']['target'] = $target = $this->randomMachineName();
374     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
375       return $id_field->theme($row);
376     });
377     $elements = $this->xpathContent($output, '//a[contains(@target, :target)]', [':target' => $target]);
378     $this->assertTrue($elements);
379     unset($id_field->options['alter']['target']);
380   }
381
382   /**
383    * Tests the field/label/wrapper classes.
384    */
385   public function testFieldClasses() {
386     /** @var \Drupal\Core\Render\RendererInterface $renderer */
387     $renderer = $this->container->get('renderer');
388     $view = Views::getView('test_field_classes');
389     $view->initHandlers();
390
391     // Tests whether the default field classes are added.
392     $id_field = $view->field['id'];
393
394     $id_field->options['element_default_classes'] = FALSE;
395     // Setup some kind of label by default.
396     $id_field->options['label'] = $this->randomMachineName();
397     $output = $view->preview();
398     $output = $renderer->renderRoot($output);
399     $this->assertFalse($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'field-content']));
400     $this->assertFalse($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'field__label']));
401
402     $id_field->options['element_default_classes'] = TRUE;
403     $output = $view->preview();
404     $output = $renderer->renderRoot($output);
405     // Per default the label and the element of the field are spans.
406     $this->assertTrue($this->xpathContent($output, '//span[contains(@class, :class)]', [':class' => 'field-content']));
407     $this->assertTrue($this->xpathContent($output, '//span[contains(@class, :class)]', [':class' => 'views-label']));
408     $this->assertTrue($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'views-field']));
409
410     // Tests the element wrapper classes/element.
411     $random_class = $this->randomMachineName();
412
413     // Set some common wrapper element types and see whether they appear with and without a custom class set.
414     foreach (['h1', 'span', 'p', 'div'] as $element_type) {
415       $id_field->options['element_wrapper_type'] = $element_type;
416
417       // Set a custom wrapper element css class.
418       $id_field->options['element_wrapper_class'] = $random_class;
419       $output = $view->preview();
420       $output = $renderer->renderRoot($output);
421       $this->assertTrue($this->xpathContent($output, "//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
422
423       // Set no custom css class.
424       $id_field->options['element_wrapper_class'] = '';
425       $output = $view->preview();
426       $output = $renderer->renderRoot($output);
427       $this->assertFalse($this->xpathContent($output, "//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
428       $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]/{$element_type}"));
429     }
430
431     // Tests the label class/element.
432
433     // Set some common label element types and see whether they appear with and without a custom class set.
434     foreach (['h1', 'span', 'p', 'div'] as $element_type) {
435       $id_field->options['element_label_type'] = $element_type;
436
437       // Set a custom label element css class.
438       $id_field->options['element_label_class'] = $random_class;
439       $output = $view->preview();
440       $output = $renderer->renderRoot($output);
441       $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
442
443       // Set no custom css class.
444       $id_field->options['element_label_class'] = '';
445       $output = $view->preview();
446       $output = $renderer->renderRoot($output);
447       $this->assertFalse($this->xpathContent($output, "//li[contains(@class, views-row)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
448       $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//{$element_type}"));
449     }
450
451     // Tests the element classes/element.
452
453     // Set some common element element types and see whether they appear with and without a custom class set.
454     foreach (['h1', 'span', 'p', 'div'] as $element_type) {
455       $id_field->options['element_type'] = $element_type;
456
457       // Set a custom label element css class.
458       $id_field->options['element_class'] = $random_class;
459       $output = $view->preview();
460       $output = $renderer->renderRoot($output);
461       $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//div[contains(@class, views-field)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
462
463       // Set no custom css class.
464       $id_field->options['element_class'] = '';
465       $output = $view->preview();
466       $output = $renderer->renderRoot($output);
467       $this->assertFalse($this->xpathContent($output, "//li[contains(@class, views-row)]//div[contains(@class, views-field)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
468       $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//div[contains(@class, views-field)]//{$element_type}"));
469     }
470
471     // Tests the available html elements.
472     $element_types = $id_field->getElements();
473     $expected_elements = [
474       '',
475       0,
476       'div',
477       'span',
478       'h1',
479       'h2',
480       'h3',
481       'h4',
482       'h5',
483       'h6',
484       'p',
485       'strong',
486       'em',
487       'marquee'
488     ];
489
490     $this->assertEqual(array_keys($element_types), $expected_elements);
491   }
492
493   /**
494    * Tests trimming/read-more/ellipses.
495    */
496   public function testTextRendering() {
497     /** @var \Drupal\Core\Render\RendererInterface $renderer */
498     $renderer = \Drupal::service('renderer');
499
500     $view = Views::getView('test_field_output');
501     $view->initHandlers();
502     $name_field = $view->field['name'];
503
504     // Tests stripping of html elements.
505     $this->executeView($view);
506     $random_text = $this->randomMachineName();
507     $name_field->options['alter']['alter_text'] = TRUE;
508     $name_field->options['alter']['text'] = $html_text = '<div class="views-test">' . $random_text . '</div>';
509     $row = $view->result[0];
510
511     $name_field->options['alter']['strip_tags'] = TRUE;
512     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
513       return $name_field->advancedRender($row);
514     });
515     $this->assertSubString($output, $random_text, 'Find text without html if stripping of views field output is enabled.');
516     $this->assertNotSubString($output, $html_text, 'Find no text with the html if stripping of views field output is enabled.');
517
518     // Tests preserving of html tags.
519     $name_field->options['alter']['preserve_tags'] = '<div>';
520     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
521       return $name_field->advancedRender($row);
522     });
523     $this->assertSubString($output, $random_text, 'Find text without html if stripping of views field output is enabled but a div is allowed.');
524     $this->assertSubString($output, $html_text, 'Find text with the html if stripping of views field output is enabled but a div is allowed.');
525
526     $name_field->options['alter']['strip_tags'] = FALSE;
527     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
528       return $name_field->advancedRender($row);
529     });
530     $this->assertSubString($output, $random_text, 'Find text without html if stripping of views field output is disabled.');
531     $this->assertSubString($output, $html_text, 'Find text with the html if stripping of views field output is disabled.');
532
533     // Tests for removing whitespace and the beginning and the end.
534     $name_field->options['alter']['alter_text'] = FALSE;
535     $views_test_data_name = $row->views_test_data_name;
536     $row->views_test_data_name = '  ' . $views_test_data_name . '     ';
537     $name_field->options['alter']['trim_whitespace'] = TRUE;
538     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
539       return $name_field->advancedRender($row);
540     });
541
542     $this->assertSubString($output, $views_test_data_name, 'Make sure the trimmed text can be found if trimming is enabled.');
543     $this->assertNotSubString($output, $row->views_test_data_name, 'Make sure the untrimmed text can be found if trimming is enabled.');
544
545     $name_field->options['alter']['trim_whitespace'] = FALSE;
546     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
547       return $name_field->advancedRender($row);
548     });
549     $this->assertSubString($output, $views_test_data_name, 'Make sure the trimmed text can be found if trimming is disabled.');
550     $this->assertSubString($output, $row->views_test_data_name, 'Make sure the untrimmed text can be found  if trimming is disabled.');
551
552     // Tests for trimming to a maximum length.
553     $name_field->options['alter']['trim'] = TRUE;
554     $name_field->options['alter']['word_boundary'] = FALSE;
555
556     // Tests for simple trimming by string length.
557     $row->views_test_data_name = $this->randomMachineName(8);
558     $name_field->options['alter']['max_length'] = 5;
559     $trimmed_name = Unicode::substr($row->views_test_data_name, 0, 5);
560
561     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
562       return $name_field->advancedRender($row);
563     });
564     $this->assertSubString($output, $trimmed_name, format_string('Make sure the trimmed output (@trimmed) appears in the rendered output (@output).', ['@trimmed' => $trimmed_name, '@output' => $output]));
565     $this->assertNotSubString($output, $row->views_test_data_name, format_string("Make sure the untrimmed value (@untrimmed) shouldn't appear in the rendered output (@output).", ['@untrimmed' => $row->views_test_data_name, '@output' => $output]));
566
567     $name_field->options['alter']['max_length'] = 9;
568     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
569       return $name_field->advancedRender($row);
570     });
571     $this->assertSubString($output, $trimmed_name, format_string('Make sure the untrimmed (@untrimmed) output appears in the rendered output  (@output).', ['@trimmed' => $trimmed_name, '@output' => $output]));
572
573     // Take word_boundary into account for the tests.
574     $name_field->options['alter']['max_length'] = 5;
575     $name_field->options['alter']['word_boundary'] = TRUE;
576     $random_text_2 = $this->randomMachineName(2);
577     $random_text_4 = $this->randomMachineName(4);
578     $random_text_8 = $this->randomMachineName(8);
579     $tuples = [
580       // Create one string which doesn't fit at all into the limit.
581       [
582         'value' => $random_text_8,
583         'trimmed_value' => '',
584         'trimmed' => TRUE
585       ],
586       // Create one string with two words which doesn't fit both into the limit.
587       [
588         'value' => $random_text_8 . ' ' . $random_text_8,
589         'trimmed_value' => '',
590         'trimmed' => TRUE
591       ],
592       // Create one string which contains of two words, of which only the first
593       // fits into the limit.
594       [
595         'value' => $random_text_4 . ' ' . $random_text_8,
596         'trimmed_value' => $random_text_4,
597         'trimmed' => TRUE
598       ],
599       // Create one string which contains of two words, of which both fits into
600       // the limit.
601       [
602         'value' => $random_text_2 . ' ' . $random_text_2,
603         'trimmed_value' => $random_text_2 . ' ' . $random_text_2,
604         'trimmed' => FALSE
605       ]
606     ];
607
608     foreach ($tuples as $tuple) {
609       $row->views_test_data_name = $tuple['value'];
610       $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
611         return $name_field->advancedRender($row);
612       });
613
614       if ($tuple['trimmed']) {
615         $this->assertNotSubString($output, $tuple['value'], format_string('The untrimmed value (@untrimmed) should not appear in the trimmed output (@output).', ['@untrimmed' => $tuple['value'], '@output' => $output]));
616       }
617       if (!empty($tuple['trimmed_value'])) {
618         $this->assertSubString($output, $tuple['trimmed_value'], format_string('The trimmed value (@trimmed) should appear in the trimmed output (@output).', ['@trimmed' => $tuple['trimmed_value'], '@output' => $output]));
619       }
620     }
621
622     // Tests for displaying a readmore link when the output got trimmed.
623     $row->views_test_data_name = $this->randomMachineName(8);
624     $name_field->options['alter']['max_length'] = 5;
625     $name_field->options['alter']['more_link'] = TRUE;
626     $name_field->options['alter']['more_link_text'] = $more_text = $this->randomMachineName();
627     $name_field->options['alter']['more_link_path'] = $more_path = $this->randomMachineName();
628
629     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
630       return $name_field->advancedRender($row);
631     });
632     $this->assertSubString($output, $more_text, 'Make sure a read more text is displayed if the output got trimmed');
633     $this->assertTrue($this->xpathContent($output, '//a[contains(@href, :path)]', [':path' => $more_path]), 'Make sure the read more link points to the right destination.');
634
635     $name_field->options['alter']['more_link'] = FALSE;
636     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
637       return $name_field->advancedRender($row);
638     });
639     $this->assertNotSubString($output, $more_text, 'Make sure no read more text appears.');
640     $this->assertFalse($this->xpathContent($output, '//a[contains(@href, :path)]', [':path' => $more_path]), 'Make sure no read more link appears.');
641
642     // Check for the ellipses.
643     $row->views_test_data_name = $this->randomMachineName(8);
644     $name_field->options['alter']['max_length'] = 5;
645     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
646       return $name_field->advancedRender($row);
647     });
648     $this->assertSubString($output, '…', 'An ellipsis should appear if the output is trimmed');
649     $name_field->options['alter']['max_length'] = 10;
650     $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
651       return $name_field->advancedRender($row);
652     });
653     $this->assertNotSubString($output, '…', 'No ellipsis should appear if the output is not trimmed');
654   }
655
656 }