<?php
/**
 * core.framework
 *
 * @category   Core
 * @package    Core_Gearman
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license    proprietary
 */

/**
 * @category   Core
 * @package    Core_Gearman
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license    proprietary
 * @group      Core_Gearman
 * @group      gearman
 * @group      pecl
 */
class Core_Gearman_ClientTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Core_Gearman_Client
     */
    protected $_object;

    protected function setUp()
    {
        if (!extension_loaded('gearman')) {
            $this->markTestSkipped('Core_Gearman_Client requires "gearman" PECL loaded');
        }
        $this->_object = new Core_Gearman_Client;
    }

    /**
     * @covers Core_Gearman_Client::setClient
     * @covers Core_Gearman_Client::getClient
     */
    public function testCanSetAndGetClient()
    {
        $client = $this->getMock('GearmanClient');
        $this->_object->setClient($client);
        $this->assertEquals($client, $this->_object->getClient());
    }

    /**
     * @covers Core_Gearman_Client::getClient
     */
    public function testIfNoClientGivenWillCreateANewGearmanClientInstance()
    {
        $this->assertInstanceOf('GearmanClient', $this->_object->getClient());
    }

    /**
     * @covers Core_Gearman_Client::run
     * @covers Core_Gearman_Client::<protected>
     */
    public function testCanRunJob()
    {
        $this->_object->setClient($this->_mockClient('function'));
        $this->assertEquals('foo', $this->_object->run('function'));
    }

    /**
     * @covers Core_Gearman_Client::runBackground
     * @covers Core_Gearman_Client::<protected>
     */
    public function testCanRunBackgroundJob()
    {
        $this->_object->setClient($this->_mockClient('function', 'doBackground'));
        $this->assertEquals('foo', $this->_object->runBackground('function'));
    }

    /**
     * @covers Core_Gearman_Client::run
     * @covers Core_Gearman_Client::<protected>
     */
    public function testCanFailDuringRunningAJob()
    {
        $this->_object->setClient($this->_mockClient('function', 'doNormal', GEARMAN_WORK_FAIL));
        $this->assertEquals(GEARMAN_WORK_FAIL, $this->_object->run('function'));
    }

    protected function _mockClient($function, $method = 'doNormal', $return = 'foo', $data = null, $id = '')
    {
        $client = $this->getMock('GearmanClient', array($method, 'returnCode'));
        $client
            ->expects($this->once())
            ->method($method)
            ->with($this->equalTo($function), $this->equalTo(json_encode($data)), $this->equalTo($id))
            ->will($this->returnValue($return));

        $client
            ->expects($this->once())
            ->method('returnCode')
            ->will($this->returnValue(GEARMAN_SUCCESS));
        return $client;
    }
}
