Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SchedulerTest.php « Scheduler « Unit « PHPUnit « tests - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2db0dfaad62a7a3fd86ffb2f7dc1c1d4febbac3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Tests\Unit\Scheduler;

use Piwik\Date;
use Piwik\Plugin;
use Piwik\Scheduler\Scheduler;
use Piwik\Scheduler\Task;
use Piwik\Scheduler\Timetable;
use Piwik\Tests\Framework\Mock\PiwikOption;
use Psr\Log\NullLogger;
use ReflectionProperty;

/**
 * @group Scheduler
 */
class SchedulerTest extends \PHPUnit\Framework\TestCase
{
    private static function getTestTimetable()
    {
        return array(
            'CoreAdminHome.purgeOutdatedArchives' => 1355529607,
            'PrivacyManager.deleteReportData_1'   => 1322229607,
        );
    }

    /**
     * Dataprovider for testGetScheduledTimeForMethod
     */
    public function getScheduledTimeForMethodTestCases()
    {
        $timetable = serialize(self::getTestTimetable());

        return array(
            array(1355529607, 'CoreAdminHome', 'purgeOutdatedArchives', null, $timetable),
            array(1322229607, 'PrivacyManager', 'deleteReportData', 1, $timetable),
            array(false, 'ScheduledReports', 'weeklySchedule', null, $timetable)
        );
    }

    /**
     * @dataProvider getScheduledTimeForMethodTestCases
     */
    public function testGetScheduledTimeForMethod($expectedTime, $className, $methodName, $methodParameter, $timetable)
    {
        self::stubPiwikOption($timetable);

        $taskLoader = $this->getMock('Piwik\Scheduler\TaskLoader');
        $scheduler = new Scheduler($taskLoader, new NullLogger());

        $this->assertEquals($expectedTime, $scheduler->getScheduledTimeForMethod($className, $methodName, $methodParameter));

        self::resetPiwikOption();
    }

    public function testRescheduleTaskAndRunTomorrow()
    {
        $timetable = serialize(self::getTestTimetable());
        self::stubPiwikOption($timetable);

        $plugin = new Plugin();
        $task = new Task($plugin, 'getVersion', null, null);

        $taskLoader = $this->getMockBuilder('Piwik\Scheduler\TaskLoader')
            ->disableOriginalConstructor()
            ->getMock();
        $scheduler = new Scheduler($taskLoader, new NullLogger());

        $scheduler->rescheduleTaskAndRunTomorrow($task);

        $this->assertEquals(Date::factory('tomorrow')->getTimeStamp(), $scheduler->getScheduledTimeForMethod(Plugin::class, 'getVersion', null));
    }

    /**
     * Dataprovider for testRun
     */
    public function runDataProvider()
    {
        $now = time();

        $dailySchedule = $this->getMock('Piwik\Scheduler\Schedule\Daily', array('getTime'));
        $dailySchedule->expects($this->any())
            ->method('getTime')
            ->will($this->returnValue($now));

        $scheduledTaskOne = new Task($this, 'scheduledTaskOne', null, $dailySchedule);
        $scheduledTaskTwo = new Task($this, 'scheduledTaskTwo', 1, $dailySchedule);
        $scheduledTaskThree = new Task($this, 'scheduledTaskThree', null, $dailySchedule);

        $caseOneExpectedTable = array(
            __CLASS__ . '.scheduledTaskOne'   => $scheduledTaskOne->getRescheduledTime(),
            __CLASS__ . '.scheduledTaskTwo_1' => $now + 60000,
            __CLASS__ . '.scheduledTaskThree' => $scheduledTaskThree->getRescheduledTime(),
        );

        $caseTwoTimetableBeforeExecution = $caseOneExpectedTable;
        $caseTwoTimetableBeforeExecution[__CLASS__ . '.scheduledTaskThree'] = $now; // simulate elapsed time between case 1 and 2

        return array(

            // case 1) contains :
            // - scheduledTaskOne: already scheduled before, should be executed and rescheduled
            // - scheduledTaskTwo: already scheduled before, should not be executed and therefore not rescheduled
            // - scheduledTaskThree: not already scheduled before, should be scheduled but not executed
            array(
                $caseOneExpectedTable,
                // methods that should be executed
                array(
                    __CLASS__ . '.scheduledTaskOne'
                ),
                // timetable before task execution
                array(
                    __CLASS__ . '.scheduledTaskOne'   => $now,
                    __CLASS__ . '.scheduledTaskTwo_1' => $now + 60000,
                ),
                // configured tasks
                array(
                    $scheduledTaskOne,
                    $scheduledTaskTwo,
                    $scheduledTaskThree,
                )
            ),

            // case 2) follows case 1) with :
            // - scheduledTaskOne: already scheduled before, should not be executed and therefore not rescheduled
            // - scheduledTaskTwo: not configured for execution anymore, should be removed from the timetable
            // - scheduledTaskThree: already scheduled before, should be executed and rescheduled
            array(
                // expected timetable
                array(
                    __CLASS__ . '.scheduledTaskOne'   => $scheduledTaskOne->getRescheduledTime(),
                    __CLASS__ . '.scheduledTaskThree' => $scheduledTaskThree->getRescheduledTime()
                ),
                // methods that should be executed
                array(
                    __CLASS__ . '.scheduledTaskThree'
                ),
                // timetable before task execution
                $caseTwoTimetableBeforeExecution,
                // configured tasks
                array(
                    $scheduledTaskOne,
//					$scheduledTaskTwo, Not configured anymore (ie. not returned after TaskScheduler::GET_TASKS_EVENT is issued)
                    $scheduledTaskThree,
                )
            ),
        );
    }

