<commit_before><?php
/**
 * PHPCI - Continuous Integration for PHP
 *
 * @copyright    Copyright 2013, Block 8 Limited.
 * @license        https://github.com/Block8/PHPCI/blob/master/LICENSE.md
 * @link            http://www.phptesting.org/
 */

namespace PHPCI\Plugin\Tests;

use PHPCI\Plugin\Email as EmailPlugin;


/**
 * Unit test for the PHPUnit plugin.
 * @author meadsteve
 */
class EmailTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var EmailPlugin $testedPhpUnit
     */
    protected $testedEmailPlugin;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject $mockCiBuilder
     */
    protected $mockCiBuilder;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject $mockBuild
     */
    protected $mockBuild;

    public function setUp()
    {
        $this->mockBuild = $this->getMock(
            '\PHPCI\Model\Build',
            array('getLog', 'getStatus'),
            array(),
            "mockBuild",
            false
        );

        $this->mockBuild->expects($this->any())
            ->method('getLog')
            ->will($this->returnValue("Build Log"));

        $this->mockBuild->expects($this->any())
            ->method('getStatus')
            ->will($this->returnValue(\PHPCI\Model\Build::STATUS_SUCCESS));

        $this->mockBuild->expects($this->any())
            ->method('getCommitterEmail')
            ->will($this->returnValue("<EMAIL>"));

        $this->mockCiBuilder = $this->getMock(
            '\PHPCI\Builder',
            array(
                'getSystemConfig',
                'getBuildProjectTitle',
                'getBuild',
                'log'
            ),
            array(),
            "mockBuilder_email",
            false
        );

        $this->mockCiBuilder->buildPath = "/";

        $this->mockCiBuilder->expects($this->any())
            ->method('getSystemConfig')
            ->with('phpci')
            ->will(
                $this->returnValue(
                    array(
                        'email_settings' => array(
                            'from_address' => "<EMAIL>"
                        )
                    )
                )
            );
        $this->mockCiBuilder->expects($this->any())
            ->method('getBuildProjectTitle')
            ->will($this->returnValue('Test-Project'));
        $this->mockCiBuilder->expects($this->any())
            ->method('getBuild')
            ->will($this->returnValue($this->mockBuild));

        $this->mockMailer = $this->getMock(
            '\Swift_Mailer',
            array('send'),
            array(),
            "mockMailer",
            false
        );

        $this->loadEmailPluginWithOptions();
    }

    protected function loadEmailPluginWithOptions($arrOptions = array())
    {
        $this->testedEmailPlugin = new EmailPlugin(
            $this->mockCiBuilder,
            $this->mockBuild,
            $arrOptions
        );
    }

    /**
     * @covers PHPUnit::execute
     */
    public function testExecute_ReturnsFalseWithoutArgs()
    {
        $returnValue = $this->testedEmailPlugin->execute();
        // As no addresses will have been mailed as non are configured.
        $expectedReturn = false;

        $this->assertEquals($expectedReturn, $returnValue);
    }

    /**
     * @covers PHPUnit::execute
     */
    public function testExecute_BuildsBasicEmails()
    {
        $this->loadEmailPluginWithOptions(
            array(
                'addresses' => array('<EMAIL>')
            )
        );

        /** @var \Swift_Message $actualMail */
        $actualMail = null;
        $this->catchMailPassedToSend($actualMail);

        $returnValue = $this->testedEmailPlugin->execute();
        $expectedReturn = true;

        $this->assertSystemMail(
            '<EMAIL>',
            '<EMAIL>',
            "Log Output: <br><pre>Build Log</pre>",
            "PHPCI - Test-Project - Passing Build",
            $actualMail
        );

        $this->assertEquals($expectedReturn, $returnValue);
    }

    /**
     * @covers PHPUnit::execute
     */
    public function testExecute_UniqueRecipientsFromWithCommitter()
    {
        $this->loadEmailPluginWithOptions(
            array(
                'addresses' => array('<EMAIL>', '<EMAIL>')
            )
        );

        $actualMails = [];
        $this->catchMailPassedToSend($actualMails);

        $returnValue = $this->testedEmailPlugin->execute();
        $this->assertTrue($returnValue);

        $this->assertCount(2, $actualMails);

        $actualTos = array(key($actualMails[0]->getTo()), key($actualMails[1]->getTo()));
        $this->assertContains('<EMAIL>', $actualTos);
        $this->assertContains('<EMAIL>', $actualTos);
    }

    /**
     * @covers PHPUnit::execute
     */
    public function testExecute_UniqueRecipientsWithCommiter()
    {
        $this->loadEmailPluginWithOptions(
            array(
                'commiter'  => true,
                'addresses' => array('<EMAIL>', '<EMAIL>')
            )
        );

        $actualMails = [];
        $this->catchMailPassedToSend($actualMails);

        $returnValue = $this->testedEmailPlugin->execute();
        $this->assertTrue($returnValue);

        $actualTos = array(key($actualMails[0]->getTo()), key($actualMails[1]->getTo()));
        $this->assertContains('<EMAIL>', $actualTos);
        $this->assertContains('<EMAIL>', $actualTos);
    }

    /**
     * @covers PHPUnit::sendEmail
     */
    public function testSendEmail_CallsMailerSend()
    {
        $this->mockMailer->expects($this->once())
            ->method('send');
        $this->testedEmailPlugin->sendEmail("<EMAIL>", array(), "hello", "body");
    }

    /**
     * @covers PHPUnit::sendEmail
     */
    public function testSendEmail_BuildsAMessageObject()
    {
        $subject = "Test mail";
        $body = "Message Body";
        $toAddress = "<EMAIL>";

        $this->mockMailer->expects($this->once())
            ->method('send')
            ->with($this->isInstanceOf('\Swift_Message'), $this->anything());
        $this->testedEmailPlugin->sendEmail($toAddress, array(), $subject, $body);
    }

    /**
     * @covers PHPUnit::sendEmail
     */
    public function testSendEmail_BuildsExpectedMessage()
    {
        $subject = "Test mail";
        $body = "Message Body";
        $toAddress = "<EMAIL>";
        $expectedMessage = \Swift_Message::newInstance($subject)
            ->setFrom('<EMAIL>')
            ->setTo($toAddress)
            ->setBody($body);

        /** @var \Swift_Message $actualMail */
        $actualMail = null;
        $this->catchMailPassedToSend($actualMail);

        $this->testedEmailPlugin->sendEmail($toAddress, array(), $subject, $body);

        $this->assertSystemMail(
            $toAddress,
            '<EMAIL>',
            $body,
            $subject,
            $actualMail
        );
    }

    /**
     * @param \Swift_Message $actualMail passed by ref and populated with
     *                                     the message object the mock mailer
     *                                     receives.
     */
    protected function catchMailPassedToSend(&$actualMail)
    {
        $this->mockMailer->expects(is_array($actualMail) ? $this->atLeast(1) : $this->once())
            ->method('send')
            ->will(
                $this->returnCallback(
                    function ($passedMail) use (&$actualMail) {
                        if(is_array($actualMail)) {
                            $actualMail[] = $passedMail;
                        } else {
                            $actualMail = $passedMail;
                        }
                        return array();
                    }
                )
            );
    }

    /**
     * Asserts that the actual mail object is populated as expected.
     *
     * @param string $expectedToAddress
     * @param $expectedFromAddress
     * @param string $expectedBody
     * @param string $expectedSubject
     * @param \Swift_Message $actualMail
     */
    protected function assertSystemMail(
        $expectedToAddress,
        $expectedFromAddress,
        $expectedBody,
        $expectedSubject,
        $actualMail
    ) {
        if (!($actualMail instanceof \Swift_Message)) {
            $type = is_object($actualMail) ? get_class($actualMail) : gettype(
                $actualMail
            );
            throw new \Exception("Expected Swift_Message got " . $type);
        }
        $this->assertEquals(
            array($expectedFromAddress => null),
            $actualMail->getFrom()
        );

        $this->assertEquals(
            array($expectedToAddress => null),
            $actualMail->getTo()
        );

        $this->assertEquals(
            $expectedBody,
            $actualMail->getBody()
        );

        $this->assertEquals(
            $expectedSubject,
            $actualMail->getSubject()
        );
    }
}
<commit_msg>Added project mocking to allow using mail template on successfull build.<commit_after><?php
/**
 * PHPCI - Continuous Integration for PHP
 *
 * @copyright    Copyright 2013, Block 8 Limited.
 * @license        https://github.com/Block8/PHPCI/blob/master/LICENSE.md
 * @link            http://www.phptesting.org/
 */

