text:
<?php

namespace Puli\ComposerPlugin\Tests;

use Composer\Composer;
use Composer\Config;
use Composer\Installer\InstallationManager;
use Composer\IO\IOInterface;
use Composer\Package\AliasPackage;
use Composer\Package\Link;
use Composer\Package\Package;
use Composer\Package\RootPackage;
use Composer\Repository\RepositoryManager;
use Composer\Script\CommandEvent;
use Composer\Script\ScriptEvents;
use PHPUnit_Framework_MockObject_MockObject;
use PHPUnit_Framework_TestCase;
use Puli\ComposerPlugin\PuliPlugin;
use Puli\ComposerPlugin\PuliRunner;
use Puli\ComposerPlugin\PuliRunnerException;
use Puli\ComposerPlugin\Tests\Fixtures\TestLocalRepository;
use Symfony\Component\Filesystem\Filesystem;
use Webmozart\Glob\Test\TestUtil;
use Webmozart\PathUtil\Path;

/**
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class PuliPluginTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var PuliPlugin
     */
    private $plugin;

    /**
     * @var Composer
     */
    private $composer;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject|IOInterface
     */
    private $io;

    /**
     * @var TestLocalRepository
     */
    private $localRepository;

    /**
     * @var RepositoryManager
     */
    private $repositoryManager;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject|InstallationManager
     */
    private $installationManager;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject|PuliRunner
     */
    private $puliRunner;

    /**
     * @var Config
     */
    private $config;

    /**
     * @var RootPackage
     */
    private $rootPackage;

    private $tempDir;

    private $previousWd;

    private $installPaths;

    public function getInstallPath(Package $package)
    {
        if (isset($this->installPaths[$package->getName()])) {
            return $this->installPaths[$package->getName()];
        }

        return $this->tempDir.'/'.basename($package->getName());
    }

    protected function setUp()
    {
        $this->tempDir = TestUtil::makeTempDir('puli-composer-plugin', __CLASS__);

        $filesystem = new Filesystem();
        $filesystem->mirror(__DIR__.'/Fixtures/root', $this->tempDir);

        $this->io = $this->getMock('Composer\IO\IOInterface');
        $this->config = new Config(false, $this->tempDir);
        $this->config->merge(array('config' => array('vendor-dir' => 'the-vendor')));

        $this->installationManager = $this->getMockBuilder('Composer\Installer\InstallationManager')
            ->disableOriginalConstructor()
            ->getMock();

        $this->installationManager->expects($this->any())
            ->method('getInstallPath')
            ->will($this->returnCallback(array($this, 'getInstallPath')));

        $this->rootPackage = new RootPackage('vendor/root', '1.0', '1.0');

        $this->rootPackage->setRequires(array(
            'vendor/package1' => new Link('vendor/root', 'vendor/package1'),
            'vendor/package2' => new Link('vendor/root', 'vendor/package2'),
        ));

        $this->localRepository = new TestLocalRepository(array(
            new Package('vendor/package1', '1.0', '1.0'),
            new Package('vendor/package2', '1.0', '1.0'),
        ));

        $this->repositoryManager = new RepositoryManager($this->io, $this->config);
        $this->repositoryManager->setLocalRepository($this->localRepository);
        $this->installPaths = array();

        $this->composer = new Composer();
        $this->composer->setRepositoryManager($this->repositoryManager);
        $this->composer->setInstallationManager($this->installationManager);
        $this->composer->setConfig($this->config);
        $this->composer->setPackage($this->rootPackage);

        $this->puliRunner = $this->getMockBuilder('Puli\ComposerPlugin\PuliRunner')
            ->disableOriginalConstructor()
            ->getMock();

        $this->previousWd = getcwd();

        chdir($this->tempDir);

        $this->plugin = new PuliPlugin($this->puliRunner);
    }

    protected function tearDown()
    {
        chdir($this->previousWd);

        $filesystem = new Filesystem();
        $filesystem->remove($this->tempDir);
    }

    public function testActivate()
    {
        $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
            ->disableOriginalConstructor()
            ->getMock();

        $dispatcher->expects($this->once())
            ->method('addSubscriber')
            ->with($this->plugin);

        $this->composer->setEventDispatcher($dispatcher);

        $this->plugin->activate($this->composer, $this->io);
    }

    public function getInstallEventNames()
    {
        return array(
            array(ScriptEvents::POST_INSTALL_CMD),
            array(ScriptEvents::POST_UPDATE_CMD),
        );
    }

    /**
     * @dataProvider getInstallEventNames
     */
    public function testInstallNewPuliPackages($eventName)
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey($eventName, $listeners);

        $listener = $listeners[$eventName];
        $event = new CommandEvent($eventName, $this->composer, $this->io);

        $this->io->expects($this->at(0))
            ->method('write')
            ->with('<info>Looking for updated Puli packages</info>');
        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Installing <info>vendor/package1</info> (<comment>package1</comment>) in <comment>prod</comment>');
        $this->io->expects($this->at(2))
            ->method('write')
            ->with('Installing <info>vendor/package2</info> (<comment>package2</comment>) in <comment>prod</comment>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package2' 'vendor/package2' --installer 'composer'");
        $this->puliRunner->expects($this->at(3))
            ->method('run')
            ->with('build');

        $this->plugin->$listener($event);
    }

    /**
     * @dataProvider getInstallEventNames
     * @depends testInstallNewPuliPackages
     */
    public function testEventListenersOnlyProcessedOnFirstCall($eventName)
    {
        // Execute normal test
        $this->testInstallNewPuliPackages($eventName);

        // Now fire again
        $event = new CommandEvent($eventName, $this->composer, $this->io);
        $listeners = PuliPlugin::getSubscribedEvents();
        $listener = $listeners[$eventName];

        $this->plugin->$listener($event);
    }

    public function testInstallNewPuliPackagesInDifferentEnvironments()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->localRepository->setPackages(array(
            $package1 = new Package('vendor/package1', '1.0', '1.0'),
            $package2 = new Package('vendor/package2', '1.0', '1.0'),
            $package3 = new Package('vendor/package3', '1.0', '1.0'),
            $package4 = new Package('vendor/package4', '1.0', '1.0'),
        ));

        // Check whether package is in "require"
        $this->rootPackage->setRequires(array(
            'vendor/package1' => new Link('vendor/root', 'vendor/package1'),
        ));

        // Recursively resolve all "require" packages
        $package1->setRequires(array(
            'vendor/package2' => new Link('vendor/package1', 'vendor/package2'),
        ));

        // Ignore "require" blocks of "require-dev" dependencies
        $package3->setRequires(array(
            'vendor/package4' => new Link('vendor/package3', 'vendor/package4'),
        ));

        $this->io->expects($this->at(0))
            ->method('write')
            ->with('<info>Looking for updated Puli packages</info>');
        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Installing <info>vendor/package1</info> (<comment>package1</comment>) in <comment>prod</comment>');
        $this->io->expects($this->at(2))
            ->method('write')
            ->with('Installing <info>vendor/package2</info> (<comment>package2</comment>) in <comment>prod</comment>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package2' 'vendor/package2' --installer 'composer'");
        $this->puliRunner->expects($this->at(3))
            ->method('run')
            ->with("package --install --dev '{$this->tempDir}/package3' 'vendor/package3' --installer 'composer'");
        $this->puliRunner->expects($this->at(4))
            ->method('run')
            ->with("package --install --dev '{$this->tempDir}/package4' 'vendor/package4' --installer 'composer'");
        $this->puliRunner->expects($this->at(5))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    // meta packages have no install path

    public function testDoNotInstallPackagesWithoutInstallPath()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->localRepository->setPackages(array(
            new Package('vendor/package1', '1.0', '1.0'),
        ));

        $this->installPaths['vendor/package1'] = '';

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testResolveAliasPackages()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $package = new Package('vendor/package1', '1.0', '1.0');

        $this->localRepository->setPackages(array(
            // Package is not listed in installed packages
            new AliasPackage($package, '1.0', '1.0'),
        ));

        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Installing <info>vendor/package1</info> (<comment>package1</comment>) in <comment>prod</comment>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testInstallAliasedPackageOnlyOnce()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $package = new Package('vendor/package1', '1.0', '1.0');

        $this->localRepository->setPackages(array(
            // This time the package is returned here as well
            $package,
            new AliasPackage($package, '1.0', '1.0'),
        ));

        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Installing <info>vendor/package1</info> (<comment>package1</comment>) in <comment>prod</comment>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfInstallFails()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not install package "vendor/package1" (at ./package1): UnsupportedVersionException: Cannot read package file /home/bernhard/Entwicklung/Web/puli/cli/puli.json at version 5.0. The highest readable version is 1.0. Please upgrade Puli.</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'")
            ->willThrowException(new PuliRunnerException(
                "/path/to/php /path/to/puli.phar package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'",
                1,
                'UnsupportedVersionException: Cannot read package file /home/bernhard/Entwicklung/Web/puli/cli/puli.json at version 5.0. The highest readable version is 1.0. Please upgrade Puli.',
                'Exception trace...'
            ));
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfOverwritingPackagesInstalledByOtherInstaller()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        // User installed "vendor/package1"
        // Package added to Composer with different path, but Composer shouldn't
        // touch the existing package
        $this->installPaths['vendor/package1'] = $this->tempDir.'/package2';

        $this->localRepository->setPackages(array(
            new Package('vendor/package1', '1.0', '1.0'),
        ));

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not install package "vendor/package1" (at ./package2): NameConflictException: A package with the name "vendor/package1" exists already.</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;spock;{$this->tempDir}/package1;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package2' 'vendor/package1' --installer 'composer'")
            ->willThrowException(new PuliRunnerException(
                "/path/to/php /path/to/puli.phar package --install '{$this->tempDir}/package2' 'vendor/package1' --installer 'composer'",
                1,
                'NameConflictException: A package with the name "vendor/package1" exists already.',
                'Exception trace...'
            ));
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfPackageLoadingFails()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->installPaths['vendor/package1'] = $this->tempDir.'/not-loadable';

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not load Puli packages: FileNotFoundException: The file foobar does not exist.</warning>');

        $this->puliRunner->expects($this->once())
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willThrowException(new PuliRunnerException(
                'package --list --format "%name%;%installer%;%install_path%;%state%;%env%"',
                1,
                'FileNotFoundException: The file foobar does not exist.',
                'Exception trace...'
            ));

        $this->plugin->postInstall($event);
    }

    public function testWarnIfPackageInstalledByComposerNotLoadable()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: The package "vendor/package1" (at ./package1) could not be loaded.</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;not-loadable;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testDoNotWarnIfPackageInstalledByUserNotLoadable()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;spock;{$this->tempDir}/package1;not-loadable;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfPackageInstalledByComposerNotFoundInDevEnvironment()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io, true);

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: The package "vendor/package1" (at ./package1) could not be found.</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;not-found;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testDoNotWarnIfPackageInstalledByComposerNotFoundInProdEnvironment()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io, false);

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;not-found;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testDoNotWarnIfPackageInstalledByUserNotFound()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;spock;{$this->tempDir}/package1;not-found;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testReinstallPackagesWithInstallPathMovedToSubPath()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        // Package was moved to sub-path (PSR-0 -> PSR-4)
        // Such a package is not recognized as removed, because the path still
        // exists. Hence we need to explicitly reinstall it.
        $this->installPaths['vendor/package1'] = $this->tempDir.'/package1/sub/path';

        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Reinstalling <info>vendor/package1</info> (<comment>package1/sub/path</comment>) in <comment>prod</comment>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --delete 'vendor/package1'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1/sub/path' 'vendor/package1' --installer 'composer'");
        $this->puliRunner->expects($this->at(3))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testReinstallPackagesWithInstallPathMovedToParentPath()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        // Package was moved to parent path (PSR-4 -> PSR-0)
        $this->installPaths['vendor/package1'] = $this->tempDir.'/package1';

        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Reinstalling <info>vendor/package1</info> (<comment>package1</comment>) in <comment>prod</comment>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1/sub/path;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --delete 'vendor/package1'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'");
        $this->puliRunner->expects($this->at(3))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testReinstallPackagesWithChangedEnvironment()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->rootPackage->setRequires(array(
            'vendor/package2' => new Link('vendor/root', 'vendor/package2'),
        ));

        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Reinstalling <info>vendor/package1</info> (<comment>package1</comment>) in <comment>dev</comment>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --delete 'vendor/package1'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("package --install --dev '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'");
        $this->puliRunner->expects($this->at(3))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testDoNotReinstallExistingPuliPackages()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package2' 'vendor/package2' --installer 'composer'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfRemoveFailsDuringReinstall()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        // Package was moved to parent path (PSR-4 -> PSR-0)
        $this->installPaths['vendor/package1'] = $this->tempDir.'/package1';

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not remove package "vendor/package1" (at ./package1): Exception: The exception</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1/sub/path;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --delete 'vendor/package1'")
            ->willThrowException(new PuliRunnerException(
                "package --delete 'vendor/package1'",
                1,
                'Exception: The exception',
                'Exception trace...'
            ));
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfInstallFailsDuringReinstall()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        // Package was moved to parent path (PSR-4 -> PSR-0)
        $this->installPaths['vendor/package1'] = $this->tempDir.'/package1';

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not install package "vendor/package1" (at ./package1): Exception: The exception</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1/sub/path;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --delete 'vendor/package1'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'")
            ->willThrowException(new PuliRunnerException(
                "package --install '{$this->tempDir}/package1' 'vendor/package1' --installer 'composer'",
                1,
                'Exception: The exception',
                'Exception trace...'
            ));
        $this->puliRunner->expects($this->at(3))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testRemoveRemovedPackagesInDevEnvironment()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io, true);

        $this->localRepository->setPackages(array(
            new Package('vendor/package1', '1.0', '1.0'),
            // no more package2
        ));

        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Removing <info>vendor/package2</info> (<comment>package2</comment>)');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;not-found;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --delete 'vendor/package2'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testDoNotRemoveRemovedPackagesInProdEnvironment()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io, false);

        $this->localRepository->setPackages(array(
            new Package('vendor/package1', '1.0', '1.0'),
            // no more package2
        ));

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;not-found;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testDoNotRemovePackagesFromOtherInstaller()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io, true);

        $this->localRepository->setPackages(array());

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;spock;{$this->tempDir}/package1;not-found;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfRemoveFails()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io, true);

        $this->localRepository->setPackages(array(
            new Package('vendor/package1', '1.0', '1.0'),
            // no more package2
        ));

        $this->io->expects($this->at(1))
            ->method('write')
            ->with('Removing <info>vendor/package2</info> (<comment>package2</comment>)');

        $this->io->expects($this->exactly(2))
            ->method('writeError')
            ->withConsecutive(
                array('<warning>Warning: Could not remove package "vendor/package2" (at ./package2): Exception: The exception</warning>'),
                array('<warning>Warning: The package "vendor/package2" (at ./package2) could not be found.</warning>')
            );

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n".
                "vendor/package1;composer;{$this->tempDir}/package1;enabled;prod\n".
                "vendor/package2;composer;{$this->tempDir}/package2;not-found;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --delete 'vendor/package2'")
            ->willThrowException(new PuliRunnerException(
                "package --delete 'vendor/package2'",
                1,
                'Exception: The exception',
                'Exception trace...'
            ));
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testCopyComposerPackageNameToPuli()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->localRepository->setPackages(array());

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/previous;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --rename 'vendor/previous' 'vendor/root'");
        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testDoNotCopyComposerPackageNameToPuliIfUnchanged()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->localRepository->setPackages(array());

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/root;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with('build');

        $this->plugin->postInstall($event);
    }

    public function testWarnIfRenameFails()
    {
        $event = new CommandEvent(ScriptEvents::POST_INSTALL_CMD, $this->composer, $this->io);

        $this->localRepository->setPackages(array());

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not rename root package to "vendor/root": Exception: Some exception.</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with('package --list --format "%name%;%installer%;%install_path%;%state%;%env%"')
            ->willReturn(
                "vendor/previous;;{$this->tempDir};enabled;prod\n"
            );
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("package --rename 'vendor/previous' 'vendor/root'")
            ->willThrowException(new PuliRunnerException(
                "package --rename 'vendor/previous' 'vendor/root'",
                1,
                'Exception: Some exception.',
                'Exception trace...'
            ));

        $this->plugin->postInstall($event);
    }

    public function testInsertFactoryClassIntoClassMap()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->at(0))
            ->method('write')
            ->with('<info>Generating PULI_FACTORY_CLASS constant</info>');
        $this->io->expects($this->at(1))
            ->method('write')
            ->with('<info>Registering Puli\\MyFactory with the class-map autoloader</info>');

        $this->io->expects($this->never())
            ->method('writeError');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with("config 'factory.in.class' --parsed")
            ->willReturn("Puli\\MyFactory\n");
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("config 'factory.in.file' --parsed")
            ->willReturn("My/Factory.php\n");

        $this->plugin->$listener($event);

        $this->assertFileExists($this->tempDir.'/the-vendor/composer/autoload_classmap.php');

        $classMap = require $this->tempDir.'/the-vendor/composer/autoload_classmap.php';

        $this->assertInternalType('array', $classMap);
        $this->assertArrayHasKey('Puli\\MyFactory', $classMap);
        $this->assertSame($this->tempDir.'/My/Factory.php', Path::canonicalize($classMap['Puli\\MyFactory']));
    }

    public function testWarnIfFactoryClassCannotBeRead()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not load Puli configuration: Exception: Some exception.</warning>');

        $this->puliRunner->expects($this->once())
            ->method('run')
            ->with("config 'factory.in.class' --parsed")
            ->willThrowException(new PuliRunnerException(
                "config 'factory.in.class' --parsed",
                1,
                'Exception: Some exception.',
                'Exception trace...'
            ));

        $this->plugin->$listener($event);
    }

    public function testWarnIfFactoryFileCannotBeRead()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->once())
            ->method('writeError')
            ->with('<warning>Warning: Could not load Puli configuration: Exception: Some exception.</warning>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with("config 'factory.in.class' --parsed")
            ->willReturn("Puli\\MyFactory\n");
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("config 'factory.in.file' --parsed")
            ->willThrowException(new PuliRunnerException(
                "config 'factory.in.file' --parsed",
                1,
                'Exception: Some exception.',
                'Exception trace...'
            ));

        $this->plugin->$listener($event);
    }

    /**
     * @expectedException \Puli\ComposerPlugin\PuliPluginException
     * @expectedExceptionMessage autoload_classmap.php
     */
    public function testFailIfClassMapFileNotFound()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->never())
            ->method('writeError');

        unlink($this->tempDir.'/the-vendor/composer/autoload_classmap.php');

        $this->plugin->$listener($event);
    }

    public function testInsertFactoryConstantIntoAutoload()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->at(0))
            ->method('write')
            ->with('<info>Generating PULI_FACTORY_CLASS constant</info>');
        $this->io->expects($this->at(1))
            ->method('write')
            ->with('<info>Registering Puli\\MyFactory with the class-map autoloader</info>');

        $this->puliRunner->expects($this->at(0))
            ->method('run')
            ->with("config 'factory.in.class' --parsed")
            ->willReturn("Puli\\MyFactory\n");
        $this->puliRunner->expects($this->at(1))
            ->method('run')
            ->with("config 'factory.in.file' --parsed")
            ->willReturn("My/Factory.php\n");

        $this->plugin->$listener($event);

        $this->assertFileExists($this->tempDir.'/the-vendor/autoload.php');

        require $this->tempDir.'/the-vendor/autoload.php';

        $this->assertTrue(defined('PULI_FACTORY_CLASS'));
        $this->assertSame('Puli\\MyFactory', PULI_FACTORY_CLASS);
    }

    /**
     * @expectedException \Puli\ComposerPlugin\PuliPluginException
     * @expectedExceptionMessage autoload.php
     */
    public function testFailIfAutoloadFileNotFound()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->never())
            ->method('write');

        unlink($this->tempDir.'/the-vendor/autoload.php');

        $this->plugin->$listener($event);
    }

    public function testSetBootstrapFileToAutoloadFile()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->at(2))
            ->method('write')
            ->with('<info>Setting "bootstrap-file" to "the-vendor/autoload.php"</info>');

        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("config 'bootstrap-file' --parsed")
            ->willReturn('null');
        $this->puliRunner->expects($this->at(3))
            ->method('run')
            ->with("config 'bootstrap-file' 'the-vendor/autoload.php'");

        $this->plugin->$listener($event);
    }

    public function testDoNotSetBootstrapFileIfAlreadySet()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->exactly(2))
            ->method('write');

        $this->puliRunner->expects($this->at(2))
            ->method('run')
            ->with("config 'bootstrap-file' --parsed")
            ->willReturn("my/bootstrap-file.php\n");
        $this->puliRunner->expects($this->exactly(3))
            ->method('run');

        $this->plugin->$listener($event);
    }

    public function testRunPostAutoloadDumpOnlyOnce()
    {
        $listeners = $this->plugin->getSubscribedEvents();

        $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners);

        $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP];
        $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io);

        $this->io->expects($this->exactly(3))
            ->method('write');

        $this->plugin->$listener($event);
        $this->plugin->$listener($event);
    }
}


