campus /tests/Zend/Log/LogTest.php

Language PHP Lines 556
MD5 Hash f129aceef6e7dad1be1dc38d46560f2a Estimated Cost $9,890 (why?)
Repository https://bitbucket.org/ksekar/campus.git View Raw File View Project SPDX
  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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Log
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: LogTest.php 24594 2012-01-05 21:27:01Z matthew $
 */

if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'Zend_Log_LogTest::main');
}

/** Zend_Log */
require_once 'Zend/Log.php';

/** Zend_Log_Writer_Mock */
require_once 'Zend/Log/Writer/Mock.php';

/** Zend_Log_Writer_Stream */
require_once 'Zend/Log/Writer/Stream.php';

/** Zend_Log_FactoryInterface */
require_once 'Zend/Log/FactoryInterface.php';

/**
 * @category   Zend
 * @package    Zend_Log
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Log
 */
class Zend_Log_LogTest extends PHPUnit_Framework_TestCase
{
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite(__CLASS__);
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function setUp()
    {
        $this->log = fopen('php://memory', 'w+');
        $this->writer = new Zend_Log_Writer_Stream($this->log);
    }

    // Writers

    public function testWriterCanBeAddedWithConstructor()
    {
        $logger = new Zend_Log($this->writer);
        $logger->log($message = 'message-to-log', Zend_Log::INFO);

        rewind($this->log);
        $this->assertContains($message, stream_get_contents($this->log));
    }

    public function testAddWriter()
    {
        $logger = new Zend_Log();
        $logger->addWriter($this->writer);
        $logger->log($message = 'message-to-log', Zend_Log::INFO);

        rewind($this->log);
        $this->assertContains($message, stream_get_contents($this->log));
    }

    public function testAddWriterAddsMultipleWriters()
    {
        $logger = new Zend_Log();

        // create writers for two separate streams of temporary memory
        $log1    = fopen('php://memory', 'w+');
        $writer1 = new Zend_Log_Writer_Stream($log1);
        $log2    = fopen('php://memory', 'w+');
        $writer2 = new Zend_Log_Writer_Stream($log2);

        // add the writers
        $logger->addWriter($writer1);
        $logger->addWriter($writer2);

        // log to both writers
        $logger->log($message = 'message-sent-to-both-logs', Zend_Log::INFO);

        // verify both writers were called by the logger
        rewind($log1);
        $this->assertContains($message, stream_get_contents($log1));
        rewind($log2);
        $this->assertContains($message, stream_get_contents($log2));

        // prove the two memory streams are different
        // and both writers were indeed called
        fwrite($log1, 'foo');
        $this->assertNotEquals(ftell($log1), ftell($log2));
    }

    public function testLoggerThrowsWhenNoWriters()
    {
        $logger = new Zend_Log();
        try {
            $logger->log('message', Zend_Log::INFO);
            $this->fail();
        } catch (Zend_Log_Exception $e) {
            $this->assertRegexp('/no writer/i', $e->getMessage());
        }
    }

    public function testDestructorCallsShutdownOnEachWriter()
    {
        $writer1 = new Zend_Log_Writer_Mock();
        $writer2 = new Zend_Log_Writer_Mock();

        $logger = new Zend_Log();
        $logger->addWriter($writer1);
        $logger->addWriter($writer2);

        $this->assertFalse($writer1->shutdown);
        $this->assertFalse($writer2->shutdown);

        $logger = null;

        $this->assertTrue($writer1->shutdown);
        $this->assertTrue($writer2->shutdown);
    }

    // Priorities

    public function testLogThrowsOnBadLogPriority()
    {
        $logger = new Zend_Log($this->writer);
        try {
            $logger->log('foo', 42);
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('/bad log priority/i', $e->getMessage());
        }
    }

    public function testLogThrough__callThrowsOnBadLogPriority()
    {
        $logger = new Zend_Log($this->writer);
        try {
            $logger->nonexistantPriority('');
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('/bad log priority/i', $e->getMessage());
        }
    }

    public function testAddingPriorityThrowsWhenOverridingBuiltinLogPriority()
    {
        try {
            $logger = new Zend_Log($this->writer);
            $logger->addPriority('BOB', 0);
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('/existing priorities/i', $e->getMessage());
        }

    }

    public function testAddLogPriority()
    {
        $logger = new Zend_Log($this->writer);
        $logger->addPriority('EIGHT', $priority = 8);

        $logger->eight($message = 'eight message');

        rewind($this->log);
        $logdata = stream_get_contents($this->log);
        $this->assertContains((string)$priority, $logdata);
        $this->assertContains($message, $logdata);
    }

    // Fields

    public function testLogWritesStandardFields() {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo');

        $this->assertEquals(1, count($mock->events));
        $event = array_shift($mock->events);

        $standardFields = array_flip(array('timestamp', 'priority', 'priorityName', 'message'));
        $this->assertEquals(array(), array_diff_key($event, $standardFields));
    }

