1<?php
2
3use dokuwiki\Extension\PluginController;
4use dokuwiki\Extension\Event;
5use dokuwiki\Extension\EventHandler;
6use dokuwiki\Logger;
7
8/**
9 * Helper class to provide basic functionality for tests
10 *
11 * @uses PHPUnit_Framework_TestCase and thus PHPUnit 5.7+ is required
12 */
13abstract class DokuWikiTest extends PHPUnit\Framework\TestCase {
14
15    /**
16     * tests can override this
17     *
18     * @var array plugins to enable for test class
19     */
20    protected $pluginsEnabled = array();
21
22    /**
23     * tests can override this
24     *
25     * @var array plugins to disable for test class
26     */
27    protected $pluginsDisabled = array();
28
29    /**
30     * setExpectedException was deprecated in PHPUnit 6
31     *
32     * @param string $class
33     * @param null|string $message
34     */
35    public function setExpectedException($class, $message=null) {
36        $this->expectException($class);
37        if(!is_null($message)) {
38            $this->expectExceptionMessage($message);
39        }
40    }
41
42    /**
43     * Setup the data directory
44     *
45     * This is ran before each test class
46     */
47    public static function setUpBeforeClass() : void {
48        // just to be safe not to delete something undefined later
49        if(!defined('TMP_DIR')) die('no temporary directory');
50        if(!defined('DOKU_TMP_DATA')) die('no temporary data directory');
51
52        self::setupDataDir();
53        self::setupConfDir();
54    }
55
56    /**
57     * Reset the DokuWiki environment before each test run. Makes sure loaded config,
58     * language and plugins are correct.
59     *
60     * @throws Exception if plugin actions fail
61     * @return void
62     */
63    public function setUp() : void {
64        // reset execution time if it's enabled
65        if(ini_get('max_execution_time') > 0) {
66            set_time_limit(90);
67        }
68
69        // reload config
70        global $conf, $config_cascade;
71        $conf = array();
72        foreach (array('default','local','protected') as $config_group) {
73            if (empty($config_cascade['main'][$config_group])) continue;
74            foreach ($config_cascade['main'][$config_group] as $config_file) {
75                if (file_exists($config_file)) {
76                    include($config_file);
77                }
78            }
79        }
80
81        // reload license config
82        global $license;
83        $license = array();
84
85        // load the license file(s)
86        foreach (array('default','local') as $config_group) {
87            if (empty($config_cascade['license'][$config_group])) continue;
88            foreach ($config_cascade['license'][$config_group] as $config_file) {
89                if(file_exists($config_file)){
90                    include($config_file);
91                }
92            }
93        }
94        // reload some settings
95        $conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false);
96
97        if($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
98            $conf['compression'] = 'gz';
99        }
100        if($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
101            $conf['compression'] = 0;
102        }
103        // make real paths and check them
104        init_creationmodes();
105        init_paths();
106        init_files();
107
108        // reset loaded plugins
109        global $plugin_controller_class, $plugin_controller;
110        /** @var PluginController $plugin_controller */
111        $plugin_controller = new $plugin_controller_class();
112
113        // disable all non-default plugins
114        global $default_plugins;
115        foreach ($plugin_controller->getList() as $plugin) {
116            if (!in_array($plugin, $default_plugins)) {
117                if (!$plugin_controller->disable($plugin)) {
118                    throw new Exception('Could not disable plugin "'.$plugin.'"!');
119                }
120            }
121        }
122
123        // disable and enable configured plugins
124        foreach ($this->pluginsDisabled as $plugin) {
125            if (!$plugin_controller->disable($plugin)) {
126                throw new Exception('Could not disable plugin "'.$plugin.'"!');
127            }
128        }
129        foreach ($this->pluginsEnabled as $plugin) {
130            /*  enable() returns false but works...
131            if (!$plugin_controller->enable($plugin)) {
132                throw new Exception('Could not enable plugin "'.$plugin.'"!');
133            }
134            */
135            $plugin_controller->enable($plugin);
136        }
137
138        // reset event handler
139        global $EVENT_HANDLER;
140        $EVENT_HANDLER = new EventHandler();
141
142        // reload language
143        $local = $conf['lang'];
144        Event::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
145
146        global $INPUT;
147        $INPUT = new \dokuwiki\Input\Input();
148    }
149
150    /**
151     * Reinitialize the data directory for this class run
152     */
153    public static function setupDataDir() {
154        // remove any leftovers from the last run
155        if(is_dir(DOKU_TMP_DATA)) {
156            // clear indexer data and cache
157            idx_get_indexer()->clear();
158            TestUtils::rdelete(DOKU_TMP_DATA);
159        }
160
161        // populate default dirs
162        TestUtils::rcopy(TMP_DIR, __DIR__ . '/../data/');
163    }
164
165    /**
166     * Reinitialize the conf directory for this class run
167     */
168    public static function setupConfDir() {
169        $defaults = [
170            'acronyms.conf',
171            'dokuwiki.php',
172            'entities.conf',
173            'interwiki.conf',
174            'license.php',
175            'manifest.json',
176            'mediameta.php',
177            'mime.conf',
178            'plugins.php',
179            'plugins.required.php',
180            'scheme.conf',
181            'smileys.conf',
182            'wordblock.conf'
183        ];
184
185        // clear any leftovers
186        if(is_dir(DOKU_CONF)) {
187            TestUtils::rdelete(DOKU_CONF);
188        }
189        mkdir(DOKU_CONF);
190
191        // copy defaults
192        foreach($defaults as $file) {
193            copy(DOKU_INC . '/conf/' . $file, DOKU_CONF . $file);
194        }
195
196        // copy test files
197        TestUtils::rcopy(TMP_DIR, __DIR__ . '/../conf');
198    }
199
200    /**
201     * Waits until a new second has passed
202     *
203     * This tried to be clever about the passing of time and return early if possible. Unfortunately
204     * this never worked reliably for unknown reasons. To avoid flaky tests, this now always simply
205     * sleeps for a full second on every call.
206     *
207     * @param bool $init no longer used
208     * @return int new timestamp
209     */
210    protected function waitForTick($init = false) {
211        sleep(1);
212        return time();
213    }
214
215    /**
216     * Allow for testing inaccessible methods (private or protected)
217     *
218     * This makes it easier to test protected methods without needing to create intermediate
219     * classes inheriting and changing the access.
220     *
221     * @link https://stackoverflow.com/a/8702347/172068
222     * @param object $obj Object in which to call the method
223     * @param string $func The method to call
224     * @param array $args The arguments to call the method with
225     * @return mixed
226     * @throws ReflectionException when the given obj/func does not exist
227     */
228    protected static function callInaccessibleMethod($obj, $func, array $args) {
229        $class = new \ReflectionClass($obj);
230        $method = $class->getMethod($func);
231        $method->setAccessible(true);
232        return $method->invokeArgs($obj, $args);
233    }
234
235    /**
236     * Allow for reading inaccessible properties (private or protected)
237     *
238     * This makes it easier to check internals of tested objects. This should generally
239     * be avoided.
240     *
241     * @param object $obj Object on which to access the property
242     * @param string $prop name of the property to access
243     * @return mixed
244     * @throws ReflectionException  when the given obj/prop does not exist
245     */
246    protected static function getInaccessibleProperty($obj, $prop) {
247        $class = new \ReflectionClass($obj);
248        $property = $class->getProperty($prop);
249        $property->setAccessible(true);
250        return $property->getValue($obj);
251    }
252
253    /**
254     * Allow for reading inaccessible properties (private or protected)
255     *
256     * This makes it easier to set internals of tested objects. This should generally
257     * be avoided.
258     *
259     * @param object $obj Object on which to access the property
260     * @param string $prop name of the property to access
261     * @param mixed $value new value to set the property to
262     * @return void
263     * @throws ReflectionException when the given obj/prop does not exist
264     */
265    protected static function setInaccessibleProperty($obj, $prop, $value) {
266        $class = new \ReflectionClass($obj);
267        $property = $class->getProperty($prop);
268        $property->setAccessible(true);
269        $property->setValue($obj, $value);
270    }
271
272    /**
273     * Expect the next log message to contain $message
274     *
275     * @param string $facility
276     * @param string $message
277     * @return void
278     */
279    protected function expectLogMessage(string $message, string $facility = Logger::LOG_ERROR): void
280    {
281        $logger = Logger::getInstance($facility);
282        $logger->expect($message);
283    }
284}
285