text:
<?php

namespace CachetHQ\Cachet\Composers;

use CachetHQ\Cachet\Facades\Setting;
use GrahamCampbell\Markdown\Facades\Markdown;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Config;

class AppComposer
{
    /**
     * Index page view composer.
     *
     * @param \Illuminate\Contracts\View\View $view
     *
     * @return void
     */
    public function compose(View $view)
    {
<<<<<<< HEAD
        $view->withAboutApp(Markdown::convertToHtml(Setting::get('app_about')));
        $view->withAppAnalytics(Setting::get('app_analytics'));
        $view->withAppAnalyticsGoSquared(Setting::get('app_analytics_gs'));
=======
        $support = Setting::get('show_support');
        $view->withAboutApp(Markdown::convertToHtml(Setting::get('app_about')));
        $view->withAppAnalytics(Setting::get('app_analytics'));
        $view->withAppAnalyticsGoSquared(Setting::get('app_analytics_go_squared'));
>>>>>>> e5c137f82b44a4fbd2d63c36abbfe0cec29ead52
        $view->withAppAnalyticsPiwikUrl(Setting::get('app_analytics_piwik_url'));
        $view->withAppAnalyticsPiwikSiteId(Setting::get('app_analytics_piwik_siteid'));
        $view->withAppBanner(Setting::get('app_banner'));
        $view->withAppBannerStyleFullWidth(Setting::get('style_fullwidth_header'));
        $view->withAppBannerType(Setting::get('app_banner_type'));
        $view->withAppDomain(Setting::get('app_domain'));
        $view->withAppGraphs(Setting::get('display_graphs'));
        $view->withAppLocale(Setting::get('app_locale'));
        $view->withAppName(Setting::get('app_name'));
<<<<<<< HEAD
        $view->withAppStylesheet(Setting::get('stylesheet'));
        $view->withAppUrl(Config::get('app.url'));
        $view->withShowSupport(Setting::get('show_support'));
=======
        if ($support) {
            $view->withSiteTitle(Setting::get('app_name').' | Cachet');
        } else {
            $view->withSiteTitle(Setting::get('app_name'));
        }
        $view->withAppStylesheet(Setting::get('stylesheet'));
        $view->withAppUrl(Config::get('app.url'));
        $view->withShowSupport($support);
>>>>>>> e5c137f82b44a4fbd2d63c36abbfe0cec29ead52
    }
}