    public function scheduledTaskOne()
    {
        // nothing to do
    }
    public function scheduledTaskTwo($param)
    {
        // nothing to do
    }
    public function scheduledTaskThree()
    {
        // nothing to do
    }

    /**
     * @dataProvider runDataProvider
     */
    public function testRun($expectedTimetable, $expectedExecutedTasks, $timetableBeforeTaskExecution, $configuredTasks)
    {
        $taskLoader = $this->getMock('Piwik\Scheduler\TaskLoader');
        $taskLoader->expects($this->atLeastOnce())
            ->method('loadTasks')
            ->willReturn($configuredTasks);

        // stub the piwik option object to control the returned option value
        self::stubPiwikOption(serialize($timetableBeforeTaskExecution));

        $scheduler = new Scheduler($taskLoader, new NullLogger());

        // execute tasks
        $executionResults = $scheduler->run();

        // assert methods are executed
        $executedTasks = array();
        foreach ($executionResults as $executionResult) {
            $executedTasks[] = $executionResult['task'];
            $this->assertNotEmpty($executionResult['output']);
        }
        $this->assertEquals($expectedExecutedTasks, $executedTasks);

        // assert the timetable is correctly updated
        $timetable = new Timetable();
        $this->assertEquals($expectedTimetable, $timetable->getTimetable());

        self::resetPiwikOption();
    }

    /**
     * @dataProvider runDataProvider
     */
    public function testRunTaskNow($expectedTimetable, $expectedExecutedTasks, $timetableBeforeTaskExecution, $configuredTasks)
    {
        $taskLoader = $this->getMock('Piwik\Scheduler\TaskLoader');
        $taskLoader->expects($this->atLeastOnce())
            ->method('loadTasks')
            ->willReturn($configuredTasks);

        // stub the piwik option object to control the returned option value
        self::stubPiwikOption(serialize($timetableBeforeTaskExecution));

        $timetable = new Timetable();
        $initialTimetable = $timetable->getTimetable();

        $scheduler = new Scheduler($taskLoader, new NullLogger());

        foreach ($configuredTasks as $task) {
            /** @var Task $task */
            $result = $scheduler->runTaskNow($task->getName());

            $this->assertNotEmpty($result);
        }

        // assert the timetable is NOT updated
        $this->assertSame($initialTimetable, $timetable->getTimetable());

        self::resetPiwikOption();
    }

    private static function stubPiwikOption($timetable)
    {
        self::getReflectedPiwikOptionInstance()->setValue(new PiwikOption($timetable));
    }

    private static function resetPiwikOption()
    {
        self::getReflectedPiwikOptionInstance()->setValue(null);
    }

    private static function getReflectedPiwikOptionInstance()
    {
        $piwikOptionInstance = new ReflectionProperty('Piwik\Option', 'instance');
        $piwikOptionInstance->setAccessible(true);
        return $piwikOptionInstance;
    }
}