core /.dev/tests/PHPUnit/TestCase.php

Language PHP Lines 563
MD5 Hash ffe16cc81d5bd97cd70151914402b2ed
Repository https://github.com/istran/core.git View Raw File
  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
557
558
559
560
561
<?php
// vim: set ts=4 sw=4 sts=4 et:

/**
 * Base class for all LiteCommerce tests
 *  
 * @category   LiteCommerce_Tests
 * @package    LiteCommerce_Tests
 * @subpackage Main
 * @author     Ruslan R. Fazliev <rrf@x-cart.com> 
 * @copyright  Copyright (c) 2009 Ruslan R. Fazliev <rrf@x-cart.com>
 * @license    http://www.x-cart.com/license.php LiteCommerce license
 * @version    GIT: $Id: 904d219932da59f6b64462264f8c7fd7294e34f8 $
 * @link       http://www.x-cart.com/
 * @see        ____file_see____
 * @since      1.0.0
 */

abstract class XLite_Tests_TestCase extends PHPUnit_Framework_TestCase
{
    /**
     * Prefix for all classes with test cases
     */
    const CLASS_PREFIX = 'XLite_Tests_';

    const IMAP_BOX  = '{mail.crtdev.local:143/imap/tls/novalidate-cert}INBOX';
    const IMAP_USER = 'rnd_tester';
    const IMAP_PASS = '7qnDjKzVoc6Qcb7b';


    /**
     * Tests range 
     * 
     * @var    array
     * @access public
     * @see    ____var_see____
     * @since  3.0.0
     */
    public static $testsRange = array();

    /**
     * Message length 
     * 
     * @var    integer
     * @access protected
     * @see    ____var_see____
     * @since  3.0.0
     */
    protected static $messageLength = 70;

    /**
     * IMAP mailbox resource
     * 
     * @var    resource
     * @access private
     * @see    ____var_see____
     * @since  1.0.0
     */
    private $mailBox = null;

    /**
     * last message counter in IMAP mailbox
     * 
     * @var    float
     * @access private
     * @see    ____var_see____
     * @since  1.0.0
     */
    private $lastMessage = 0;

    /**
     * Parameters registering when test starts
     * 
     * @var    array
     * @access protected
     * @see    ____var_see____
     * @since  1.0.0
     */
    protected $start = array('time' => 0, 'memory' => 0);

    /**
     * Parameters registering when test ends
     *
     * @var    array
     * @access protected
     * @see    ____var_see____
     * @since  1.0.0
     */
    protected $end = array('time' => 0, 'memory' => 0);

    /**
     * Return test execution time  
     * 
     * @return string
     * @access private
     * @see    ____func_see____
     * @since  1.0.0
     */
    private function getExecTime()
    {
        $time    = number_format($this->end['time'] - $this->start['time'], 4);
        $message = trim($this->getMessage('', get_called_class(), $this->name));

        if (strlen($message) > self::$messageLength) {
            self::$messageLength = strlen($message) + 1;
        }

        return sprintf('%\'.-' . self::$messageLength. 's', trim($message))
            . ' ' . sprintf('%8s', $time) . ' sec .....';
    }

    /**
     * Return memory used by test
     * 
     * @return string
     * @access private
     * @see    ____func_see____
     * @since  1.0.0
     */
    private function getMemoryUsage()
    {
        $memory = $this->end['memory'] - $this->start['memory'];
        if ($memory < 0) {
            $memory = 0;
        }

        return sprintf('%8s', number_format($memory / 1024, 2)) . ' Kb .....';
    }
    
    /**
     * Check if we need to construct/destruct application singleton
     * 
     * @param array $request request info
     *  
     * @return bool
     * @access private
     * @see    ____func_see____
     * @since  1.0.0
     */
    private function needAppInit(array $request = array())
    {
        if (empty($request)) {
            $request = $this->getRequest();
        }

        return $request['init_app'];
    }

    /**
     * Return message (common method)
     * 
     * @param string $message custom part of message
     * @param string $class   called class name
     * @param string $method  called method name
     *  
     * @return string
     * @access protected
     * @see    ____func_see____
     * @since  1.0.0
     */
    protected function getMessage($message, $class = '', $method = '')
    {
        // Full debag trace for called method
        $trace = debug_backtrace();
        $trace = $trace[1];

        // Retrieve class and method names
        $class = str_replace(self::CLASS_PREFIX, '', empty($class) ? $trace['class'] : $class);
        $method = lcfirst(str_replace('test', '', empty($method) ? $trace['function'] : $method));

        return $class . ' ' . '[' . $method . ']. ' . $message;
    }