redpajama_set_name: RedPajamaGithub


text:
module PDB

using Compat

export parse_entry, eachatom, eachmol, eachchain, name, models

import Base: convert, show, start, done, next

include("element.jl")
include("parser.jl")

end # module


text:
package org.apache.helix.integration.task;

import java.util.ArrayList;
import java.util.List;

import org.apache.helix.TestHelper;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.TaskConfig;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.Workflow;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestDropOnParticipantReset extends TaskTestBase {

  @BeforeClass
  public void beforeClass() throws Exception {
    _numDbs = 0;
    _numPartitions = 0;
    _numReplicas = 0;
    _numNodes = 1; // Only bring up 1 instance
    super.beforeClass();
  }

  /**
   * Tests that upon Participant reconnect, the Controller correctly sends the current
   * state of the task partition to DROPPED. This is to avoid a resource leak in case of a
   * Participant disconnect/reconnect and an ensuing reset() on all of the partitions on that
   * Participant.
   */
  @Test
  public void testDropOnParticipantReset() throws InterruptedException {
    // Create a workflow with some long-running jobs in progress
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB";
    Workflow.Builder builder = new Workflow.Builder(workflowName);
    List<TaskConfig> taskConfigs = new ArrayList<>();
    for (int j = 0; j < 2; j++) { // 2 tasks to ensure that they execute
      String taskID = jobName + "_TASK_" + j;
      TaskConfig.Builder taskConfigBuilder = new TaskConfig.Builder();
      taskConfigBuilder.setTaskId(taskID).setCommand(MockTask.TASK_COMMAND)
          .addConfig(MockTask.JOB_DELAY, "3000");
      taskConfigs.add(taskConfigBuilder.build());
    }
    JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND)
        .setMaxAttemptsPerTask(10).setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG)
        .addTaskConfigs(taskConfigs).setIgnoreDependentJobFailure(true)
        // 1 task at a time
        .setNumConcurrentTasksPerInstance(1);
    builder.addJob(jobName, jobBuilder);

    // Modify maxConcurrentTask for the instance so that it only accepts 1 task at most
    InstanceConfig instanceConfig = _gSetupTool.getClusterManagementTool()
        .getInstanceConfig(CLUSTER_NAME, _participants[0].getInstanceName());
    instanceConfig.setMaxConcurrentTask(1);
    _gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME,
        _participants[0].getInstanceName(), instanceConfig);

    // Start the workflow
    _driver.start(builder.build());
    _driver.pollForJobState(workflowName, workflowName + "_" + jobName, TaskState.IN_PROGRESS);
    Thread.sleep(1500L); // Wait for the Participant to process the message
    // Stop and start the participant to mimic a connection issue
    _participants[0].syncStop();
    // Upon starting the participant, the first task partition should be dropped and assigned anew
    // on the instance. Then the rest of the tasks will execute and the workflow will complete
    startParticipant(0);

    TaskState workflowState = _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED);
    TaskState jobState =
        _driver.pollForJobState(workflowName, workflowName + "_" + jobName, TaskState.COMPLETED);
    Assert.assertEquals(workflowState, TaskState.COMPLETED);
    Assert.assertEquals(jobState, TaskState.COMPLETED);
  }
}