    public function testLogWritesAndOverwritesExtraFields() {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->setEventItem('foo', 42);
        $logger->setEventItem($field = 'bar', $value = 43);
        $logger->info('foo');

        $this->assertEquals(1, count($mock->events));
        $event = array_shift($mock->events);

        $this->assertTrue(array_key_exists($field, $event));
        $this->assertEquals($value, $event[$field]);
    }

    /**
     * @group ZF-8491
     */
    public function testLogAcceptsExtrasParameterAsArrayAndPushesIntoEvent()
    {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo', array('content' => 'nonesuch'));
        $event = array_shift($mock->events);
        $this->assertContains('content', array_keys($event));
        $this->assertEquals('nonesuch', $event['content']);
    }

    /**
     * @group ZF-8491
     */
    public function testLogNumericKeysInExtrasArrayArePassedToInfoKeyOfEvent()
    {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo', array('content' => 'nonesuch', 'bar'));
        $event = array_shift($mock->events);
        $this->assertContains('content', array_keys($event));
        $this->assertContains('info', array_keys($event));
        $this->assertContains('bar', $event['info']);
    }

    /**
     * @group ZF-8491
     */
    public function testLogAcceptsExtrasParameterAsScalarAndAddsAsInfoKeyToEvent()
    {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo', 'nonesuch');
        $event = array_shift($mock->events);
        $this->assertContains('info', array_keys($event));
        $info = $event['info'];
        $this->assertContains('nonesuch', $info);
    }

    // Factory

    public function testLogConstructFromConfigStream()
    {
        $cfg = array('log' => array('memory' => array(
            'writerName'      => "Stream",
            'writerNamespace' => "Zend_Log_Writer",
            'writerParams'    => array(
                'stream'      => "php://memory"
            )
        )));

        $logger = Zend_Log::factory($cfg['log']);
        $this->assertTrue($logger instanceof Zend_Log);
    }

    public function testLogConstructFromConfigStreamAndFilter()
    {
        $cfg = array('log' => array('memory' => array(
            'writerName'      => "Stream",
            'writerNamespace' => "Zend_Log_Writer",
            'writerParams'    => array(
                'stream'      => "php://memory"
            ),
            'filterName'   => "Priority",
            'filterParams' => array(
                'priority' => "Zend_Log::CRIT",
                'operator' => "<="
             ),
        )));

        $logger = Zend_Log::factory($cfg['log']);
        $this->assertTrue($logger instanceof Zend_Log);
    }

    public function testFactoryUsesNameAndNamespaceWithoutModifications()
    {
        $cfg = array('log' => array('memory' => array(
            'writerName'      => "ZendMonitor",
            'writerNamespace' => "Zend_Log_Writer",
        )));

        $logger = Zend_Log::factory($cfg['log']);
        $this->assertTrue($logger instanceof Zend_Log);
    }

    /**
     * @group ZF-9192
     */
    public function testUsingWithErrorHandler()
    {
        $writer = new Zend_Log_Writer_Mock();

        $logger = new Zend_Log();
        $logger->addWriter($writer);
        $this->errWriter = $writer;


        $oldErrorLevel = error_reporting();

        $this->expectingLogging = true;
        error_reporting(E_ALL | E_STRICT);

        $oldHandler = set_error_handler(array($this, 'verifyHandlerData'));
        $logger->registerErrorHandler();

        trigger_error("Testing notice shows up in logs", E_USER_NOTICE);
        trigger_error("Testing warning shows up in logs", E_USER_WARNING);
        trigger_error("Testing error shows up in logs", E_USER_ERROR);

        $this->expectingLogging = false;
        error_reporting(0);

        trigger_error("Testing notice misses logs", E_USER_NOTICE);
        trigger_error("Testing warning misses logs", E_USER_WARNING);
        trigger_error("Testing error misses logs", E_USER_ERROR);

        restore_error_handler(); // Pop off the Logger
        restore_error_handler(); // Pop off the verifyHandlerData
        error_reporting($oldErrorLevel); // Restore original reporting level
        unset($this->errWriter);
    }

    /**
     * @group ZF-9192
     * Used by testUsingWithErrorHandler -
     * verifies that the data written to the original logger is the same as the data written in Zend_Log
     */
    public function verifyHandlerData($errno, $errstr, $errfile, $errline, $errcontext)
    {
        if ($this->expectingLogging) {
            $this->assertFalse(empty($this->errWriter->events));
            $event = array_shift($this->errWriter->events);
            $this->assertEquals($errstr, $event['message']);
            $this->assertEquals($errno, $event['errno']);
            $this->assertEquals($errfile, $event['file']);
            $this->assertEquals($errline, $event['line']);
        } else {
            $this->assertTrue(empty($this->errWriter->events));
        }
    }

