View source
<?php
namespace Drupal\nodeviewcount\Tests;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\KernelTests\AssertContentTrait;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
abstract class NodeViewCountTestBase extends BrowserTestBase {
use AssertContentTrait;
public static $modules = [
'node',
'nodeviewcount',
];
protected $adminUser;
protected $firstTestTrackedNode;
protected $secondTestTrackedNode;
protected $testNotTrackedNode;
protected $connection;
protected $httpClientFactory;
protected $client;
protected $FormattableMarkup;
protected function setUp() {
parent::setUp();
$this
->createRole([
'access administration pages',
'administer modules',
'administer users',
'access content',
], 'administrator', 'administrator');
$this->adminUser = $this
->createUserWithRole('administrator');
$this->firstTestTrackedNode = $this
->drupalCreateNode([
'type' => 'tracked_page',
'uid' => $this->adminUser
->id(),
'promoted' => TRUE,
]);
$this->secondTestTrackedNode = $this
->drupalCreateNode([
'type' => 'tracked_page',
'uid' => $this->adminUser
->id(),
'promoted' => TRUE,
]);
$this->testNotTrackedNode = $this
->drupalCreateNode([
'type' => 'not_tracked_page',
'uid' => $this->adminUser
->id(),
'promoted' => TRUE,
]);
$this->connection = $this->container
->get('database');
$this->httpClientFactory = $this->container
->get('http_client_factory');
$this->client = $this->httpClientFactory
->fromOptions([
'config/curl' => [
CURLOPT_TIMEOUT => 20,
],
]);
$this
->drupalCreateContentType([
'type' => 'tracked_page',
'name' => 'Basic page with tracking',
]);
$this
->drupalCreateContentType([
'type' => 'not_tracked_page',
'name' => 'Basic page with no tracking',
]);
$this
->createRole([
'access content',
'change own username',
], 'logged', 'logged');
$this
->setNodeviewcountSettings();
}
private function setNodeviewcountSettings() {
$node_view_count_settings = $this
->config('nodeviewcount.settings');
$node_view_count_settings
->set('user_roles', [
'anonymous',
'logged',
])
->set('excluded_user_roles', [
'administrator',
])
->set('node_types', [
'tracked_page',
])
->set('view_modes', [
'full',
'teaser',
])
->set('logs_life_time', 0)
->save();
}
protected function sendAjaxStatistics($nid, $uid) {
global $base_url;
$stats_path = $base_url . '/nodeviewcount/updateCounter';
$post = [
'nid' => $nid,
'uid' => $uid,
];
$this->client
->post($stats_path, [
'form_params' => $post,
]);
}
protected function createUserWithRole($user_role_name) {
$edit['name'] = $this
->randomMachineName();
$edit['mail'] = $edit['name'] . '@example.com';
$edit['pass'] = user_password();
$edit['status'] = 1;
$edit['roles'] = [
$user_role_name,
];
$account = User::create($edit);
$account
->save();
$this
->assertTrue($account
->id(), new FormattableMarkup('User created with name %name and pass %pass', [
'%name' => $edit['name'],
'%pass' => $edit['pass'],
]));
if (!$account
->id()) {
return NULL;
}
$account->pass_raw = $edit['pass'];
return $account;
}
}