text:
package org.ambraproject.rhino.model;

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import java.util.Date;

/**
 * @author Alex Kudlick 3/7/12
 */
@Entity
@Table(name = "comment")
public class Comment {

  @Id
  @GeneratedValue
  @Column
  private Long commentId;

  @Column
  private Long userProfileID;

  @ManyToOne
  @JoinColumn(name = "articleId", nullable = false)
  private Article article;

  @ManyToOne
  @JoinColumn(name = "parentId", nullable = true)
  private Comment parent;

  @Column
  private String commentUri;

  @Column
  private String title;

  @Column
  private String body;

  @Column
  private String highlightedText;

  @Column
  private String competingInterestBody;

  @Generated(value = GenerationTime.INSERT)
  @Temporal(javax.persistence.TemporalType.TIMESTAMP)
  @Column(insertable = false, updatable = false, columnDefinition = "timestamp default current_timestamp")
  private Date created;

  @Generated(value = GenerationTime.ALWAYS)
  @Temporal(javax.persistence.TemporalType.TIMESTAMP)
  @Column(insertable = false, updatable = false, columnDefinition = "timestamp default current_timestamp")
  private Date lastModified;

  @Column
  private boolean isRemoved;

  @Column
  private String authorEmailAddress;

  @Column
  private String authorName;

