PageRenderTime 46ms CodeModel.GetById 32ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/Zend/Log/LogTest.php

https://bitbucket.org/ksekar/campus
PHP | 556 lines | 386 code | 81 blank | 89 comment | 5 complexity | f129aceef6e7dad1be1dc38d46560f2a MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Log
 17 * @subpackage UnitTests
 18 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 19 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 20 * @version    $Id: LogTest.php 24594 2012-01-05 21:27:01Z matthew $
 21 */
 22
 23if (!defined('PHPUnit_MAIN_METHOD')) {
 24    define('PHPUnit_MAIN_METHOD', 'Zend_Log_LogTest::main');
 25}
 26
 27/** Zend_Log */
 28require_once 'Zend/Log.php';
 29
 30/** Zend_Log_Writer_Mock */
 31require_once 'Zend/Log/Writer/Mock.php';
 32
 33/** Zend_Log_Writer_Stream */
 34require_once 'Zend/Log/Writer/Stream.php';
 35
 36/** Zend_Log_FactoryInterface */
 37require_once 'Zend/Log/FactoryInterface.php';
 38
 39/**
 40 * @category   Zend
 41 * @package    Zend_Log
 42 * @subpackage UnitTests
 43 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 44 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 45 * @group      Zend_Log
 46 */
 47class Zend_Log_LogTest extends PHPUnit_Framework_TestCase
 48{
 49    public static function main()
 50    {
 51        $suite  = new PHPUnit_Framework_TestSuite(__CLASS__);
 52        $result = PHPUnit_TextUI_TestRunner::run($suite);
 53    }
 54
 55    public function setUp()
 56    {
 57        $this->log = fopen('php://memory', 'w+');
 58        $this->writer = new Zend_Log_Writer_Stream($this->log);
 59    }
 60
 61    // Writers
 62
 63    public function testWriterCanBeAddedWithConstructor()
 64    {
 65        $logger = new Zend_Log($this->writer);
 66        $logger->log($message = 'message-to-log', Zend_Log::INFO);
 67
 68        rewind($this->log);
 69        $this->assertContains($message, stream_get_contents($this->log));
 70    }
 71
 72    public function testAddWriter()
 73    {
 74        $logger = new Zend_Log();
 75        $logger->addWriter($this->writer);
 76        $logger->log($message = 'message-to-log', Zend_Log::INFO);
 77
 78        rewind($this->log);
 79        $this->assertContains($message, stream_get_contents($this->log));
 80    }
 81
 82    public function testAddWriterAddsMultipleWriters()
 83    {
 84        $logger = new Zend_Log();
 85
 86        // create writers for two separate streams of temporary memory
 87        $log1    = fopen('php://memory', 'w+');
 88        $writer1 = new Zend_Log_Writer_Stream($log1);
 89        $log2    = fopen('php://memory', 'w+');
 90        $writer2 = new Zend_Log_Writer_Stream($log2);
 91
 92        // add the writers
 93        $logger->addWriter($writer1);
 94        $logger->addWriter($writer2);
 95
 96        // log to both writers
 97        $logger->log($message = 'message-sent-to-both-logs', Zend_Log::INFO);
 98
 99        // verify both writers were called by the logger
100        rewind($log1);
101        $this->assertContains($message, stream_get_contents($log1));
102        rewind($log2);
103        $this->assertContains($message, stream_get_contents($log2));
104
105        // prove the two memory streams are different
106        // and both writers were indeed called
107        fwrite($log1, 'foo');
108        $this->assertNotEquals(ftell($log1), ftell($log2));
109    }
110
111    public function testLoggerThrowsWhenNoWriters()
112    {
113        $logger = new Zend_Log();
114        try {
115            $logger->log('message', Zend_Log::INFO);
116            $this->fail();
117        } catch (Zend_Log_Exception $e) {
118            $this->assertRegexp('/no writer/i', $e->getMessage());
119        }
120    }
121
122    public function testDestructorCallsShutdownOnEachWriter()
123    {
124        $writer1 = new Zend_Log_Writer_Mock();
125        $writer2 = new Zend_Log_Writer_Mock();
126
127        $logger = new Zend_Log();
128        $logger->addWriter($writer1);
129        $logger->addWriter($writer2);
130
131        $this->assertFalse($writer1->shutdown);
132        $this->assertFalse($writer2->shutdown);
133
134        $logger = null;
135
136        $this->assertTrue($writer1->shutdown);
137        $this->assertTrue($writer2->shutdown);
138    }
139
140    // Priorities
141
142    public function testLogThrowsOnBadLogPriority()
143    {
144        $logger = new Zend_Log($this->writer);
145        try {
146            $logger->log('foo', 42);
147            $this->fail();
148        } catch (Exception $e) {
149            $this->assertType('Zend_Log_Exception', $e);
150            $this->assertRegExp('/bad log priority/i', $e->getMessage());
151        }
152    }
153
154    public function testLogThrough__callThrowsOnBadLogPriority()
155    {
156        $logger = new Zend_Log($this->writer);
157        try {
158            $logger->nonexistantPriority('');
159            $this->fail();
160        } catch (Exception $e) {
161            $this->assertType('Zend_Log_Exception', $e);
162            $this->assertRegExp('/bad log priority/i', $e->getMessage());
163        }
164    }
165
166    public function testAddingPriorityThrowsWhenOverridingBuiltinLogPriority()
167    {
168        try {
169            $logger = new Zend_Log($this->writer);
170            $logger->addPriority('BOB', 0);
171            $this->fail();
172        } catch (Exception $e) {
173            $this->assertType('Zend_Log_Exception', $e);
174            $this->assertRegExp('/existing priorities/i', $e->getMessage());
175        }
176
177    }
178
179    public function testAddLogPriority()
180    {
181        $logger = new Zend_Log($this->writer);
182        $logger->addPriority('EIGHT', $priority = 8);
183
184        $logger->eight($message = 'eight message');
185
186        rewind($this->log);
187        $logdata = stream_get_contents($this->log);
188        $this->assertContains((string)$priority, $logdata);
189        $this->assertContains($message, $logdata);
190    }
191
192    // Fields
193
194    public function testLogWritesStandardFields() {
195        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
196        $logger->info('foo');
197
198        $this->assertEquals(1, count($mock->events));
199        $event = array_shift($mock->events);
200
201        $standardFields = array_flip(array('timestamp', 'priority', 'priorityName', 'message'));
202        $this->assertEquals(array(), array_diff_key($event, $standardFields));
203    }
204
205    public function testLogWritesAndOverwritesExtraFields() {
206        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
207        $logger->setEventItem('foo', 42);
208        $logger->setEventItem($field = 'bar', $value = 43);
209        $logger->info('foo');
210
211        $this->assertEquals(1, count($mock->events));
212        $event = array_shift($mock->events);
213
214        $this->assertTrue(array_key_exists($field, $event));
215        $this->assertEquals($value, $event[$field]);
216    }
217
218    /**
219     * @group ZF-8491
220     */
221    public function testLogAcceptsExtrasParameterAsArrayAndPushesIntoEvent()
222    {
223        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
224        $logger->info('foo', array('content' => 'nonesuch'));
225        $event = array_shift($mock->events);
226        $this->assertContains('content', array_keys($event));
227        $this->assertEquals('nonesuch', $event['content']);
228    }
229
230    /**
231     * @group ZF-8491
232     */
233    public function testLogNumericKeysInExtrasArrayArePassedToInfoKeyOfEvent()
234    {
235        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
236        $logger->info('foo', array('content' => 'nonesuch', 'bar'));
237        $event = array_shift($mock->events);
238        $this->assertContains('content', array_keys($event));
239        $this->assertContains('info', array_keys($event));
240        $this->assertContains('bar', $event['info']);
241    }
242
243    /**
244     * @group ZF-8491
245     */
246    public function testLogAcceptsExtrasParameterAsScalarAndAddsAsInfoKeyToEvent()
247    {
248        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
249        $logger->info('foo', 'nonesuch');
250        $event = array_shift($mock->events);
251        $this->assertContains('info', array_keys($event));
252        $info = $event['info'];
253        $this->assertContains('nonesuch', $info);
254    }
255
256    // Factory
257
258    public function testLogConstructFromConfigStream()
259    {
260        $cfg = array('log' => array('memory' => array(
261            'writerName'      => "Stream",
262            'writerNamespace' => "Zend_Log_Writer",
263            'writerParams'    => array(
264                'stream'      => "php://memory"
265            )
266        )));
267
268        $logger = Zend_Log::factory($cfg['log']);
269        $this->assertTrue($logger instanceof Zend_Log);
270    }
271
272    public function testLogConstructFromConfigStreamAndFilter()
273    {
274        $cfg = array('log' => array('memory' => array(
275            'writerName'      => "Stream",
276            'writerNamespace' => "Zend_Log_Writer",
277            'writerParams'    => array(
278                'stream'      => "php://memory"
279            ),
280            'filterName'   => "Priority",
281            'filterParams' => array(
282                'priority' => "Zend_Log::CRIT",
283                'operator' => "<="
284             ),
285        )));
286
287        $logger = Zend_Log::factory($cfg['log']);
288        $this->assertTrue($logger instanceof Zend_Log);
289    }
290
291    public function testFactoryUsesNameAndNamespaceWithoutModifications()
292    {
293        $cfg = array('log' => array('memory' => array(
294            'writerName'      => "ZendMonitor",
295            'writerNamespace' => "Zend_Log_Writer",
296        )));
297
298        $logger = Zend_Log::factory($cfg['log']);
299        $this->assertTrue($logger instanceof Zend_Log);
300    }
301
302    /**
303     * @group ZF-9192
304     */
305    public function testUsingWithErrorHandler()
306    {
307        $writer = new Zend_Log_Writer_Mock();
308
309        $logger = new Zend_Log();
310        $logger->addWriter($writer);
311        $this->errWriter = $writer;
312
313
314        $oldErrorLevel = error_reporting();
315
316        $this->expectingLogging = true;
317        error_reporting(E_ALL | E_STRICT);
318
319        $oldHandler = set_error_handler(array($this, 'verifyHandlerData'));
320        $logger->registerErrorHandler();
321
322        trigger_error("Testing notice shows up in logs", E_USER_NOTICE);
323        trigger_error("Testing warning shows up in logs", E_USER_WARNING);
324        trigger_error("Testing error shows up in logs", E_USER_ERROR);
325
326        $this->expectingLogging = false;
327        error_reporting(0);
328
329        trigger_error("Testing notice misses logs", E_USER_NOTICE);
330        trigger_error("Testing warning misses logs", E_USER_WARNING);
331        trigger_error("Testing error misses logs", E_USER_ERROR);
332
333        restore_error_handler(); // Pop off the Logger
334        restore_error_handler(); // Pop off the verifyHandlerData
335        error_reporting($oldErrorLevel); // Restore original reporting level
336        unset($this->errWriter);
337    }
338
339    /**
340     * @group ZF-9192
341     * Used by testUsingWithErrorHandler -
342     * verifies that the data written to the original logger is the same as the data written in Zend_Log
343     */
344    public function verifyHandlerData($errno, $errstr, $errfile, $errline, $errcontext)
345    {
346        if ($this->expectingLogging) {
347            $this->assertFalse(empty($this->errWriter->events));
348            $event = array_shift($this->errWriter->events);
349            $this->assertEquals($errstr, $event['message']);
350            $this->assertEquals($errno, $event['errno']);
351            $this->assertEquals($errfile, $event['file']);
352            $this->assertEquals($errline, $event['line']);
353        } else {
354            $this->assertTrue(empty($this->errWriter->events));
355        }
356    }
357
358    /**
359     * @group ZF-9870
360     */
361    public function testSetAndGetTimestampFormat()
362    {
363        $logger = new Zend_Log($this->writer);
364        $this->assertEquals('c', $logger->getTimestampFormat());
365        $this->assertSame($logger, $logger->setTimestampFormat('Y-m-d H:i:s'));
366        $this->assertEquals('Y-m-d H:i:s', $logger->getTimestampFormat());
367    }
368
369    /**
370     * @group ZF-9870
371     */
372    public function testLogWritesWithModifiedTimestampFormat()
373    {
374        $logger = new Zend_Log($this->writer);
375        $logger->setTimestampFormat('Y-m-d');
376        $logger->debug('ZF-9870');
377        rewind($this->log);
378        $message = stream_get_contents($this->log);
379        $this->assertEquals(date('Y-m-d'), substr($message, 0, 10));
380    }
381
382    /**
383     * @group ZF-9955
384     */
385    public function testExceptionConstructWriterFromConfig()
386    {
387        try {
388            $logger = new Zend_Log();
389            $writer = array('writerName' => 'NotExtendedWriterAbstract');
390            $logger->addWriter($writer);
391        } catch (Exception $e) {
392            $this->assertType('Zend_Log_Exception', $e);
393            $this->assertRegExp('#^(Zend_Log_Writer_NotExtendedWriterAbstract|The\sspecified\swriter)#', $e->getMessage());
394        }
395    }
396
397    /**
398     * @group ZF-9956
399     */
400    public function testExceptionConstructFilterFromConfig()
401    {
402        try {
403            $logger = new Zend_Log();
404            $filter = array('filterName' => 'NotImplementsFilterInterface');
405            $logger->addFilter($filter);
406        } catch (Exception $e) {
407            $this->assertType('Zend_Log_Exception', $e);
408            $this->assertRegExp('#^(Zend_Log_Filter_NotImplementsFilterInterface|The\sspecified\sfilter)#', $e->getMessage());
409        }
410    }
411
412    /**
413     * @group ZF-8953
414     */
415    public function testFluentInterface()
416    {
417        $logger   = new Zend_Log();
418        $instance = $logger->addPriority('all', 8)
419                           ->addFilter(1)
420                           ->addWriter(array('writerName' => 'Null'))
421                           ->setEventItem('os', PHP_OS);
422
423        $this->assertTrue($instance instanceof Zend_Log);
424    }
425
426    /**
427     * @group ZF-10170
428     */
429    public function testPriorityDuplicates()
430    {
431        $logger   = new Zend_Log();
432        $mock     = new Zend_Log_Writer_Mock();
433        $logger->addWriter($mock);
434        try {
435            $logger->addPriority('emerg', 8);
436            $this->fail();
437        } catch(Exception $e) {
438            $this->assertType('Zend_Log_Exception', $e);
439            $this->assertEquals('Existing priorities cannot be overwritten', $e->getMessage());
440        }
441
442        try {
443            $logger->log('zf10170', 0);
444            $logger->log('clone zf10170', 8);
445            $this->fail();
446        } catch (Exception $e) {
447            $this->assertType('Zend_Log_Exception', $e);
448            $this->assertEquals('Bad log priority', $e->getMessage());
449        }
450        $this->assertEquals(0, $mock->events[0]['priority']);
451        $this->assertEquals('EMERG', $mock->events[0]['priorityName']);
452        $this->assertFalse(array_key_exists(1, $mock->events));
453    }
454
455    /**
456     * @group ZF-9176
457     */
458    public function testLogConstructFromConfigFormatter()
459    {
460        $config = array(
461        	'log' => array(
462	        	'test' => array(
463		            'writerName'    => 'Mock',
464		            'formatterName' => 'Simple',
465		            'formatterParams' => array(
466		                'format' => '%timestamp% (%priorityName%): %message%'
467		            )
468	            )
469            )
470        );
471
472        $logger = Zend_Log::factory($config['log']);
473        $logger->log('custom message', Zend_Log::INFO);
474    }
475
476	/**
477     * @group ZF-9176
478     */
479    public function testLogConstructFromConfigCustomFormatter()
480    {
481        $config = array(
482        	'log' => array(
483	        	'test' => array(
484		            'writerName'    => 'Mock',
485		            'formatterName' => 'Mock',
486        			'formatterNamespace' => 'Custom_Formatter'
487	            )
488            )
489        );
490
491        $logger = Zend_Log::factory($config['log']);
492        $logger->log('custom message', Zend_Log::INFO);
493    }
494
495    /**
496     * @group ZF-10990
497     */
498    public function testFactoryShouldSetTimestampFormat()
499    {
500        $config = array(
501            'timestampFormat' => 'Y-m-d',
502            'mock' => array(
503                'writerName' => 'Mock'
504            )
505        );
506        $logger = Zend_Log::factory($config);
507
508        $this->assertEquals('Y-m-d', $logger->getTimestampFormat());
509    }
510
511    /**
512     * @group ZF-10990
513     */
514    public function testFactoryShouldKeepDefaultTimestampFormat()
515    {
516        $config = array(
517            'timestampFormat' => '',
518            'mock' => array(
519                'writerName' => 'Mock'
520            )
521        );
522        $logger = Zend_Log::factory($config);
523
524        $this->assertEquals('c', $logger->getTimestampFormat());
525    }
526}
527
528class Zend_Log_Writer_NotExtendedWriterAbstract implements Zend_Log_FactoryInterface
529{
530    public static function factory($config)
531    {
532    }
533}
534
535class Zend_Log_Filter_NotImplementsFilterInterface implements Zend_Log_FactoryInterface
536{
537    public static function factory($config)
538    {
539    }
540}
541
542class Custom_Formatter_Mock extends Zend_Log_Formatter_Abstract
543{
544    public static function factory($config)
545    {
546        return new self;
547    }
548
549    public function format($event)
550    {
551    }
552}
553
554if (PHPUnit_MAIN_METHOD == 'Zend_Log_LogTest::main') {
555    Zend_Log_LogTest::main();
556}