Move all files to 2017/

This commit is contained in:
Oliver Davies 2025-09-29 22:25:17 +01:00
parent ac7370f67f
commit 2875863330
15717 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,9 @@
name: 'Statistics test views'
type: module
description: 'Provides default views for views statistics tests.'
package: Testing
version: VERSION
core: 8.x
dependencies:
- drupal:statistics
- drupal:views

View file

@ -0,0 +1,250 @@
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
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
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,173 @@
<?php
namespace Drupal\Tests\statistics\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\Traits\Core\CronRunTrait;
/**
* Tests the statistics admin.
*
* @group statistics
*/
class StatisticsAdminTest extends BrowserTestBase {
use CronRunTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'statistics'];
/**
* 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;
protected function setUp() {
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() {
$config = $this->config('statistics.settings');
$this->assertFalse($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->drupalPostForm('admin/config/system/statistics', $edit, t('Save configuration'));
$config = $this->config('statistics.settings');
$this->assertTrue($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 . '/' . drupal_get_path('module', '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->assertText('1 view', 'Node is viewed once.');
$this->drupalGet('node/' . $this->testNode->id());
$this->client->post($stats_path, ['form_params' => $post]);
$this->assertText('2 views', 'Node is viewed 2 times.');
// 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->assertText('3 views', 'Node is viewed 3 times.');
$this->client->post($stats_path, ['form_params' => $post]);
$this->drupalGet('node/' . $this->testNode->id());
$this->assertText('3 views', 'Views counter was not updated.');
}
/**
* Tests that when a node is deleted, the node counter is deleted too.
*/
public function testDeleteNode() {
$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 . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$this->client->post($stats_path, ['form_params' => $post]);
$result = db_select('node_counter', 'n')
->fields('n', ['nid'])
->condition('n.nid', $this->testNode->id())
->execute()
->fetchAssoc();
$this->assertEqual($result['nid'], $this->testNode->id(), 'Verifying that the node counter is incremented.');
$this->testNode->delete();
$result = db_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() {
$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 . '/' . drupal_get_path('module', '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->assertText('1 view', 'Node is viewed once.');
// statistics_cron() will subtract
// statistics.settings:accesslog.max_lifetime config from REQUEST_TIME 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();
$this->drupalGet('admin/reports/pages');
$this->assertNoText('node/' . $this->testNode->id(), 'No hit URL found.');
$result = db_select('node_counter', 'nc')
->fields('nc', ['daycount'])
->condition('nid', $this->testNode->id(), '=')
->execute()
->fetchField();
$this->assertFalse($result, 'Daycounter is zero.');
}
}

View file

@ -0,0 +1,57 @@
<?php
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
*/
class StatisticsAttachedTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'statistics'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(['type' => 'page']);
// Install "statistics_test_attached" and set it as the default theme.
$theme = 'statistics_test_attached';
\Drupal::service('theme_handler')->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() {
$node = Node::create([
'type' => 'page',
'title' => 'Page node',
'body' => 'body text',
]);
$node->save();
$this->drupalGet('node/' . $node->id());
$this->assertRaw('core/modules/statistics/statistics.js', 'Statistics library is available');
}
}

View file