  public Comment() {
    super();
  }

  public Long getCommentId() {
    return commentId;
  }

  public void setCommentId(Long commentId) {
    this.commentId = commentId;
  }

  public Long getUserProfileID() {
    return userProfileID;
  }

  public void setUserProfileID(Long userProfileID) {
    this.userProfileID = userProfileID;
  }

  public Article getArticle() {
    return article;
  }

  public void setArticle(Article article) {
    this.article = article;
  }

  public Comment getParent() {
    return parent;
  }

  public Long getParentId() {
    return parent.getCommentId();
  }

  public void setParent(Comment parent) {
    this.parent = parent;
  }

  public Date getCreated() {
    return created;
  }

  public void setCreated(Date created) {
    this.created = created;
  }

  public Date getLastModified() {
    return lastModified;
  }

  public void setLastModified(Date lastModified) {
    this.lastModified = lastModified;
  }

  public String getCommentUri() {
    return commentUri;
  }

  public void setCommentUri(String commentUri) {
    this.commentUri = commentUri;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getBody() {
    return body;
  }

  public void setBody(String body) {
    this.body = body;
  }

  public String getCompetingInterestBody() {
    return competingInterestBody;
  }

  public void setCompetingInterestBody(String competingInterestBody) {
    this.competingInterestBody = competingInterestBody;
  }

  public String getHighlightedText() {
    return highlightedText;
  }

  public void setHighlightedText(String highlightedText) {
    this.highlightedText = highlightedText;
  }

  public boolean getIsRemoved() {
    return isRemoved;
  }

  public void setIsRemoved(boolean removed) {
    isRemoved = removed;
  }

  public String getAuthorEmailAddress() {
    return authorEmailAddress;
  }

  public void setAuthorEmailAddress(String authorEmailAddress) {
    this.authorEmailAddress = authorEmailAddress;
  }

  public String getAuthorName() {
    return authorName;
  }

  public void setAuthorName(String authorName) {
    this.authorName = authorName;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Comment comment = (Comment) o;

    if (isRemoved != comment.isRemoved) return false;
    if (!commentId.equals(comment.commentId)) return false;
    if (userProfileID != null ? !userProfileID.equals(comment.userProfileID) : comment.userProfileID != null)
      return false;
    if (!article.equals(comment.article)) return false;
    if (parent != null ? !parent.equals(comment.parent) : comment.parent != null) return false;
    if (commentUri != null ? !commentUri.equals(comment.commentUri) : comment.commentUri != null)
      return false;
    if (title != null ? !title.equals(comment.title) : comment.title != null) return false;
    if (body != null ? !body.equals(comment.body) : comment.body != null) return false;
    if (highlightedText != null ? !highlightedText.equals(comment.highlightedText) : comment.highlightedText != null)
      return false;
    if (competingInterestBody != null ? !competingInterestBody.equals(comment.competingInterestBody) : comment.competingInterestBody != null)
      return false;
    if (!created.equals(comment.created)) return false;
    if (!lastModified.equals(comment.lastModified)) return false;
    if (authorEmailAddress != null ? !authorEmailAddress.equals(comment.authorEmailAddress) : comment.authorEmailAddress != null)
      return false;
    return authorName != null ? authorName.equals(comment.authorName) : comment.authorName == null;
  }

  @Override
  public int hashCode() {
    int result = commentId.hashCode();
    result = 31 * result + (userProfileID != null ? userProfileID.hashCode() : 0);
    result = 31 * result + article.hashCode();
    result = 31 * result + (parent != null ? parent.hashCode() : 0);
    result = 31 * result + (commentUri != null ? commentUri.hashCode() : 0);
    result = 31 * result + (title != null ? title.hashCode() : 0);
    result = 31 * result + (body != null ? body.hashCode() : 0);
    result = 31 * result + (highlightedText != null ? highlightedText.hashCode() : 0);
    result = 31 * result + (competingInterestBody != null ? competingInterestBody.hashCode() : 0);
    result = 31 * result + created.hashCode();
    result = 31 * result + lastModified.hashCode();
    result = 31 * result + (isRemoved ? 1 : 0);
    result = 31 * result + (authorEmailAddress != null ? authorEmailAddress.hashCode() : 0);
    result = 31 * result + (authorName != null ? authorName.hashCode() : 0);
    return result;
  }

  @Override
  public String toString() {
    return "Comment{" +
        "title='" + title + '\'' +
        ", body='" + body + '\'' +
        '}';
  }
}


text:
package models;

import models.enumeration.ResourceType;
import models.resource.Resource;
import models.resource.ResourceConvertible;
import org.apache.commons.collections.CollectionUtils;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;

import javax.annotation.Nonnull;
import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Entity
public class IssueLabel extends Model implements ResourceConvertible {