    /**
     * Return data needed to start application.
     * Derived class can redefine this method.
     * It's possible to detect current test using the $this->name variable
     * 
     * @return array
     * @access protected
     * @see    ____func_see____
     * @since  1.0.0
     */
    protected function getRequest()
    {
        // Default request
        $request = array(
            'init_app'   => true,
            'method'     => 'GET',
            'controller' => true, // true - admin, false - customer
            'data'       => array(
                'target' => \XLite::TARGET_DEFAULT,
                'action' => '',
            ),
            'cookies'    => array(),
        );

        return $request;
    }

    /**
     * PHPUnit default function.
     * Redefine this method only if you really need to do so.
     * In any other cases redefine the getRequest() one
     * 
     * @return void
     * @access protected
     * @see    ____func_see____
     * @since  1.0.0
     */
    protected function setUp()
    {
        set_time_limit(0);

        $request = $this->getRequest();

        // This data will be parsed by Reqest/Router transports
        $GLOBALS['_SERVER']['REQUEST_METHOD'] = $request['method'];

        if (!empty($request['data'])) {
            $GLOBALS['_' . $request['method']] = $request['data'];
        }

        if (!empty($request['cookies'])) {
            $GLOBALS['_COOKIE'] = $request['cookies'];
        }

        // Instantiate singltons
        if ($this->needAppInit($request)) {
            $this->app = \XLite::getInstance()->run($request['controller']);
        }

        // Set customer skin
        \XLite\Model\Layout::getInstance()->setCustomerSkin();

        // Clear and restart (if need) entity manager
        \XLite\Core\Database::getEM()->clear();

        \XLite\Core\Database::getEM()->getConnection()->executeQuery('SET autocommit = 1');

        try {
            \XLite\Core\Database::getEM()->flush();
        } catch (\Doctrine\ORM\ORMException $e) {
            if ('The EntityManager is closed.' == $e->getMessage()) {
                \XLite\Core\Database::getInstance()->startEntityManager();
                xlite(true);

            } else {
                throw $e;
            }
        }

        \XLite\Core\Session::getInstance()->restart();

        // Print new line between classes
        $currentClass = get_called_class();
        if (empty(XLite_Tests_TestSuite::$currentClass) || $currentClass !== XLite_Tests_TestSuite::$currentClass) {
            echo PHP_EOL;
            XLite_Tests_TestSuite::$currentClass = $currentClass;
        }

        // Memory usage
        $this->start['memory'] = memory_get_usage();
        $this->end['memory']   = 0;

        // Timing
        $this->start['time'] = microtime(true);
    }

    /**
     * PHPUnit default function.
     * It's not recommended to redefine this method
     * 
     * @return void
     * @access protected
     * @see    ____func_see____
     * @since  1.0.0
     */
    protected function tearDown()
    {
        // Timing
        $this->end['time'] = microtime(true);
        
//        if ($this->needAppInit()) {
//            \XLite\Core\Converter::getInstance()->__destruct();
//            \XLite\Core\Database::getInstance()->__destruct();
//            $this->app->__destruct();
//        }

        // Memory usage
        $this->end['memory'] += memory_get_usage();

        echo PHP_EOL . $this->getExecTime();
        echo $this->getMemoryUsage();

        $this->writeMetricLog();
    }

    /**
     * Write metric log 
     * 
     * @return void
     * @access private
     * @see    ____func_see____
     * @since  3.0.0
     */
    private function writeMetricLog()
    {
        $trace = debug_backtrace();
        $trace = $trace[0];

        $class = get_called_class();
        $method = $this->name;
        $class = str_replace(self::CLASS_PREFIX, '', empty($class) ? $trace['class'] : $class);
        $method = lcfirst(str_replace('test', '', empty($method) ? $trace['function'] : $method));

        $time = intval(round($this->end['time'] - $this->start['time'], 6) * 1000000);
        $memory = max($this->end['memory'] - $this->start['memory'], 0);

        XLite_Tests_MetricWriter::write($class, $method, $time, $memory);
    }

    /**
     * Check exception code 
     * 
     * @param function $func    Function
     * @param string   $class   Exception class name
     * @param string   $message Exception message
     *  
     * @return void
     * @access protected
     * @see    ____func_see____
     * @since  1.0.0
     */
    protected function checkException($func, $message, $class = '\Exception')
    {
        try {

            $func();
            $this->fail('Exception "' . $message . '" was not thrown');

        } catch (\Exception $exception) {

            $this->assertEquals($message, $exception->getMessage(), 'Check exception : "' . $message . '" message not found');
            $this->assertTrue($exception instanceof $class, 'Check exception : "' . $class . '" exception class not equal');

        } 
    }

