summaryrefslogtreecommitdiff
path: root/plugins/Irc/extlib/phergie/Tests/Phergie/Plugin/TestCase.php
blob: 941e7cb41078f83a7937279d2dbcf844df9e8584 (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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
<?php
/**
 * Phergie
 *
 * PHP version 5
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * http://phergie.org/license
 *
 * @category  Phergie
 * @package   Phergie_Tests
 * @author    Phergie Development Team <team@phergie.org>
 * @copyright 2008-2010 Phergie Development Team (http://phergie.org)
 * @license   http://phergie.org/license New BSD License
 * @link      http://pear.phergie.org/package/Phergie_Tests
 */

/**
 * Unit test suite for plugin classes.
 *
 * @category Phergie
 * @package  Phergie_Tests
 * @author   Phergie Development Team <team@phergie.org>
 * @license  http://phergie.org/license New BSD License
 * @link     http://pear.phergie.org/package/Phergie_Tests
 */
abstract class Phergie_Plugin_TestCase extends PHPUnit_Framework_TestCase
{
    /**
     * Mock configuration
     *
     * @var Phergie_Config
     */
    protected $config;

    /**
     * Associative array for configuration setting values, accessed by the
     * mock configuration object using a callback
     *
     * @var array
     */
    protected $settings = array();

    /**
     * Mock connection
     *
     * @var Phergie_Connection
     */
    protected $connection;

    /**
     * Mock event handler
     *
     * @var Phergie_Event_Handler
     */
    protected $events;

    /**
     * Mock plugin handler
     *
     * @var Phergie_Plugin_Handler
     */
    protected $plugins;

    /**
     * Plugin instance being tested
     *
     * @var Phergie_Plugin_Abstract
     */
    protected $plugin;

    /**
     * Full name of the plugin class being tested, may be explicitly
     * specified in subclasses but is otherwise automatically derived from
     * the test case class name
     *
     * @var string
     */
    protected $pluginClass;

    /**
     * User nick used in any events requiring one
     *
     * @var string
     */
    protected $nick = 'nick';

    /**
     * Event source used in any events requiring one
     *
     * @var string
     */
    protected $source = '#channel';

    /**
     * Initializes instance properties.
     *
     * @return void
     */
    public function setUp()
    {
        if (empty($this->pluginClass)) {
            $this->pluginClass = preg_replace('/Test$/', '', get_class($this));
        }

        if (empty($this->plugin)) {
            $this->plugin = new $this->pluginClass;
        }

        $this->plugin->setConfig($this->getMockConfig());
        $this->plugin->setConnection($this->getMockConnection());
        $this->plugin->setEventHandler($this->getMockEventHandler());
        $this->plugin->setPluginHandler($this->getMockPluginHandler());
    }

    /**
     * Destroys all initialized instance properties.
     *
     * @return void
     */
    public function tearDown()
    {
        unset(
            $this->plugins,
            $this->events,
            $this->connection,
            $this->config,
            $this->plugin
        );
    }

    /**
     * Returns a mock configuration object.
     *
     * @return Phergie_Config
     */
    protected function getMockConfig()
    {
        if (empty($this->config)) {
            $this->config = $this->getMock('Phergie_Config', array('offsetExists', 'offsetGet'));
            $this->config
                ->expects($this->any())
                ->method('offsetExists')
                ->will($this->returnCallback(array($this, 'configOffsetExists')));
            $this->config
                ->expects($this->any())
                ->method('offsetGet')
                ->will($this->returnCallback(array($this, 'configOffsetGet')));
        }
        return $this->config;
    }

    /**
     * Returns whether a specific configuration setting has a value. Only
     * intended for use by this class, but must be public for PHPUnit to
     * call them.
     *
     * @param string $name Name of the setting
     *
     * @return boolean TRUE if the setting has a value, FALSE otherwise
     */
    public function configOffsetExists($name)
    {
        return isset($this->settings[$name]);
    }

    /**
     * Returns the value of a specific configuration setting. Only intended
     * for use by this class, but must be public for PHPUnit to call them.
     *
     * @param string $name Name of the setting
     *
     * @return mixed Value of the setting
     */
    public function configOffsetGet($name)
    {
        return $this->settings[$name];
    }

    /**
     * Returns a mock connection object.
     *
     * @return Phergie_Connection
     */
    protected function getMockConnection()
    {
        if (empty($this->connection)) {
            $this->connection = $this->getMock('Phergie_Connection');
            $this->connection
                ->expects($this->any())
                ->method('getNick')
                ->will($this->returnValue($this->nick));
        }
        return $this->connection;
    }

    /**
     * Returns a mock event handler object.
     *
     * @return Phergie_Event_Handler
     */
    protected function getMockEventHandler()
    {
        if (empty($this->events)) {
            $this->events = $this->getMock('Phergie_Event_Handler', array('addEvent'));
        }
        return $this->events;
    }

    /**
     * Returns a mock plugin handler object.
     *
     * @return Phergie_Plugin_Handler
     */
    protected function getMockPluginHandler()
    {
        if (empty($this->plugins)) {
            $config = $this->getMockConfig();
            $events = $this->getMockEventHandler();
            $this->plugins = $this->getMock(
                'Phergie_Plugin_Handler',
                array(), // mock everything
                array($config, $events)
            );
        }
        return $this->plugins;
    }

    /**
     * Returns a mock event object.
     *
     * @param string $type   Event type
     * @param array  $args   Optional associative array of event arguments
     * @param string $nick   Optional user nick to associate with the event
     * @param string $source Optional user nick or channel name to associate
     *        with the event as its source
     *
     * @return Phergie_Event_Request
     */
    protected function getMockEvent($type, array $args = array(),
        $nick = null, $source = null
    ) {
        $methods = array('getNick', 'getSource');
        foreach (array_keys($args) as $arg) {
            if (is_int($arg) || ctype_digit($arg)) {
                $methods[] = 'getArgument';
            } else {
                $methods[] = 'get' . ucfirst($arg);
            }
        }

        $event = $this->getMock(
            'Phergie_Event_Request',
            $methods
        );

        $nick = $nick ? $nick : $this->nick;
        $event
            ->expects($this->any())
            ->method('getNick')
            ->will($this->returnValue($nick));

        $source = $source ? $source : $this->source;
        $event
            ->expects($this->any())
            ->method('getSource')
            ->will($this->returnValue($source));

        foreach ($args as $key => $value) {
            if (is_int($key) || ctype_digit($key)) {
                $event
                    ->expects($this->any())
                    ->method('getArgument')
                    ->with($key)
                    ->will($this->returnValue($value));
            } else {
                $event
                    ->expects($this->any())
                    ->method('get' . ucfirst($key))
                    ->will($this->returnValue($value));
            }
        }

        return $event;
    }

    /**
     * Sets the value of a configuration setting.
     *
     * @param string $setting Name of the setting
     * @param mixed  $value   Value for the setting
     *
     * @return void
     */
    protected function setConfig($setting, $value)
    {
        $this->settings[$setting] = $value;
    }

    /**
     * Returns the absolute path to the Phergie/Plugin directory. Useful in
     * conjunction with getMockDatabase().
     *
     * @param string $subpath Optional path to append to the directory path
     *
     * @return string Directory path
     */
    protected function getPluginsPath($subpath = null)
    {
        $path = realpath(dirname(__FILE__) . '/../../../Phergie/Plugin');
        if (!empty($subpath)) {
            $path .= '/' . ltrim($subpath, '/');
        }
        return $path;
    }

    /**
     * Modifies the event handler to include an expectation of an event
     * being added by the plugin being tested. Note that this must be called
     * BEFORE executing the plugin code intended to initiate the event.
     *
     * @param string $type Event type
     * @param array  $args Optional enumerated array of event arguments
     *
     * @return void
     */
    protected function assertEmitsEvent($type, array $args = array())
    {
        $this->events
            ->expects($this->at(0))
            ->method('addEvent')
            ->with($this->plugin, $type, $args);
    }

    /**
     * Modifies the event handler to include an expectation of an event NOT
     * being added by the plugin being tested. Note that this must be called
     * BEFORE executing plugin code that may initiate the event.
     *
     * @param string $type Event type
     * @param array  $args Optional enumerated array of event arguments
     *
     * @return void
     */
    protected function assertDoesNotEmitEvent($type, array $args = array())
    {
        // Ugly hack to get around an issue in PHPUnit
        // @link http://github.com/sebastianbergmann/phpunit-mock-objects/issues/issue/5#issue/5/comment/343524
        $callback = create_function(
            '$plugin, $type, $args',
            'if (get_class($plugin) == "' . $this->pluginClass . '"
            && $type == "' . $type . '"
            && $args == "' . var_export($args, true) . '") {
                trigger_error("Instance of ' . $this->pluginClass
                . ' unexpectedly emitted event of type ' . $type
                . '", E_USER_ERROR);
            }'
        );

        $this->events
            ->expects($this->any())
            ->method('addEvent')
            ->will($this->returnCallback($callback));
    }

    /**
     * Modifies the plugin handler to include an expectation of a plugin
     * being retrieved, indicating a dependency. Note that this must be
     * called BEFORE executing the plugin code that may load that plugin
     * dependency, which is usually located in onLoad().
     *
     * @param string $name Short name of the plugin required as a dependency
     *
     * @return void
     */
    public function assertRequiresPlugin($name)
    {
        $this->plugins
            ->expects($this->atLeastOnce())
            ->method('getPlugin')
            ->with($name);
    }

    /**
     * Creates an in-memory copy of a specified SQLite database file and
     * returns a connection to it.
     *
     * @param string $path Path to the SQLite file to copy
     *
     * @return PDO Connection to the database copy
     */
    public function getMockDatabase($path)
    {
        $original = new PDO('sqlite:' . $path);
        $copy = new PDO('sqlite::memory:');

        $result = $original->query('SELECT sql FROM sqlite_master');
        while ($sql = $result->fetchColumn()) {
            $copy->exec($sql);
        }

        $tables = array();
        $result = $original->query('SELECT name FROM sqlite_master WHERE type = "table"');
        while ($table = $result->fetchColumn()) {
            $tables[] = $table;
        }

        foreach ($tables as $table) {
            $result = $original->query('SELECT * FROM ' . $table);
            $insert = null;
            $copy->beginTransaction();
            while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
                $columns = array_keys($row);
                if (empty($insert)) {
                    $insert = $copy->prepare(
                        'INSERT INTO "' . $table . '" (' .
                        '"' . implode('", "', $columns) . '"' .
                        ') VALUES (' .
                        ':' . implode(', :', $columns) .
                        ')'
                    );
                }
                $insert->execute($row);
            }
            $copy->commit();
            unset($insert);
        }

        return $copy;
    }
}