    static public class IssueLabelException extends Exception {
        private static final long serialVersionUID = 1L;
        public IssueLabelException(String s) {
            super(s);
        }
    }

    private static final long serialVersionUID = -35487506476718498L;
    public static final Finder<Long, IssueLabel> finder = new Finder<>(Long.class, IssueLabel.class);

    @Id
    public Long id;

    @Required
    @ManyToOne
    public IssueLabelCategory category;

    @Required(message="label.error.color.empty")
    public String color;

    @Required(message="label.error.labelName.empty")
    @Size(max=255, message="label.error.labelName.tooLongSize")
    public String name;

    @ManyToOne
    public Project project;

    @ManyToMany(mappedBy="labels", fetch = FetchType.EAGER)
    public Set<Issue> issues;

    @ManyToMany(mappedBy="labels", fetch = FetchType.EAGER)
    public Set<Posting> postings;

    public static List<IssueLabel> findByProject(Project project) {
        return finder.where()
                .eq("project.id", project.id)
                .orderBy().asc("category.name")
                .orderBy().asc("name")
                .findList();
    }

    public static void copyIssueLabels(Project fromProject, Project toProject){
        List<IssueLabel> fromLabels = findByProject(fromProject);
        if(CollectionUtils.isEmpty(fromLabels)){
            return;
        }

        toProject.issueLabels = new ArrayList<>();
        for(IssueLabel fromLabel: fromLabels){
            IssueLabel copiedLabel = copyIssueLabel(toProject, fromLabel);
            if(!copiedLabel.exists()){
                toProject.issueLabels.add(copiedLabel);
            }
        }
        toProject.update();
    }

    /**
     * Copy IssueLabel to toProject.
     * If same label already exists in the {@code toProject}, it doesn't save and just reuse it.
     *
     * @param toProject
     * @param fromLabel
     * @return copied {@code IssueLabel}
     */
    public static IssueLabel copyIssueLabel(@Nonnull Project toProject, @Nonnull IssueLabel fromLabel) {
        IssueLabel label = new IssueLabel();
        label.name = fromLabel.name;
        label.color = fromLabel.color;
        label.category = copyIssueLabelCategory(toProject, fromLabel);
        label.project = toProject;
        return label;
    }

    /**
     * Copy IssueLabelCategory.
     * If same category already exists in the {@code toProject}, it doesn't save and just reuse it.
     *
     * @param toProject
     * @param fromLabel
     * @return copied {@code IssueLabelCategory}
     */
    private static IssueLabelCategory copyIssueLabelCategory(@Nonnull Project toProject, @Nonnull IssueLabel fromLabel) {
        IssueLabelCategory category = new IssueLabelCategory();
        category.name = fromLabel.category.name;
        category.project = toProject;
        category.isExclusive = fromLabel.category.isExclusive;
        if(category.exists()){
            category = IssueLabelCategory.findBy(category);
        } else {
            category.save();
        }
        return category;
    }

    public String toString() {
        return category.name + " - " + name;
    }

