first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,13 @@
name: 'Statistics test views'
type: module
description: 'Provides default views for views statistics tests.'
package: Testing
# version: VERSION
dependencies:
- drupal:statistics
- drupal:views
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,250 @@
# cspell:ignore daycount totalcount
langcode: en
status: true
dependencies:
module:
- node
- user
id: test_statistics_integration
label: 'Test statistics integration'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
display:
default:
display_plugin: default
id: default
display_title: Default
position: null
display_options:
access:
type: perm
cache:
type: tag
query:
type: views_query
exposed_form:
type: basic
pager:
type: none
options:
offset: 0
style:
type: default
row:
type: fields
fields:
title:
id: title
table: node_field_data
field: title
label: ''
alter:
alter_text: false
make_link: false
absolute: false
trim: false
word_boundary: false
ellipsis: false
strip_tags: false
html: false
hide_empty: false
empty_zero: false
plugin_id: field
entity_type: node
entity_field: title
timestamp:
id: timestamp
table: node_counter
field: timestamp
relationship: none
group_type: group
admin_label: ''
label: 'Most recent view'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
date_format: html_year
custom_date_format: ''
timezone: ''
plugin_id: date
totalcount:
id: totalcount
table: node_counter
field: totalcount
relationship: none
group_type: group
admin_label: ''
label: 'Total views'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
set_precision: false
precision: 0
decimal: .
separator: ''
format_plural: false
format_plural_string: "1\x03@count"
prefix: ''
suffix: ''
plugin_id: numeric
daycount:
id: daycount
table: node_counter
field: daycount
relationship: none
group_type: group
admin_label: ''
label: 'Views today'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
set_precision: false
precision: 0
decimal: .
separator: ''
format_plural: false
format_plural_string: "1\x03@count"
prefix: ''
suffix: ''
plugin_id: numeric
filters:
status:
value: '1'
table: node_field_data
field: status
id: status
expose:
operator: ''
group: 1
plugin_id: boolean
entity_type: node
entity_field: status
sorts:
created:
id: created
table: node_field_data
field: created
order: DESC
entity_type: node
entity_field: created
page_1:
display_plugin: page
id: page_1
display_title: Page
position: null
display_options:
path: test_statistics_integration

View File

@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional;
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
/**
* Generic module test for statistics.
*
* @group statistics
* @group legacy
*/
class GenericTest extends GenericModuleTestBase {}

View File