@ -0,0 +1,142 @@
<?php
namespace Drupal\Tests\statistics\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\node\Entity\Node;
/**
* Tests request logging for cached and uncached pages.
*
* We subclass WebTestBase rather than StatisticsTestBase, because we
* want to test requests from an anonymous user.
*
* @group statistics
*/
class StatisticsLoggingTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'statistics', 'block', 'locale'];
/**
* 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;
protected function setUp() {
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->drupalPostForm('admin/config/regional/language/add', $this->language, t('Add custom language'));
$this->drupalPostForm('admin/config/regional/language/detection', ['language_interface[enabled][language-url]' => 1], t('Save settings'));
$this->drupalLogout();
// Enable access logging.
$this->config('statistics.settings')
->set('count_content_views', 1)
->save();
// Clear the logs.
db_truncate('node_counter');
$this->client = \Drupal::httpClient();
}
/**
* Verifies node hit counter logging and script placement.
*/
public function testLogging() {
$path = 'node/' . $this->node->id();
$module_path = drupal_get_path('module', '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();
$this->assertNoPattern($expected_library, 'Statistics library JS not found on node page.');
$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();
$this->assertNoPattern($expected_library, 'Statistics library JS not found on non-existent node page.');
$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->assertPattern($expected_library, 'Found statistics library JS on node page.');
$this->assertIdentical($this->node->id(), $settings['statistics']['data']['nid'], '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->assertPattern($expected_library, 'Found statistics library JS on a valid node page in a non-default language.');
$this->assertIdentical($this->node->id(), $settings['statistics']['data']['nid'], '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 = statistics_get($this->node->id());
$this->assertIdentical($node_counter['totalcount'], 1);
// 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 = statistics_get($node_id);
$this->assertIdentical($result, FALSE);
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace Drupal\Tests\statistics\Functional;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
/**
* Tests display of statistics report blocks.
*
* @group statistics
*/
class StatisticsReportsTest extends StatisticsTestBase {
use AssertPageCacheContextsAndTagsTrait;
/**
* Tests the "popular content" block.
*/
public function testPopularContentBlock() {
// 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 . '/' . drupal_get_path('module', '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->assertText('Popular content', 'Found the popular content block.');
$this->assertText("Today's", "Found today's popular content.");
$this->assertText('All time', 'Found the all time popular content.');
$this->assertText('Last viewed', 'Found the last viewed popular content.');
$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']);
$this->assertCacheContexts($contexts);
// Check if the node link is displayed.
$this->assertRaw(\Drupal::l($node->label(), $node->urlInfo('canonical')), 'Found link to visited node.');
}
}

View file

@ -0,0 +1,51 @@
<?php
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
*/
public static $modules = ['node', 'block', 'ban', 'statistics'];
/**
* User with permissions to ban IP's.
*
* @var \Drupal\user\UserInterface
*/
protected $blockingUser;
protected function setUp() {
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,52 @@
<?php
namespace Drupal\Tests\statistics\Functional;
/**
* Generates text using placeholders for dummy content to check statistics token
* replacement.
*
* @group statistics
*/
class StatisticsTokenReplaceTest extends StatisticsTestBase {
/**
* Creates a node, then tests the statistics tokens generated from it.
*/
public function testStatisticsTokenReplacement() {
$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()]);
// 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 . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = \Drupal::httpClient();
$client->post($stats_path, ['headers' => $headers, 'body' => $post]);
$statistics = statistics_get($node->id());
// Generate and test tokens.
$tests = [];
$tests['[node:total-count]'] = 1;
$tests['[node:day-count]'] = 1;
$tests['[node:last-view]'] = format_date($statistics['timestamp']);
$tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short');
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(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->assertEqual($output, $expected, format_string('Statistics token %token replaced.', ['%token' => $input]));
}
}
}

View file

@ -0,0 +1,103 @@
<?php
namespace Drupal\Tests\statistics\Functional\Views;
use Drupal\Tests\views\Functional\ViewTestBase;
use Drupal\views\Tests\ViewTestData;
/**
* Tests basic integration of views data from the statistics module.
*
* @group statistics
* @see
*/
class IntegrationTest extends ViewTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['statistics', 'statistics_test_views', 'node'];
/**
* Stores the user object that accesses the page.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* 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'];
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
ViewTestData::createTestViews(get_class($this), ['statistics_test_views']);
// 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() {
$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 . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = $this->getHttpClient();
$client->post($stats_path, ['form_params' => ['nid' => $this->node->id()]]);
$this->drupalGet('test_statistics_integration');
$expected = statistics_get($this->node->id());
// Convert the timestamp to year, to match the expected output of the date
// handler.
$expected['timestamp'] = date('Y', $expected['timestamp']);
foreach ($expected as $field => $value) {
$xpath = "//div[contains(@class, views-field-$field)]/span[@class = 'field-content']";
$this->assertFieldByXpath($xpath, $value, "The $field output matches the expected.");
}
$this->drupalLogout();
$this->drupalLogin($this->deniedUser);
$this->drupalGet('test_statistics_integration');
$this->assertResponse(200);
foreach ($expected as $field => $value) {
$xpath = "//div[contains(@class, views-field-$field)]/span[@class = 'field-content']";
$this->assertNoFieldByXpath($xpath, $value, "The $field output is not displayed.");
}
}
}

View file

@ -0,0 +1,87 @@
<?php
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 system
*/
class StatisticsLoggingTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'statistics', 'language'];
/**
* Node for tests.
*
* @var \Drupal\node\Entity\Node
*/
protected $node;
/**
* {@inheritdoc}
*/
protected function setUp() {
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'])->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() {
// 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', '.statistics-counter');
return $field_counter ? (int) explode(' ', $field_counter->getText())[0] : NULL;
}
}

View file

@ -0,0 +1,92 @@
<?php
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
*/
class MigrateNodeCounterTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = [
'content_translation',
'language',
'menu_ui',
// Required for translation migrations.
'migrate_drupal_multilingual',
'node',
'statistics',
'text',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
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',
]);
}
/**
* Tests migration of node counter.
*/
public function testStatisticsSettings() {
$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.
*/
protected function assertNodeCounter($nid, $total_count, $day_count, $timestamp) {
/** @var \Drupal\statistics\StatisticsViewsResult $statistics */
$statistics = $this->container->get('statistics.storage.node')->fetchView($nid);
// @todo Remove casting after https://www.drupal.org/node/2926069 lands.
$this->assertSame($total_count, (int) $statistics->getTotalCount());
$this->assertSame($day_count, (int) $statistics->getDayCount());
$this->assertSame($timestamp, (int) $statistics->getTimestamp());
}
}