    @Transient
    public boolean exists() {
        return finder.where()
                .eq("project.id", project.id)
                .eq("category", category)
                .eq("name", name)
                .findRowCount() > 0;
    }

    @Transient
    public IssueLabel findExistLabel() {
        List<IssueLabel> list = finder.where()
                .eq("project.id", project.id)
                .eq("category", category)
                .eq("name", name)
                .findList();
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Transient
    public static IssueLabel findByName(String labelName, String categoryName, Project project) {
        List<IssueLabel> list = finder.where()
                .eq("project.id", project.id)
                .eq("category.name", categoryName)
                .eq("name", labelName)
                .findList();
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public void delete() {
        for(Issue issue: issues) {
            issue.labels.remove(this);
            issue.save();
        }
        super.delete();
    }

    @Override
    public Resource asResource() {
        return new Resource() {
            @Override
            public String getId() {
                return id.toString();
            }

            @Override
            public Project getProject() {
                return project;
            }

            @Override
            public ResourceType getType() {
                return ResourceType.ISSUE_LABEL;
            }
        };
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        if (!super.equals(object)) return false;

        IssueLabel that = (IssueLabel) object;

        if (!color.equals(that.color)) return false;
        if (!id.equals(that.id)) return false;
        if (!name.equals(that.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (id != null ? id.hashCode() : 0);
        result = 31 * result + color.hashCode();
        result = 31 * result + name.hashCode();
        return result;
    }
}


text:
/*
	Note: This code is based on the following example:
	http://www.cim.mcgill.ca/~yiannis/417/2013/COMP417_A1.pdf
*/

#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"

class Robot
{
	public:

		//Constructor to initialize a robot.
		Robot(ros::NodeHandle& nh, int numRobot,
		double min_scan_angle_rad, double max_scan_angle_rad, float proximity_range_m,
		double forward_speed_mps, double rotate_speed_radps);

 		//Method to send commands of movement to the robot.
		void move(double linearVelMPS, double angularVelRadPS);

 		//This method is going to be called every time we got some data from the laser.
		void commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg);

		//Execute loop at 10 Hz
		void spin();

 		//Finite State Machine
		enum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};

		const double MIN_SCAN_ANGLE_RAD;//Specify the min angle in radians to take into account in the laser data.
		const double MAX_SCAN_ANGLE_RAD;//Specify the max angle in radians to take into account in the laser data.
		const float PROXIMITY_RANGE_M;//The minimum range in meters to accept before the robot stop and turn to another random direction.
		const double FORWARD_SPEED_MPS;//Miles per second
		const double ROTATE_SPEED_RADPS;//Radians per second

	protected:

		ros::Publisher commandPub;//Publisher to the velocity command topic
		ros::Subscriber laserSub;//Subscriber to the laser scan topic
		enum FSM fsm;
		ros::Time rotateStartTime;//Start time of the rotation.
		ros::Duration rotateDuration;//Duration of the rotation.
};


text:
import ma = require('azure-pipelines-task-lib/mock-answer');
import tmrm = require('azure-pipelines-task-lib/mock-run');
import path = require('path');

const DefaultWorkingDirectory: string = "/a/w";
let taskPath = path.join(__dirname, '..', 'dockercompose.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);

tr.setInput('containerregistrytype', process.env["__container_type__"] || 'Container Registry');
tr.setInput('action', process.env["__command__"] || 'Build services');
tr.setInput('dockerRegistryEndpoint', 'dockerhubendpoint');
tr.setInput('dockerComposeFile', process.env["__composeFilePath__"] ||'/tmp/tempdir/100/docker-compose.yml');
tr.setInput('customCommand', "pull test/test:2");
tr.setInput('includeLatestTag', process.env["__includeLatestTag__"] || "false");
tr.setInput('qualifyImageNames', process.env["__qualifyImageNames__"] || "false");
tr.setInput('additionalDockerComposeFiles', process.env["__additionalDockerComposeFiles__"] || null);
tr.setInput('dockerComposeCommand', process.env["__dockerComposeCommand__"] || null);
tr.setInput('azureSubscriptionEndpoint', 'AzureRMSpn');
tr.setInput('azureContainerRegistry', '{"loginServer":"ajgtestacr1.azurecr.io", "id" : "/subscriptions/c00d16c7-6c1f-4c03-9be1-6934a4c49682/resourcegroups/ajgtestacr1rg/providers/Microsoft.ContainerRegistry/registries/ajgtestacr1"}');
tr.setInput('arguments', process.env["__arguments__"] || '');
tr.setInput('dockerComposePath', process.env["__dockerComposePath__"] || '');

console.log("Inputs have been set");

process.env["RELEASE_RELEASENAME"] = "Release-1";
process.env["SYSTEM_DEFAULTWORKINGDIRECTORY"] =  DefaultWorkingDirectory;
process.env["SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"] = "https://abc.visualstudio.com/";
process.env["SYSTEM_SERVERTYPE"] = "hosted";
process.env["ENDPOINT_AUTH_dockerhubendpoint"] = "{\"parameters\":{\"username\":\"test\", \"password\":\"regpassword\", \"email\":\"test@microsoft.com\",\"registry\":\"https://index.docker.io/v1/\"},\"scheme\":\"UsernamePassword\"}";
process.env["ENDPOINT_AUTH_SCHEME_AzureRMSpn"] = "ServicePrincipal";
process.env["ENDPOINT_AUTH_PARAMETER_AzureRMSpn_SERVICEPRINCIPALID"] = "spId";
process.env["ENDPOINT_AUTH_PARAMETER_AzureRMSpn_SERVICEPRINCIPALKEY"] = "spKey";
process.env["ENDPOINT_AUTH_PARAMETER_AzureRMSpn_TENANTID"] = "tenant";
process.env["ENDPOINT_DATA_AzureRMSpn_SUBSCRIPTIONNAME"] = "sName";
process.env["ENDPOINT_DATA_AzureRMSpn_SUBSCRIPTIONID"] =  "sId";
process.env["ENDPOINT_DATA_AzureRMSpn_SPNOBJECTID"] =  "oId";
process.env['AGENT_HOMEDIRECTORY'] = '/tmp/tempdir/100/';

// provide answers for task mock
let a: any = <any>{
    "which": {
        "docker": "docker",
        "docker-compose": "docker-compose"
    },
    "checkPath": {
        "docker": true,
        "docker-compose": true
    },
    "exec": {
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml build" :{
            "code": 0,
            "stdout": "sucessfully built the service images"
        },
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml config" :{
            "code": 0,
            "stdout": "services:\n  redis:\n    image: redis:alpine\n  web:\n    build:\n      context: /tmp/tempdir/100\n    ports:\n    - 5000:5000/tcp\n    volumes:\n    - /tmp/tempdir/100:/code:rw\nversion: '2.0'"
        },
        "docker push 100_web": {
            "code": 0,
            "stdout": "sucessfully pushed 100_web"
        },
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml up": {
            "code": 0,
            "stdout": "sucessfully ran services"
        },
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml -f /tmp/tempdir/100/.docker-compose.12345.yml config":{
            "code": 0,
            "stdout": "services:\n  redis:\n    image: redis:alpine\n  web:\n    build:\n      context: /tmp/tempdir/100\n    image: ajgtestacr1.azurecr.io/100_web\n    ports:\n    - 5000:5000/tcp\n    volumes:\n    - /tmp/tempdir/100:/code:rw\nversion: '2.0'"
        },
        "docker push ajgtestacr1.azurecr.io/100_web":{
            "code": 0,
            "stdout": "successfully pushed with qualified image"
        },
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml -f /tmp/tempdir/100/docker-compose.override.yml config":{
            "code": 0,
            "stdout": "services:\n  redis:\n    image: redis:alpine\n  web:\n    build:\n      context: /tmp/tempdir/100\n    image: ajgtestacr1.azurecr.io/100_web\n    ports:\n    - 5000:5000/tcp\n    volumes:\n    - /tmp/tempdir/100:/code:rw\nversion: '2.0'"
        },
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml -f /tmp/tempdir/100/docker-compose.override.yml up -d":{
            "code": 0,
            "stdout": "successfully ran up command"
        },
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml up -d":{
            "code": 0,
            "stdout": "successfully ran up command"
        },
        "docker-compose -f /tmp/tempdir/100/docker-compose.yml build --pull --parallel" :{
            "code": 0,
            "stdout": "sucessfully built the service images"
        },
        "docker-compose-userdefined -f /tmp/tempdir/100/docker-compose.yml build" :{
            "code": 0,
            "stdout": "sucessfully built the service images"
        }, "docker-compose-userdefined -f /tmp/tempdir/100/docker-compose.yml config" :{
            "code": 0,
            "stdout": "services:\n  redis:\n    image: redis:alpine\n  web:\n    build:\n      context: /tmp/tempdir/100\n    ports:\n    - 5000:5000/tcp\n    volumes:\n    - /tmp/tempdir/100:/code:rw\nversion: '2.0'"
        }, "docker-compose -f /tmp/tempdir/100/docker-compose.yml pull service1 service2" :{
            "code": 0,
            "stdout": "successfully pulled the passed service images"
        }
    },
    "exist": {
        "/tmp/tempdir/100/.docker-compose.12345.yml" : true,
        "/tmp/tempdir/100/docker-compose.override.yml" : true
    }
};