@@ -0,0 +1,195 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional;
use Drupal\Core\Database\Database;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\Traits\Core\CronRunTrait;
// cspell:ignore accesslog daycount
/**
* Tests the statistics admin.
*
* @group statistics
* @group legacy
*/
class StatisticsAdminTest extends BrowserTestBase {
use CronRunTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node', 'statistics'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* A user that has permission to administer statistics.
*
* @var \Drupal\user\UserInterface
*/
protected $privilegedUser;
/**
* A page node for which to check content statistics.
*
* @var \Drupal\node\NodeInterface
*/
protected $testNode;
/**
* The Guzzle HTTP client.
*
* @var \GuzzleHttp\Client
*/
protected $client;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Set the max age to 0 to simplify testing.
$this->config('statistics.settings')->set('display_max_age', 0)->save();
// Create Basic page node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
}
$this->privilegedUser = $this->drupalCreateUser([
'administer statistics',
'view post access counter',
'create page content',
]);
$this->drupalLogin($this->privilegedUser);
$this->testNode = $this->drupalCreateNode(['type' => 'page', 'uid' => $this->privilegedUser->id()]);
$this->client = \Drupal::httpClient();
}
/**
* Verifies that the statistics settings page works.
*/
public function testStatisticsSettings(): void {
$config = $this->config('statistics.settings');
$this->assertEmpty($config->get('count_content_views'), 'Count content view log is disabled by default.');
// Enable counter on content view.
$edit['statistics_count_content_views'] = 1;
$this->drupalGet('admin/config/system/statistics');
$this->submitForm($edit, 'Save configuration');
$config = $this->config('statistics.settings');
$this->assertNotEmpty($config->get('count_content_views'), 'Count content view log is enabled.');
// Hit the node.
$this->drupalGet('node/' . $this->testNode->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $this->testNode->id();
$post = ['nid' => $nid];
global $base_url;
$stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
$this->client->post($stats_path, ['form_params' => $post]);
// Hit the node again (the counter is incremented after the hit, so
// "1 view" will actually be shown when the node is hit the second time).
$this->drupalGet('node/' . $this->testNode->id());
$this->client->post($stats_path, ['form_params' => $post]);
$this->assertSession()->pageTextContains('1 view');
$this->drupalGet('node/' . $this->testNode->id());
$this->client->post($stats_path, ['form_params' => $post]);
$this->assertSession()->pageTextContains('2 views');
// Increase the max age to test that nodes are no longer immediately
// updated, visit the node once more to populate the cache.
$this->config('statistics.settings')->set('display_max_age', 3600)->save();
$this->drupalGet('node/' . $this->testNode->id());
$this->assertSession()->pageTextContains('3 views');
$this->client->post($stats_path, ['form_params' => $post]);
$this->drupalGet('node/' . $this->testNode->id());
// Verify that views counter was not updated.
$this->assertSession()->pageTextContains('3 views');
}
/**
* Tests that when a node is deleted, the node counter is deleted too.
*/
public function testDeleteNode(): void {
$this->config('statistics.settings')->set('count_content_views', 1)->save();
$this->drupalGet('node/' . $this->testNode->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $this->testNode->id();
$post = ['nid' => $nid];
global $base_url;
$stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
$this->client->post($stats_path, ['form_params' => $post]);
$connection = Database::getConnection();
$result = $connection->select('node_counter', 'n')
->fields('n', ['nid'])
->condition('n.nid', $this->testNode->id())
->execute()
->fetchAssoc();
$this->assertEquals($result['nid'], $this->testNode->id(), 'Verifying that the node counter is incremented.');
$this->testNode->delete();
$result = $connection->select('node_counter', 'n')
->fields('n', ['nid'])
->condition('n.nid', $this->testNode->id())
->execute()
->fetchAssoc();
$this->assertFalse($result, 'Verifying that the node counter is deleted.');
}
/**
* Tests that cron clears day counts and expired access logs.
*/
public function testExpiredLogs(): void {
$this->config('statistics.settings')
->set('count_content_views', 1)
->save();
\Drupal::state()->set('statistics.day_timestamp', 8640000);
$this->drupalGet('node/' . $this->testNode->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $this->testNode->id();
$post = ['nid' => $nid];
global $base_url;
$stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
$this->client->post($stats_path, ['form_params' => $post]);
$this->drupalGet('node/' . $this->testNode->id());
$this->client->post($stats_path, ['form_params' => $post]);
$this->assertSession()->pageTextContains('1 view');
// statistics_cron() will subtract
// statistics.settings:accesslog.max_lifetime config from
// \Drupal::time()->getRequestTime() in the delete query, so wait two secs here to make
// sure the access log will be flushed for the node just hit.
sleep(2);
$this->cronRun();
// Verify that no hit URL is found.
$this->drupalGet('admin/reports/pages');
$this->assertSession()->pageTextNotContains('node/' . $this->testNode->id());
$result = Database::getConnection()->select('node_counter', 'nc')
->fields('nc', ['daycount'])
->condition('nid', $this->testNode->id(), '=')
->execute()
->fetchField();
$this->assertEmpty($result, 'Daycount is zero.');
}
}

View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\node\Entity\Node;
/**
* Tests if statistics.js is loaded when content is not printed.
*
* @group statistics
* @group legacy
*/
class StatisticsAttachedTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node', 'statistics'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalCreateContentType(['type' => 'page']);
// Install "statistics_test_attached" and set it as the default theme.
$theme = 'statistics_test_attached';
\Drupal::service('theme_installer')->install([$theme]);
$this->config('system.theme')
->set('default', $theme)
->save();
// Installing a theme will cause the kernel terminate event to rebuild the
// router. Simulate that here.
\Drupal::service('router.builder')->rebuildIfNeeded();
}
/**
* Tests if statistics.js is loaded when content is not printed.
*/
public function testAttached(): void {
$node = Node::create([
'type' => 'page',
'title' => 'Page node',
'body' => 'body text',
]);
$node->save();
$this->drupalGet('node/' . $node->id());
$this->assertSession()->responseContains('core/modules/statistics/statistics.js');
}
}

View File

@@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\node\Entity\Node;
/**
* Tests request logging for cached and uncached pages.
*
* We subclass BrowserTestBase rather than StatisticsTestBase, because we
* want to test requests from an anonymous user.
*
* @group statistics
* @group legacy
*/
class StatisticsLoggingTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node', 'statistics', 'block', 'locale'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* User with permissions to create and edit pages.
*
* @var \Drupal\user\UserInterface
*/
protected $authUser;
/**
* Associative array representing a hypothetical Drupal language.
*
* @var array
*/
protected $language;
/**
* The Guzzle HTTP client.
*
* @var \GuzzleHttp\Client
*/
protected $client;
/**
* A test node.
*
* @var \Drupal\node\Entity\Node
*/
protected Node $node;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create Basic page node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
}
$this->authUser = $this->drupalCreateUser([
// For node creation.
'access content',
'create page content',
'edit own page content',
// For language negotiation administration.
'administer languages',
'access administration pages',
]);
// Ensure we have a node page to access.
$this->node = $this->drupalCreateNode(['title' => $this->randomMachineName(255), 'uid' => $this->authUser->id()]);
// Add a custom language and enable path-based language negotiation.
$this->drupalLogin($this->authUser);
$this->language = [
'predefined_langcode' => 'custom',
'langcode' => 'xx',
'label' => $this->randomMachineName(16),
'direction' => 'ltr',
];
$this->drupalGet('admin/config/regional/language/add');
$this->submitForm($this->language, 'Add custom language');
$this->drupalGet('admin/config/regional/language/detection');
$this->submitForm(['language_interface[enabled][language-url]' => 1], 'Save settings');
$this->drupalLogout();
// Enable access logging.
$this->config('statistics.settings')
->set('count_content_views', 1)
->save();
$this->client = \Drupal::httpClient();
}
/**
* Verifies node hit counter logging and script placement.
*/
public function testLogging(): void {
$path = 'node/' . $this->node->id();
$module_path = $this->getModulePath('statistics');
$stats_path = base_path() . $module_path . '/statistics.php';
$lib_path = base_path() . $module_path . '/statistics.js';
$expected_library = '/<script src=".*?' . preg_quote($lib_path, '/.') . '.*?">/is';
// Verify that logging scripts are not found on a non-node page.
$this->drupalGet('node');
$settings = $this->getDrupalSettings();
// Statistics library JS should not be present.
$this->assertSession()->responseNotMatches($expected_library);
$this->assertFalse(isset($settings['statistics']), 'Statistics settings not found on node page.');
// Verify that logging scripts are not found on a non-existent node page.
$this->drupalGet('node/9999');
$settings = $this->getDrupalSettings();
// Statistics library JS should not be present.
$this->assertSession()->responseNotMatches($expected_library);
$this->assertFalse(isset($settings['statistics']), 'Statistics settings not found on node page.');
// Verify that logging scripts are found on a valid node page.
$this->drupalGet($path);
$settings = $this->getDrupalSettings();
$this->assertSession()->responseMatches($expected_library);
$this->assertSame($settings['statistics']['data']['nid'], $this->node->id(), 'Found statistics settings on node page.');
// Verify the same when loading the site in a non-default language.
$this->drupalGet($this->language['langcode'] . '/' . $path);
$settings = $this->getDrupalSettings();
$this->assertSession()->responseMatches($expected_library);
$this->assertSame($settings['statistics']['data']['nid'], $this->node->id(), 'Found statistics settings on valid node page in a non-default language.');
// Manually call statistics.php to simulate ajax data collection behavior.
global $base_root;
$post = ['nid' => $this->node->id()];
$this->client->post($base_root . $stats_path, ['form_params' => $post]);
$node_counter = \Drupal::service('statistics.storage.node')->fetchView($this->node->id());
$this->assertSame(1, $node_counter->getTotalCount());
// Try fetching statistics for an invalid node ID and verify it returns
// FALSE.
$node_id = 1000000;
$node = Node::load($node_id);
$this->assertNull($node);
// This is a test specifically for the deprecated statistics_get() function
// and so should remain unconverted until that function is removed.
$result = \Drupal::service('statistics.storage.node')->fetchView($node_id);
$this->assertFalse($result);
}
}