    /**
     * Check warning 
     * 
     * @param mixed  $func      Closure (function) or list of closures
     * @param string $errorCode Error code
     *  
     * @return void
     * @access protected
     * @see    ____func_see____
     * @since  3.0.0
     */
    protected function checkWarning($func, $errorCode)
    {
        if ($this->isFunction($func)) {
            $func = array($func);

        } elseif (is_array($func)) {
            foreach ($func as $k => $v) {
                if (!$this->isFunction($v)) {
                    unset($func[$k]);
                }
            }
        }

        if (!is_array($func) || count($func) == 0) {
            $this->fail($this->getMessage('Argument $func is not valid'));
        }

        foreach ($func as $i => $f) {

            try {

                $f();

            } catch (PHPUnit_Framework_Error_Warning $exception) {

                $message = $this->getMessage('Check for the "' . $errorCode . '" exception:');
                $this->assertEquals($errorCode, substr($exception->getMessage(), 0, strlen($errorCode)), $message);
                continue;
            } 

            $this->fail(
                $this->getMessage(
                    'The "' . $errorCode . '" exception was not thrown'
                    . (count($func) > 1 ? (' (function #' . ($i + 1) .')') : '')
                )
            );
        }

    }

    /**
     * Check - is fuunction (closure) or not
     * 
     * @param \Closure $func Function
     *  
     * @return boolean
     * @access protected
     * @see    ____func_see____
     * @since  3.0.0
     */
    protected function isFunction($func) {
        return is_object($func) && get_class($func) == 'Closure';
    }

    /**
     * Set start of emails counter
     * 
     * @return void
     * @access public
     * @see    ____func_see____
     * @since  1.0.0
     */
    public function startCheckingMail()
    {
        $this->initMailBox();

        $mc = imap_check($this->mailBox);

        $this->lastMessage = $mc->Nmsgs;

        $this->closeMailBox();
    }

    /**
     * Init mailbox
     * 
     * @return void
     * @access private
     * @see    ____func_see____
     * @since  1.0.0
     */
    private function initMailBox()
    {
        if (
            is_null($this->mailBox) 
            || false === $this->mailBox
        ) {

            $this->mailBox = imap_open(self::IMAP_BOX, self::IMAP_USER, self::IMAP_PASS);

        }
    }

    /**
     * close IMAP mailbox
     * 
     * @return void
     * @access private
     * @see    ____func_see____
     * @since  1.0.0
     */
    private function closeMailBox()
    {
        imap_close($this->mailBox);

        $this->mailBox = null;
    }

    /**
     * check if there are new emails and fetch them
     * 
     * @return array array of emails
     * @access public
     * @see    ____func_see____
     * @since  1.0.0
     */
    public function finishCheckingMail()
    {
        $this->initMailBox();

        $mc = imap_check($this->mailBox);

        $emails = array();

        if ($mc->Nmsgs > $this->lastMessage) {

            for ($i = $this->lastMessage + 1; $i <= $mc->Nmsgs; $i++) {

                $header = @imap_fetchbody($this->mailBox, $i, '0');
                $body   = @imap_fetchbody($this->mailBox, $i, '1');

                $emails[] = array(
                    'header' => $header,
                    'body'   => $body,
                );
            }

            $this->lastMessage = $mc->Nmsgs;
        }

        $this->closeMailBox();

        return $emails;
    }

    /**
     * Do SQL query 
     * 
     * @param sql $sql SQL query
     *  
     * @return void
     * @access protected
     * @see    ____func_see____
     * @since  3.0.0
     */
    protected function query($sql)
    {
        \XLite\Core\Database::getEM()->getConnection()->executeQuery($sql, array());
    }

    /**
     * Constructs a test case with the given name.
     *
     * @param  string $name
     * @param  array  $data
     * @param  string $dataName
     */
    public function __construct($name = NULL, array $data = array(), $dataName = '')
    {
        parent::__construct($name, $data, $dataName);
    }

    /**
     * Run test 
     * 
     * @return void
     * @access protected
     * @see    ____func_see____
     * @since  3.0.0
     */
    protected function runTest()
    {
        $shortName = lcfirst(substr($this->name, 4));
        if (self::$testsRange && !in_array($shortName, self::$testsRange)) {
            $this->markTestSkipped();

        } else {
            parent::runTest();
        }
    }

    protected function getProduct()
    {
        return \XLite\Core\Database::getRepo('XLite\Model\Product')->findOneByEnabled(true);
    }

    protected function getProductBySku($sku)
    {
        return \XLite\Core\Database::getRepo('XLite\Model\Product')->findOneBy(array('sku' => $sku));
    }
}
Back to Top