var ut = require('../utils');
tr.registerMock('./utils', {
    IsNullOrEmpty : ut.IsNullOrEmpty,
    HasItems : ut.HasItems,
    StringWritable: ut.StringWritable,
    PackerVersion: ut.PackerVersion,
    isGreaterVersion: ut.isGreaterVersion,
    getFinalComposeFileName: function(){
        return ".docker-compose.12345" + ".yml";
    },
    writeFileSync: function(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }){
        console.log("content of yaml file : "+data);
    },
    writeTaskOutput: function (commandName: string, output: string): string {
        let outputFileName = commandName + "_" + Date.now() + ".txt";
        console.log(`Mocked test writing to: ${outputFileName}`);
        return outputFileName;
    }
});

tr.setAnswers(a);
tr.run();


text:
<?php

namespace LivrariaAdmin\Controller;

use Zend\Mvc\Controller\AbstractActionController,
	Zend\View\Model\ViewModel,
	Zend\Authentication\AuthenticationService,
	Zend\Authentication\Storage\Session as SessionStorage;

use LivrariaAdmin\Form\Login as LoginForm;

class AuthController extends AbstractActionController{

	public function __construct() {
		$this->entity     = 'Livraria\Entity\Categoria';
		$this->form       = 'LivrariaAdmin\Form\Categoria';
		$this->service    = 'Livraria\Service\Categoria';
		$this->controller = 'categorias';
		$this->route 	  = 'livraria-admin';
	}

	public function indexAction() {
		$form = new LoginForm;
		$error = false;

		$request = $this->getRequest();
		if ($request->isPost()) {
			$form->setData($request->getPost());
			if($form->isValid()) {
				$data = $request->getPost()->toArray();

				$auth = new AuthenticationService;
				$sessionStorage = new SessionStorage('LivrariaAdmin');
				$auth->setStorage($sessionStorage);

				$authAdapter = $this->getServiceLocator()->get('Livraria\Auth\Adapter');
				$authAdapter->setUsername($data['email']);
                $authAdapter->setPassword($data['password']);

				$result = $auth->authenticate($authAdapter);

				if ($result->isValid()) {
					# php 5.4 == $sessionStorage->write($auth->getIdentity()['user'], null);

					$user = $auth->getIdentity();
					$sessionStorage->write($user['user'], null);

					return $this->redirect()->toRoute('livraria-admin', array('controller' => 'categorias'));
				}else
					$error = true;
			}
		}

		return new ViewModel(array('form' => $form, 'error' => $error));
	}

	public function logoutAction() {
		$auth = new AuthenticationService;
		$auth->setStorage(new SessionStorage('LivrariaAdmin'));
		$auth->clearIdentity();

		return $this->redirect()->toRoute('livraria-admin-auth');
	}

}