View File

@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Link;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
/**
* Tests display of statistics report blocks.
*
* @group statistics
* @group legacy
*/
class StatisticsReportsTest extends StatisticsTestBase {
use AssertPageCacheContextsAndTagsTrait;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests the "popular content" block.
*/
public function testPopularContentBlock(): void {
// Clear the block cache to load the Statistics module's block definitions.
$this->container->get('plugin.manager.block')->clearCachedDefinitions();
// Visit a node to have something show up in the block.
$node = $this->drupalCreateNode(['type' => 'page', 'uid' => $this->blockingUser->id()]);
$this->drupalGet('node/' . $node->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $node->id();
$post = http_build_query(['nid' => $nid]);
$headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
global $base_url;
$stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
$client = \Drupal::httpClient();
$client->post($stats_path, ['headers' => $headers, 'body' => $post]);
// Configure and save the block.
$block = $this->drupalPlaceBlock('statistics_popular_block', [
'label' => 'Popular content',
'top_day_num' => 3,
'top_all_num' => 3,
'top_last_num' => 3,
]);
// Get some page and check if the block is displayed.
$this->drupalGet('user');
$this->assertSession()->pageTextContains('Popular content');
$this->assertSession()->pageTextContains("Today's");
$this->assertSession()->pageTextContains('All time');
$this->assertSession()->pageTextContains('Last viewed');
$tags = Cache::mergeTags($node->getCacheTags(), $block->getCacheTags());
$tags = Cache::mergeTags($tags, $this->blockingUser->getCacheTags());
$tags = Cache::mergeTags($tags, ['block_view', 'config:block_list', 'node_list', 'rendered', 'user_view']);
$this->assertCacheTags($tags);
$contexts = Cache::mergeContexts($node->getCacheContexts(), $block->getCacheContexts());
$contexts = Cache::mergeContexts($contexts, ['url.query_args:_wrapper_format', 'url.site']);
$this->assertCacheContexts($contexts);
// Check if the node link is displayed.
$this->assertSession()->responseContains(Link::fromTextAndUrl($node->label(), $node->toUrl('canonical'))->toString());
}
}

View File

@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Defines a base class for testing the Statistics module.
*/
abstract class StatisticsTestBase extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node', 'block', 'ban', 'statistics'];
/**
* User with permissions to ban IPs.
*
* @var \Drupal\user\UserInterface
*/
protected $blockingUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create Basic page node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
}
// Create user.
$this->blockingUser = $this->drupalCreateUser([
'access administration pages',
'access site reports',
'ban IP addresses',
'administer blocks',
'administer statistics',
'administer users',
]);
$this->drupalLogin($this->blockingUser);
// Enable logging.
$this->config('statistics.settings')
->set('count_content_views', 1)
->save();
}
}

View File