View file

@ -0,0 +1,39 @@
<?php
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 migrate_drupal_6
*/
class MigrateStatisticsConfigsTest extends MigrateDrupal6TestBase {
use SchemaCheckTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['statistics'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executeMigration('statistics_settings');
}
/**
* Tests migration of statistics variables to statistics.settings.yml.
*/
public function testStatisticsSettings() {
$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,86 @@
<?php
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
*/
class MigrateNodeCounterTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
public static $modules = [
'content_translation',
'language',
'menu_ui',
// Required for translation migrations.
'migrate_drupal_multilingual',
'node',
'statistics',
'text',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('node');
$this->installConfig('node');
$this->installSchema('node', ['node_access']);
$this->installSchema('statistics', ['node_counter']);
$this->executeMigrations([
'language',
'd7_user_role',
'd7_user',
'd7_node_type',
'd7_language_content_settings',
'd7_node',
'd7_node_translation',
'statistics_node_counter',
]);
}
/**
* Tests migration of node counter.
*/
public function testStatisticsSettings() {
$this->assertNodeCounter(1, 2, 0, 1421727536);
$this->assertNodeCounter(2, 1, 0, 1471428059);
$this->assertNodeCounter(4, 1, 1, 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, 2, 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.
*/
protected function assertNodeCounter($nid, $total_count, $day_count, $timestamp) {
/** @var \Drupal\statistics\StatisticsViewsResult $statistics */
$statistics = $this->container->get('statistics.storage.node')->fetchView($nid);
// @todo Remove casting after https://www.drupal.org/node/2926069 lands.
$this->assertSame($total_count, (int) $statistics->getTotalCount());
$this->assertSame($day_count, (int) $statistics->getDayCount());
$this->assertSame($timestamp, (int) $statistics->getTimestamp());
}
}

View file

@ -0,0 +1,39 @@
<?php
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 migrate_drupal_7
*/
class MigrateStatisticsConfigsTest extends MigrateDrupal7TestBase {
use SchemaCheckTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['statistics'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executeMigration('statistics_settings');
}
/**
* Tests migration of statistics variables to statistics.settings.yml.
*/
public function testStatisticsSettings() {
$config = $this->config('statistics.settings');
$this->assertIdentical(1, $config->get('count_content_views'));
$this->assertConfigSchema(\Drupal::service('config.typed'), 'statistics.settings', $config->get());
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Drupal\Tests\statistics\Kernel\Plugin\migrate\source;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the node_counter source plugin.
*
* @covers \Drupal\statistics\Plugin\migrate\source\NodeCounter
*
* @group statistics
*/
class NodeCounterTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['migrate_drupal', 'statistics'];
/**
* {@inheritdoc}
*/
public 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,37 @@
<?php
namespace Drupal\Tests\statistics\Unit;
use Drupal\statistics\StatisticsViewsResult;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\statistics\StatisticsViewsResult
* @group statistics
*/
class StatisticsViewsResultTest extends UnitTestCase {
/**
* Tests migration of node counter.
*
* @covers ::__construct
*
* @dataProvider providerTestStatisticsCount
*/
public function testStatisticsCount($total_count, $day_count, $timestamp) {
$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 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,5 @@
name: 'Statistics test attached theme'
type: theme
description: 'Theme for testing attached library'
version: VERSION
core: 8.x