CaptchaCronTest.php 2.53 KB
Newer Older
1
2
<?php

3
namespace Drupal\Tests\captcha\Functional;
4
5

use Drupal\Core\Database\Database;
6
use Drupal\Tests\BrowserTestBase;
7
8
9
10
11
12

/**
 * Tests CAPTCHA cron.
 *
 * @group captcha
 */
13
class CaptchaCronTest extends BrowserTestBase {
14

15
  /**
16
17
18
   * Modules to install for this Test class.
   *
   * @var array
19
20
21
22
23
24
25
26
   */
  public static $modules = ['captcha'];

  /**
   * Temporary captcha sessions storage.
   *
   * @var [int]
   */
27
  public $captchaSessions;
28
29
30
31
32
33
34

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

35
36
37
    // Get request time.
    $request_time = \Drupal::time()->getRequestTime();

38
    // Add removed session.
39
    $time = $request_time - 1 - 60 * 60 * 24;
40
    $this->captchaSessions['remove_sid'] = $this->addCaptchaSession('captcha_cron_test_remove', $time);
41
    // Add remain session.
42
    $this->captchaSessions['remain_sid'] = $this->addCaptchaSession('captcha_cron_test_remain', $request_time);
43
44
45
  }

  /**
46
47
48
49
50
51
52
53
54
   * Add test CAPTCHA session data.
   *
   * @param string $form_id
   *   Form id.
   * @param int $request_time
   *   Timestamp.
   *
   * @return int
   *   CAPTCHA session id.
55
   */
56
  public function addCaptchaSession($form_id, $request_time) {
57
    // Initialize solution with random data.
58
    $solution = hash('sha256', mt_rand());
59
60
61
62

    // Insert an entry and thankfully receive the value
    // of the autoincrement field 'csid'.
    $connection = Database::getConnection();
63
64
65
66
67
68
69
70
71
72
73
    $captcha_sid = $connection->insert('captcha_sessions')->fields([
      'uid' => 0,
      'sid' => session_id(),
      'ip_address' => \Drupal::request()->getClientIp(),
      'timestamp' => $request_time,
      'form_id' => $form_id,
      'solution' => $solution,
      'status' => 1,
      'attempts' => 0,
    ])->execute();

74
75
76
77
    return $captcha_sid;
  }

  /**
78
   * Test CAPTCHA cron.
79
80
   */
  public function testCron() {
81
    \Drupal::service('cron')->run();
82
83

    $connection = Database::getConnection();
84
85
    $sids = $connection->select('captcha_sessions')
      ->fields('captcha_sessions', ['csid'])
86
      ->condition('csid', array_values($this->captchaSessions), 'IN')
87
88
89
      ->execute()
      ->fetchCol('csid');

90
    // Test if CAPTCHA cron appropriately removes sessions older than a day.
91
    $this->assertNotContains($this->captchaSessions['remove_sid'], $sids, 'CAPTCHA cron removes captcha session data older than 1 day.');
92

93
    // Test if CAPTCHA cron appropriately keeps sessions younger than a day.
94
    $this->assertContains($this->captchaSessions['remain_sid'], $sids, 'CAPTCHA cron does not remove captcha session data younger than 1 day.');
95
  }
96

97
}