@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional;
/**
* Tests statistics token replacement.
*
* @group statistics
* @group legacy
*/
class StatisticsTokenReplaceTest extends StatisticsTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Creates a node, then tests the statistics tokens generated from it.
*/
public function testStatisticsTokenReplacement(): void {
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
// Create user and node.
$user = $this->drupalCreateUser(['create page content']);
$this->drupalLogin($user);
$node = $this->drupalCreateNode(['type' => 'page', 'uid' => $user->id()]);
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = $this->container->get('date.formatter');
$request_time = \Drupal::time()->getRequestTime();
// Generate and test tokens.
$tests = [];
$tests['[node:total-count]'] = 0;
$tests['[node:day-count]'] = 0;
$tests['[node:last-view]'] = 'never';
$tests['[node:last-view:short]'] = $date_formatter->format($request_time, 'short');
foreach ($tests as $input => $expected) {
$output = \Drupal::token()->replace($input, ['node' => $node], ['langcode' => $language_interface->getId()]);
$this->assertEquals($expected, $output, "Statistics token $input replaced.");
}
// Hit the node.
$this->drupalGet('node/' . $node->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $node->id();
$post = http_build_query(['nid' => $nid]);
$headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
global $base_url;
$stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
$client = \Drupal::httpClient();
$client->post($stats_path, ['headers' => $headers, 'body' => $post]);
/** @var \Drupal\statistics\StatisticsViewsResult $statistics */
$statistics = \Drupal::service('statistics.storage.node')->fetchView($node->id());
// Generate and test tokens.
$tests = [];
$tests['[node:total-count]'] = 1;
$tests['[node:day-count]'] = 1;
$tests['[node:last-view]'] = $date_formatter->format($statistics->getTimestamp());
$tests['[node:last-view:short]'] = $date_formatter->format($statistics->getTimestamp(), 'short');
// Test to make sure that we generated something for each token.
$this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = \Drupal::token()->replace($input, ['node' => $node], ['langcode' => $language_interface->getId()]);
$this->assertEquals($expected, $output, "Statistics token $input replaced.");
}
}
}

View File

@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional\Views;
use Drupal\Tests\views\Functional\ViewTestBase;
use Drupal\user\Entity\User;
/**
* Tests basic integration of views data from the statistics module.
*
* @group statistics
* @group legacy
* @see
*/
class IntegrationTest extends ViewTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['statistics', 'statistics_test_views', 'node'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Stores the user object that accesses the page.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* A test user with node viewing access only.
*
* @var \Drupal\user\Entity\User
*/
protected User $deniedUser;
/**
* Stores the node object which is used by the test.
*
* @var \Drupal\node\Entity\Node
*/
protected $node;
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_statistics_integration'];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE, $modules = ['statistics_test_views']): void {
parent::setUp($import_test_views, $modules);
// Create a new user for viewing nodes and statistics.
$this->webUser = $this->drupalCreateUser([
'access content',
'view post access counter',
]);
// Create a new user for viewing nodes only.
$this->deniedUser = $this->drupalCreateUser(['access content']);
$this->drupalCreateContentType(['type' => 'page']);
$this->node = $this->drupalCreateNode(['type' => 'page']);
// Enable counting of content views.
$this->config('statistics.settings')
->set('count_content_views', 1)
->save();
}
/**
* Tests the integration of the {node_counter} table in views.
*/
public function testNodeCounterIntegration(): void {
$this->drupalLogin($this->webUser);
$this->drupalGet('node/' . $this->node->id());
// Manually calling statistics.php, simulating ajax behavior.
// @see \Drupal\statistics\Tests\StatisticsLoggingTest::testLogging().
global $base_url;
$stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
$client = $this->getHttpClient();
$client->post($stats_path, ['form_params' => ['nid' => $this->node->id()]]);
$this->drupalGet('test_statistics_integration');
/** @var \Drupal\statistics\StatisticsViewsResult $statistics */
$statistics = \Drupal::service('statistics.storage.node')->fetchView($this->node->id());
$this->assertSession()->pageTextContains('Total views: 1');
$this->assertSession()->pageTextContains('Views today: 1');
$this->assertSession()->pageTextContains('Most recent view: ' . date('Y', $statistics->getTimestamp()));
$this->drupalLogout();
$this->drupalLogin($this->deniedUser);
$this->drupalGet('test_statistics_integration');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextNotContains('Total views:');
$this->assertSession()->pageTextNotContains('Views today:');
$this->assertSession()->pageTextNotContains('Most recent view:');
}
}

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional\migrate_drupal\d6;
use Drupal\Tests\migrate_drupal_ui\Functional\NoMultilingualReviewPageTestBase;
/**
* Tests migrate upgrade review page.
*
* @group statistics
* @group legacy
*/
class NoMultilingualReviewPageTest extends NoMultilingualReviewPageTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'statistics',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->loadFixture($this->getModulePath('statistics') . '/tests/fixtures/drupal6.php');
}
/**
* {@inheritdoc}
*/
protected function getSourceBasePath() {
return __DIR__;
}
/**
* Tests that Statistics is displayed in the will be upgraded list.
*/
public function testMigrateUpgradeReviewPage(): void {
$this->prepare();
// Start the upgrade process.
$this->submitCredentialForm();
$session = $this->assertSession();
$this->submitForm([], 'I acknowledge I may lose data. Continue anyway.');
$session->statusCodeEquals(200);
// Confirm that Statistics will be upgraded.
$session->elementExists('xpath', "//td[contains(@class, 'checked') and text() = 'Statistics']");
$session->elementNotExists('xpath', "//td[contains(@class, 'error') and text() = 'Statistics']");
}
/**
* {@inheritdoc}
*/
protected function getAvailablePaths() {
return [];
}
/**
* {@inheritdoc}
*/
protected function getIncompletePaths() {
return [];
}
/**
* {@inheritdoc}
*/
protected function getMissingPaths() {
return [];
}
}

View File