namespace PHPCI\Plugin\Tests;

use PHPCI\Plugin\Email as EmailPlugin;


/**
 * Unit test for the PHPUnit plugin.
 * @author meadsteve
 */
class EmailTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var EmailPlugin $testedPhpUnit
     */
    protected $testedEmailPlugin;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject $mockCiBuilder
     */
    protected $mockCiBuilder;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject $mockBuild
     */
    protected $mockBuild;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject $mockProject
     */
    protected $mockProject;

    public function setUp()
    {
        $this->mockProject = $this->getMock(
            '\PHPCI\Model\Project',
            array('getTitle'),
            array(),
            "mockProject",
            false
        );

        $this->mockProject->expects($this->any())
            ->method('getTitle')
            ->will($this->returnValue("Test project"));

        $this->mockBuild = $this->getMock(
            '\PHPCI\Model\Build',
            array('getLog', 'getStatus', 'getProject'),
            array(),
            "mockBuild",
            false
        );

        $this->mockBuild->expects($this->any())
            ->method('getLog')
            ->will($this->returnValue("Build Log"));

        $this->mockBuild->expects($this->any())
            ->method('getStatus')
            ->will($this->returnValue(\PHPCI\Model\Build::STATUS_SUCCESS));

        $this->mockBuild->expects($this->any())
            ->method('getProject')
            ->will($this->returnValue($this->mockProject));

        $this->mockCiBuilder = $this->getMock(
            '\PHPCI\Builder',
            array(
                'getSystemConfig',
                'getBuildProjectTitle',
                'getBuild',
                'log'
            ),
            array(),
            "mockBuilder_email",
            false
        );

        $this->mockCiBuilder->buildPath = "/";

        $this->mockCiBuilder->expects($this->any())
            ->method('getSystemConfig')
            ->with('phpci')
            ->will(
                $this->returnValue(
                    array(
                        'email_settings' => array(
                            'from_address' => "<EMAIL>"
                        )
                    )
                )
            );
        $this->mockCiBuilder->expects($this->any())
            ->method('getBuildProjectTitle')
            ->will($this->returnValue('Test-Project'));
        $this->mockCiBuilder->expects($this->any())
            ->method('getBuild')
            ->will($this->returnValue($this->mockBuild));

        $this->mockMailer = $this->getMock(
            '\Swift_Mailer',
            array('send'),
            array(),
            "mockMailer",
            false
        );

        $this->loadEmailPluginWithOptions();
    }

    protected function loadEmailPluginWithOptions($arrOptions = array())
    {
        $this->testedEmailPlugin = new EmailPlugin(
            $this->mockCiBuilder,
            $this->mockBuild,
            $arrOptions
        );
    }

    /**
     * @covers PHPUnit::execute
     */
    public function testExecute_ReturnsFalseWithoutArgs()
    {
        $returnValue = $this->testedEmailPlugin->execute();
        // As no addresses will have been mailed as non are configured.
        $expectedReturn = false;

        $this->assertEquals($expectedReturn, $returnValue);
    }

    /**
     * @covers PHPUnit::execute
     */
    public function testExecute_BuildsBasicEmails()
    {
        $this->loadEmailPluginWithOptions(
            array(
                'addresses' => array('<EMAIL>')
            )
        );

        /** @var \Swift_Message $actualMail */
        $actualMail = null;
        $this->catchMailPassedToSend($actualMail);

        $returnValue = $this->testedEmailPlugin->execute();
        $expectedReturn = true;

        $this->assertSystemMail(
            '<EMAIL>',
            '<EMAIL>',
            "Log Output: <br><pre>Build Log</pre>",
            "PHPCI - Test-Project - Passing Build",
            $actualMail
        );

        $this->assertEquals($expectedReturn, $returnValue);


    }

    /**
     * @covers PHPUnit::sendEmail
     */
    public function testSendEmail_CallsMailerSend()
    {
        $this->mockMailer->expects($this->once())
            ->method('send');
        $this->testedEmailPlugin->sendEmail("<EMAIL>", array(), "hello", "body");
    }

    /**
     * @covers PHPUnit::sendEmail
     */
    public function testSendEmail_BuildsAMessageObject()
    {
        $subject = "Test mail";
        $body = "Message Body";
        $toAddress = "<EMAIL>";

        $this->mockMailer->expects($this->once())
            ->method('send')
            ->with($this->isInstanceOf('\Swift_Message'), $this->anything());
        $this->testedEmailPlugin->sendEmail($toAddress, array(), $subject, $body);
    }

    /**
     * @covers PHPUnit::sendEmail
     */
    public function testSendEmail_BuildsExpectedMessage()
    {
        $subject = "Test mail";
        $body = "Message Body";
        $toAddress = "<EMAIL>";
        $expectedMessage = \Swift_Message::newInstance($subject)
            ->setFrom('<EMAIL>')
            ->setTo($toAddress)
            ->setBody($body);

        /** @var \Swift_Message $actualMail */
        $actualMail = null;
        $this->catchMailPassedToSend($actualMail);

        $this->testedEmailPlugin->sendEmail($toAddress, array(), $subject, $body);

        $this->assertSystemMail(
            $toAddress,
            '<EMAIL>',
            $body,
            $subject,
            $actualMail
        );
    }

    /**
     * @param \Swift_Message $actualMail passed by ref and populated with
     *                                     the message object the mock mailer
     *                                     receives.
     */
    protected function catchMailPassedToSend(&$actualMail)
    {
        $this->mockMailer->expects(is_array($actualMail) ? $this->atLeast(1) : $this->once())
            ->method('send')
            ->will(
                $this->returnCallback(
                    function ($passedMail) use (&$actualMail) {
                        if(is_array($actualMail)) {
                            $actualMail[] = $passedMail;
                        } else {
                            $actualMail = $passedMail;
                        }
                        return array();
                    }
                )
            );
    }

    /**
     * Asserts that the actual mail object is populated as expected.
     *
     * @param string $expectedToAddress
     * @param $expectedFromAddress
     * @param string $expectedBody
     * @param string $expectedSubject
     * @param \Swift_Message $actualMail
     */
    protected function assertSystemMail(
        $expectedToAddress,
        $expectedFromAddress,
        $expectedBody,
        $expectedSubject,
        $actualMail
    ) {
        if (!($actualMail instanceof \Swift_Message)) {
            $type = is_object($actualMail) ? get_class($actualMail) : gettype(
                $actualMail
            );
            throw new \Exception("Expected Swift_Message got " . $type);
        }
        $this->assertEquals(
            array($expectedFromAddress => null),
            $actualMail->getFrom()
        );

        $this->assertEquals(
            array($expectedToAddress => null),
            $actualMail->getTo()
        );

        $this->assertEquals(
            $expectedBody,
            $actualMail->getBody()
        );

        $this->assertEquals(
            $expectedSubject,
            $actualMail->getSubject()
        );
    }
}

{'fraction_non_alphanumeric': 0.13929997650927883, 'fraction_numerical': 0.001115809255344139, 'mean_word_length': 1.7159489633173843, 'pattern_counts': {'":': 0, '<': 38, '<?xml version=': 0, '>': 269, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6517413', 'n_tokens_mistral': 4680, 'n_tokens_neox': 4496, 'n_words': 745}