    /**
     * @group ZF-9870
     */
    public function testSetAndGetTimestampFormat()
    {
        $logger = new Zend_Log($this->writer);
        $this->assertEquals('c', $logger->getTimestampFormat());
        $this->assertSame($logger, $logger->setTimestampFormat('Y-m-d H:i:s'));
        $this->assertEquals('Y-m-d H:i:s', $logger->getTimestampFormat());
    }

    /**
     * @group ZF-9870
     */
    public function testLogWritesWithModifiedTimestampFormat()
    {
        $logger = new Zend_Log($this->writer);
        $logger->setTimestampFormat('Y-m-d');
        $logger->debug('ZF-9870');
        rewind($this->log);
        $message = stream_get_contents($this->log);
        $this->assertEquals(date('Y-m-d'), substr($message, 0, 10));
    }

    /**
     * @group ZF-9955
     */
    public function testExceptionConstructWriterFromConfig()
    {
        try {
            $logger = new Zend_Log();
            $writer = array('writerName' => 'NotExtendedWriterAbstract');
            $logger->addWriter($writer);
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('#^(Zend_Log_Writer_NotExtendedWriterAbstract|The\sspecified\swriter)#', $e->getMessage());
        }
    }

    /**
     * @group ZF-9956
     */
    public function testExceptionConstructFilterFromConfig()
    {
        try {
            $logger = new Zend_Log();
            $filter = array('filterName' => 'NotImplementsFilterInterface');
            $logger->addFilter($filter);
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('#^(Zend_Log_Filter_NotImplementsFilterInterface|The\sspecified\sfilter)#', $e->getMessage());
        }
    }

    /**
     * @group ZF-8953
     */
    public function testFluentInterface()
    {
        $logger   = new Zend_Log();
        $instance = $logger->addPriority('all', 8)
                           ->addFilter(1)
                           ->addWriter(array('writerName' => 'Null'))
                           ->setEventItem('os', PHP_OS);

        $this->assertTrue($instance instanceof Zend_Log);
    }

    /**
     * @group ZF-10170
     */
    public function testPriorityDuplicates()
    {
        $logger   = new Zend_Log();
        $mock     = new Zend_Log_Writer_Mock();
        $logger->addWriter($mock);
        try {
            $logger->addPriority('emerg', 8);
            $this->fail();
        } catch(Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertEquals('Existing priorities cannot be overwritten', $e->getMessage());
        }

        try {
            $logger->log('zf10170', 0);
            $logger->log('clone zf10170', 8);
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertEquals('Bad log priority', $e->getMessage());
        }
        $this->assertEquals(0, $mock->events[0]['priority']);
        $this->assertEquals('EMERG', $mock->events[0]['priorityName']);
        $this->assertFalse(array_key_exists(1, $mock->events));
    }

    /**
     * @group ZF-9176
     */
    public function testLogConstructFromConfigFormatter()
    {
        $config = array(
        	'log' => array(
	        	'test' => array(
		            'writerName'    => 'Mock',
		            'formatterName' => 'Simple',
		            'formatterParams' => array(
		                'format' => '%timestamp% (%priorityName%): %message%'
		            )
	            )
            )
        );

        $logger = Zend_Log::factory($config['log']);
        $logger->log('custom message', Zend_Log::INFO);
    }

	/**
     * @group ZF-9176
     */
    public function testLogConstructFromConfigCustomFormatter()
    {
        $config = array(
        	'log' => array(
	        	'test' => array(
		            'writerName'    => 'Mock',
		            'formatterName' => 'Mock',
        			'formatterNamespace' => 'Custom_Formatter'
	            )
            )
        );

        $logger = Zend_Log::factory($config['log']);
        $logger->log('custom message', Zend_Log::INFO);
    }

    /**
     * @group ZF-10990
     */
    public function testFactoryShouldSetTimestampFormat()
    {
        $config = array(
            'timestampFormat' => 'Y-m-d',
            'mock' => array(
                'writerName' => 'Mock'
            )
        );
        $logger = Zend_Log::factory($config);

        $this->assertEquals('Y-m-d', $logger->getTimestampFormat());
    }

    /**
     * @group ZF-10990
     */
    public function testFactoryShouldKeepDefaultTimestampFormat()
    {
        $config = array(
            'timestampFormat' => '',
            'mock' => array(
                'writerName' => 'Mock'
            )
        );
        $logger = Zend_Log::factory($config);

        $this->assertEquals('c', $logger->getTimestampFormat());
    }
}

class Zend_Log_Writer_NotExtendedWriterAbstract implements Zend_Log_FactoryInterface
{
    public static function factory($config)
    {
    }
}

class Zend_Log_Filter_NotImplementsFilterInterface implements Zend_Log_FactoryInterface
{
    public static function factory($config)
    {
    }
}

class Custom_Formatter_Mock extends Zend_Log_Formatter_Abstract
{
    public static function factory($config)
    {
        return new self;
    }

    public function format($event)
    {
    }
}

if (PHPUnit_MAIN_METHOD == 'Zend_Log_LogTest::main') {
    Zend_Log_LogTest::main();
}
Back to Top