@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional\migrate_drupal\d6;
use Drupal\Tests\migrate_drupal_ui\Functional\MigrateUpgradeExecuteTestBase;
/**
* Tests Drupal 6 upgrade using the migrate UI.
*
* The test method is provided by the MigrateUpgradeTestBase class.
*
* @group statistics
* @group legacy
*/
class UpgradeTest extends MigrateUpgradeExecuteTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'config_translation',
'content_translation',
'language',
'migrate_drupal_ui',
'statistics',
];
/**
* The entity storage for node.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeStorage;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->loadFixture($this->getModulePath('statistics') . '/tests/fixtures/drupal6.php');
}
/**
* {@inheritdoc}
*/
protected function getSourceBasePath() {
return __DIR__ . '/files';
}
/**
* {@inheritdoc}
*/
protected function getEntityCounts() {
return [
'action' => 24,
'base_field_override' => 18,
'block' => 33,
'block_content' => 1,
'block_content_type' => 1,
'comment' => 2,
'comment_type' => 7,
'configurable_language' => 5,
'contact_form' => 2,
'contact_message' => 0,
'date_format' => 12,
'editor' => 2,
'entity_form_display' => 16,
'entity_form_mode' => 1,
'entity_view_display' => 25,
'entity_view_mode' => 10,
'field_config' => 25,
'field_storage_config' => 14,
'file' => 1,
'filter_format' => 7,
'image_style' => 4,
'language_content_settings' => 9,
'menu' => 8,
'menu_link_content' => 1,
'node' => 11,
'node_type' => 7,
'path_alias' => 0,
'search_page' => 3,
'shortcut' => 2,
'shortcut_set' => 1,
'taxonomy_term' => 1,
'taxonomy_vocabulary' => 1,
'user' => 3,
'user_role' => 4,
'view' => 14,
];
}
/**
* {@inheritdoc}
*/
protected function getEntityCountsIncremental() {
return [];
}
/**
* {@inheritdoc}
*/
protected function getAvailablePaths() {
return [
'Block',
'Content translation',
'Content',
'Comment',
'Filter',
'Internationalization',
'Locale',
'Menu',
'Node',
'Path',
'Statistics',
'System',
'User',
'Variable admin',
];
}
/**
* {@inheritdoc}
*/
protected function getMissingPaths() {
return [];
}
/**
* Executes all steps of migrations upgrade.
*/
public function testUpgrade(): void {
// Start the upgrade process.
$this->submitCredentialForm();
$session = $this->assertSession();
$this->submitForm([], 'I acknowledge I may lose data. Continue anyway.');
$session->statusCodeEquals(200);
// Test the review form.
$this->assertReviewForm();
$this->submitForm([], 'Perform upgrade');
$this->assertUpgrade($this->getEntityCounts());
}
}

View File

@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional\migrate_drupal\d7;
use Drupal\Tests\migrate_drupal_ui\Functional\NoMultilingualReviewPageTestBase;
/**
* Tests Drupal 7 upgrade without translations.
*
* The test method is provided by the MigrateUpgradeTestBase class.
*
* @group statistics
* @group legacy
*/
class NoMultilingualReviewPageTest extends NoMultilingualReviewPageTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'statistics',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->loadFixture($this->getModulePath('statistics') . '/tests/fixtures/drupal7.php');
}
/**
* Tests that Statistics is displayed in the will be upgraded list.
*/
public function testMigrateUpgradeReviewPage(): void {
$this->prepare();
// Start the upgrade process.
$this->submitCredentialForm();
$session = $this->assertSession();
$this->submitForm([], 'I acknowledge I may lose data. Continue anyway.');
$session->statusCodeEquals(200);
// Confirm that Statistics will be upgraded.
$session->elementExists('xpath', "//td[contains(@class, 'checked') and text() = 'Statistics']");
$session->elementNotExists('xpath', "//td[contains(@class, 'error') and text() = 'Statistics']");
}
/**
* {@inheritdoc}
*/
protected function getSourceBasePath() {
return __DIR__ . '/files';
}
/**
* {@inheritdoc}
*/
protected function getAvailablePaths() {
return [];
}
/**
* {@inheritdoc}
*/
protected function getIncompletePaths() {
return [];
}
/**
* {@inheritdoc}
*/
protected function getMissingPaths() {
return [];
}
}

View File

@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional\migrate_drupal\d7;
use Drupal\Tests\migrate_drupal_ui\Functional\MigrateUpgradeExecuteTestBase;
/**
* Tests Drupal 7 upgrade using the migrate UI.
*
* The test method is provided by the MigrateUpgradeTestBase class.
*
* @group statistics
* @group legacy
*/
class UpgradeTest extends MigrateUpgradeExecuteTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'config_translation',
'content_translation',
'datetime_range',
'language',
'migrate_drupal_ui',
'statistics',
'telephone',
];
/**
* The entity storage for node.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeStorage;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// @todo remove when https://www.drupal.org/project/drupal/issues/3266491 is
// fixed.
// Delete the existing content made to test the ID Conflict form. Migrations
// are to be done on a site without content. The test of the ID Conflict
// form is being moved to its own issue which will remove the deletion
// of the created nodes.
// See https://www.drupal.org/project/drupal/issues/3087061.
$this->nodeStorage = $this->container->get('entity_type.manager')
->getStorage('node');
$this->nodeStorage->delete($this->nodeStorage->loadMultiple());
$this->loadFixture($this->getModulePath('statistics') . '/tests/fixtures/drupal7.php');
}
/**
* {@inheritdoc}
*/
protected function getSourceBasePath() {
return __DIR__ . '/files';
}
/**
* {@inheritdoc}
*/
protected function getEntityCounts() {
return [
'action' => 24,
'base_field_override' => 2,
'block' => 26,
'block_content' => 1,
'block_content_type' => 1,
'comment' => 4,
'comment_type' => 9,
'configurable_language' => 5,
'contact_form' => 2,
'contact_message' => 0,
'date_format' => 12,
'editor' => 2,
'entity_form_display' => 19,
'entity_form_mode' => 1,
'entity_view_display' => 28,
'entity_view_mode' => 11,
'field_config' => 33,
'field_storage_config' => 19,
'file' => 1,
'filter_format' => 7,
'image_style' => 7,
'language_content_settings' => 16,
'menu' => 5,
'menu_link_content' => 2,
'node' => 7,
'node_type' => 8,
'path_alias' => 0,
'search_page' => 3,
'shortcut' => 2,
'shortcut_set' => 1,
'taxonomy_term' => 15,
'taxonomy_vocabulary' => 2,
'user' => 3,
'user_role' => 4,
'view' => 14,
];
}
/**
* {@inheritdoc}
*/
protected function getEntityCountsIncremental() {
return [];
}
/**
* {@inheritdoc}
*/
protected function getAvailablePaths() {
return [
'Block',
'Blog',
'Comment',
'Contact',
'Content translation',
'Entity Translation',
'Field',
'Field SQL storage',
'Field UI',
'File',
'Filter',
'Image',
'Internationalization',
'List',
'Locale',
'Menu',
'Node',
'Number',
'Options',
'Path',
'Statistics',
'System',
'Taxonomy',
'Text',
'User',
];
}
/**
* {@inheritdoc}
*/
protected function getMissingPaths() {
return [
'Forum',
'Variable',
];
}
/**
* Executes all steps of migrations upgrade.
*/
public function testUpgrade(): void {
// Start the upgrade process.
$this->submitCredentialForm();
$session = $this->assertSession();
$this->submitForm([], 'I acknowledge I may lose data. Continue anyway.');
$session->statusCodeEquals(200);
// Test the review form.
$this->assertReviewForm();
$this->submitForm([], 'Perform upgrade');
$this->assertUpgrade($this->getEntityCounts());
}
}

View File

@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Functional\search;
use Drupal\Core\Database\Database;
use Drupal\search\Entity\SearchPage;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\Traits\Core\CronRunTrait;
// cspell:ignore daycount totalcount
/**
* Indexes content and tests ranking factors.
*
* @group statistics
* @group legacy
*/
class SearchRankingTest extends BrowserTestBase {
use CronRunTrait;
/**
* The node search page.
*
* @var \Drupal\search\SearchPageInterface
*/
protected $nodeSearch;
/**
* {@inheritdoc}
*/
protected static $modules = ['node', 'search', 'statistics'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
// Create a plugin instance.
$this->nodeSearch = SearchPage::load('node_search');
// Log in with sufficient privileges.
$this->drupalLogin($this->drupalCreateUser([
'create page content',
'administer search',
]));
}
/**
* Tests statistics ranking on search pages.
*/
public function testRankings(): void {
// Create nodes for testing.
$nodes = [];
$settings = [
'type' => 'page',
'title' => 'Drupal rocks',
'body' => [['value' => "Drupal's search rocks"]],
// Node is one day old.
'created' => \Drupal::time()->getRequestTime() - 24 * 3600,
'sticky' => 0,
'promote' => 0,
];
foreach ([0, 1] as $num) {
$nodes['views'][$num] = $this->drupalCreateNode($settings);
}
// Enable counting of statistics.
$this->config('statistics.settings')->set('count_content_views', 1)->save();
// Simulating content views is kind of difficult in the test. So instead go
// ahead and manually update the counter for this node.
$nid = $nodes['views'][1]->id();
Database::getConnection()->insert('node_counter')
->fields([
'totalcount' => 5,
'daycount' => 5,
'timestamp' => \Drupal::time()->getRequestTime(),
'nid' => $nid,
])
->execute();
// Run cron to update the search index and statistics totals.
$this->cronRun();
// Test that the settings form displays the content ranking section.
$this->drupalGet('admin/config/search/pages/manage/node_search');
$this->assertSession()->pageTextContains('Content ranking');
// Check that views ranking is visible and set to 0.
$this->assertSession()->optionExists('edit-rankings-views-value', '0');
// Test each of the possible rankings.
$edit = [];
// Enable views ranking.
$edit['rankings[views][value]'] = 10;
$this->drupalGet('admin/config/search/pages/manage/node_search');
$this->submitForm($edit, 'Save search page');
$this->drupalGet('admin/config/search/pages/manage/node_search');
$this->assertSession()->optionExists('edit-rankings-views-value', '10');
// Reload the plugin to get the up-to-date values.
$this->nodeSearch = SearchPage::load('node_search');
// Do the search and assert the results.
$this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
$set = $this->nodeSearch->getPlugin()->execute();
$this->assertEquals($nodes['views'][1]->id(), $set[0]['node']->id());
}
}

View File

@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\FunctionalJavascript;
use Drupal\Core\Session\AccountInterface;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\user\Entity\Role;
/**
* Tests that statistics works.
*
* @group statistics
* @group legacy
*/
class StatisticsLoggingTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['node', 'statistics', 'language'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Node for tests.
*
* @var \Drupal\node\Entity\Node
*/
protected $node;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->config('statistics.settings')
->set('count_content_views', 1)
->save();
Role::load(AccountInterface::ANONYMOUS_ROLE)
->grantPermission('view post access counter')
->save();
// Add another language to enable multilingual path processor.
ConfigurableLanguage::create(['id' => 'xx', 'label' => 'Test language'])->save();
$this->config('language.negotiation')->set('url.prefixes.en', 'en')->save();
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
$this->node = $this->drupalCreateNode();
}
/**
* Tests that statistics works with different addressing variants.
*/
public function testLoggingPage(): void {
// At the first request, the page does not contain statistics counter.
$this->assertNull($this->getStatisticsCounter('node/1'));
$this->assertSame(1, $this->getStatisticsCounter('node/1'));
$this->assertSame(2, $this->getStatisticsCounter('en/node/1'));
$this->assertSame(3, $this->getStatisticsCounter('en/node/1'));
$this->assertSame(4, $this->getStatisticsCounter('index.php/node/1'));
$this->assertSame(5, $this->getStatisticsCounter('index.php/node/1'));
$this->assertSame(6, $this->getStatisticsCounter('index.php/en/node/1'));
$this->assertSame(7, $this->getStatisticsCounter('index.php/en/node/1'));
}
/**
* Gets counter of views by path.
*
* @param string $path
* A path to node.
*
* @return int|null
* A counter of views. Returns NULL if the page does not contain statistics.
*/
protected function getStatisticsCounter($path) {
$this->drupalGet($path);
// Wait while statistics module send ajax request.
$this->assertSession()->assertWaitOnAjaxRequest();
// Resaving the node to call the hook_node_links_alter(), which is used to
// update information on the page. See statistics_node_links_alter().
$this->node->save();
$field_counter = $this->getSession()->getPage()->find('css', '.links li');
return $field_counter ? (int) explode(' ', $field_counter->getText())[0] : NULL;
}
}

View File

@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Kernel\Migrate\d6;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Tests the migration of node counter data to Drupal 8.
*
* @group statistics
* @group legacy
*/
class MigrateNodeCounterTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'content_translation',
'language',
'menu_ui',
'node',
'statistics',
'text',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('node');
$this->installConfig('node');
$this->installSchema('node', ['node_access']);
$this->installSchema('statistics', ['node_counter']);
$this->executeMigrations([
'language',
'd6_filter_format',
'd6_user_role',
'd6_node_settings',
'd6_user',
'd6_node_type',
'd6_language_content_settings',
'd6_node',
'd6_node_translation',
'statistics_node_counter',
]);
}
/**
* Gets the path to the fixture file.
*/
protected function getFixtureFilePath() {
return __DIR__ . '/../../../../fixtures/drupal6.php';
}
/**
* Tests migration of node counter.
*/
public function testStatisticsSettings(): void {
$this->assertNodeCounter(1, 2, 0, 1421727536);
$this->assertNodeCounter(2, 1, 0, 1471428059);
$this->assertNodeCounter(3, 1, 0, 1471428153);
$this->assertNodeCounter(4, 1, 1, 1478755275);
$this->assertNodeCounter(5, 1, 1, 1478755314);
$this->assertNodeCounter(10, 5, 1, 1521137459);
$this->assertNodeCounter(12, 3, 0, 1521137469);
// Tests that translated node counts include all translation counts.
$this->executeMigration('statistics_node_translation_counter');
$this->assertNodeCounter(10, 8, 2, 1521137463);
$this->assertNodeCounter(12, 5, 1, 1521137470);
}
/**
* Asserts various aspects of a node counter.
*
* @param int $nid
* The node ID.
* @param int $total_count
* The expected total count.
* @param int $day_count
* The expected day count.
* @param int $timestamp
* The expected timestamp.
*
* @internal
*/
protected function assertNodeCounter(int $nid, int $total_count, int $day_count, int $timestamp): void {
/** @var \Drupal\statistics\StatisticsViewsResult $statistics */
$statistics = $this->container->get('statistics.storage.node')->fetchView($nid);
$this->assertSame($total_count, $statistics->getTotalCount());
$this->assertSame($day_count, $statistics->getDayCount());
$this->assertSame($timestamp, $statistics->getTimestamp());
}
}

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Kernel\Migrate\d6;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Upgrade variables to statistics.settings.yml.
*
* @group statistics
* @group legacy
*/
class MigrateStatisticsConfigsTest extends MigrateDrupal6TestBase {
use SchemaCheckTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['statistics'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->executeMigration('statistics_settings');
}
/**
* Gets the path to the fixture file.
*/
protected function getFixtureFilePath() {
return __DIR__ . '/../../../../fixtures/drupal6.php';
}
/**
* Tests migration of statistics variables to statistics.settings.yml.
*/
public function testStatisticsSettings(): void {
$config = $this->config('statistics.settings');
$this->assertSame(1, $config->get('count_content_views'));
$this->assertConfigSchema(\Drupal::service('config.typed'), 'statistics.settings', $config->get());
}
}

View File

@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Kernel\Migrate\d7;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests the migration of node counter data to Drupal 8.
*
* @group statistics
* @group legacy
*/
class MigrateNodeCounterTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'content_translation',
'language',
'menu_ui',
'node',
'statistics',
'text',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installSchema('node', ['node_access']);
$this->installSchema('statistics', ['node_counter']);
$this->migrateUsers(FALSE);
$this->migrateContentTypes();
$this->executeMigrations([
'language',
'd7_language_content_settings',
'd7_node',
'd7_node_translation',
'statistics_node_counter',
]);
}
/**
* Gets the path to the fixture file.
*/
protected function getFixtureFilePath() {
return __DIR__ . '/../../../../fixtures/drupal7.php';
}
/**
* Tests migration of node counter.
*/
public function testStatisticsSettings(): void {
$this->assertNodeCounter(1, 2, 0, 1421727536);
$this->assertNodeCounter(2, 1, 0, 1471428059);
$this->assertNodeCounter(4, 1, 0, 1478755275);
// Tests that translated node counts include all translation counts.
$this->executeMigration('statistics_node_translation_counter');
$this->assertNodeCounter(2, 2, 0, 1471428153);
$this->assertNodeCounter(4, 2, 0, 1478755314);
}
/**
* Asserts various aspects of a node counter.
*
* @param int $nid
* The node ID.
* @param int $total_count
* The expected total count.
* @param int $day_count
* The expected day count.
* @param int $timestamp
* The expected timestamp.
*
* @internal
*/
protected function assertNodeCounter(int $nid, int $total_count, int $day_count, int $timestamp): void {
/** @var \Drupal\statistics\StatisticsViewsResult $statistics */
$statistics = $this->container->get('statistics.storage.node')->fetchView($nid);
$this->assertSame($total_count, $statistics->getTotalCount());
$this->assertSame($day_count, $statistics->getDayCount());
$this->assertSame($timestamp, $statistics->getTimestamp());
}
}

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Kernel\Migrate\d7;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Upgrade variables to statistics.settings.yml.
*
* @group statistics
* @group legacy
*/
class MigrateStatisticsConfigsTest extends MigrateDrupal7TestBase {
use SchemaCheckTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['statistics'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->executeMigration('statistics_settings');
}
/**
* Gets the path to the fixture file.
*/
protected function getFixtureFilePath() {
return __DIR__ . '/../../../../fixtures/drupal7.php';
}
/**
* Tests migration of statistics variables to statistics.settings.yml.
*/
public function testStatisticsSettings(): void {
$config = $this->config('statistics.settings');
$this->assertSame(1, $config->get('count_content_views'));
$this->assertConfigSchema(\Drupal::service('config.typed'), 'statistics.settings', $config->get());
}
}

View File

@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Kernel\Plugin\migrate\source;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
// cspell:ignore daycount totalcount
/**
* Tests the node_counter source plugin.
*
* @covers \Drupal\statistics\Plugin\migrate\source\NodeCounter
*
* @group statistics
* @group legacy
*/
class NodeCounterTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['migrate_drupal', 'statistics'];
/**
* {@inheritdoc}
*/
public static function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['node_counter'] = [
[
'nid' => 1,
'totalcount' => 2,
'daycount' => 0,
'timestamp' => 1421727536,
],
[
'nid' => 2,
'totalcount' => 1,
'daycount' => 0,
'timestamp' => 1471428059,
],
[
'nid' => 3,
'totalcount' => 1,
'daycount' => 0,
'timestamp' => 1471428153,
],
[
'nid' => 4,
'totalcount' => 1,
'daycount' => 1,
'timestamp' => 1478755275,
],
[
'nid' => 5,
'totalcount' => 1,
'daycount' => 1,
'timestamp' => 1478755314,
],
];
// The expected results.
$tests[0]['expected_data'] = $tests[0]['source_data']['node_counter'];
return $tests;
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\statistics\Unit;
use Drupal\statistics\StatisticsViewsResult;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\statistics\StatisticsViewsResult
* @group statistics
* @group legacy
*/
class StatisticsViewsResultTest extends UnitTestCase {
/**
* Tests migration of node counter.
*
* @covers ::__construct
*
* @dataProvider providerTestStatisticsCount
*/
public function testStatisticsCount($total_count, $day_count, $timestamp): void {
$statistics = new StatisticsViewsResult($total_count, $day_count, $timestamp);
$this->assertSame((int) $total_count, $statistics->getTotalCount());
$this->assertSame((int) $day_count, $statistics->getDayCount());
$this->assertSame((int) $timestamp, $statistics->getTimestamp());
}
public static function providerTestStatisticsCount() {
return [
[2, 0, 1421727536],
[1, 0, 1471428059],
[1, 1, 1478755275],
['1', '1', '1478755275'],
];
}
}

View File

@@ -0,0 +1,24 @@
<article{{ attributes }}>
{{ title_prefix }}
{% if not page %}
<h2{{ title_attributes }}>
<a href="{{ url }}" rel="bookmark">{{ label }}</a>
</h2>
{% endif %}
{{ title_suffix }}
{% if display_submitted %}
<footer>
{{ author_picture }}
<div{{ author_attributes }}>
{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
{{ metadata }}
</div>
</footer>
{% endif %}
<div{{ content_attributes }}>
{{ content.body }}
</div>
</article>

View File

@@ -0,0 +1,10 @@
name: 'Statistics test attached theme'
type: theme
base theme: stable9
description: 'Theme for testing attached library'
# version: VERSION
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222