Exemple #1
0
use Ayaml\Ayaml;
use Ayaml\Fixture\YamlData;
use Symfony\Component\Yaml\Yaml as SymfonyYaml;
describe('\\Ayaml\\Fixture\\YamlData', function () {
    context('load', function () {
        beforeEach(function () {
            Ayaml::registerBasePath(__DIR__ . '/../../SampleYaml');
            Ayaml::registerBasePath(__DIR__ . '/../../SampleYaml/AnotherPath');
        });
        it('should load multiple paths', function () {
            expect(Ayaml::file('another_path'))->to->be->instanceof('\\Ayaml\\Container');
        });
        afterEach(function () {
            $reflection = new \ReflectionProperty('\\Ayaml\\Ayaml', 'basePaths');
            $reflection->setAccessible(true);
            $reflection->setValue([]);
        });
    });
    context('getSchema', function () {
        context('normal case', function () {
            beforeEach(function () {
                $data = SymfonyYaml::parse(file_get_contents(__DIR__ . '/../../SampleYaml/user.yml', SymfonyYaml::PARSE_EXCEPTION_ON_INVALID_TYPE));
                $this->yamlData = new YamlData($data);
            });
            it('should get schema correctly', function () {
                $validUser = $this->yamlData->getSchema('valid_user');
                $expected = ['id' => 1, 'name' => 'Taro', 'created' => '2014-01-01 00:00:00'];
                expect($validUser)->to->equal($expected);
            });
            it('should get nested data', function () {
Exemple #2
0
<?php

namespace Kahlan\Spec\Suite\Analysis;

use Exception;
use Kahlan\Analysis\Debugger;
use Kahlan\Plugin\Stub;
describe("Debugger", function () {
    beforeEach(function () {
        $this->loader = Debugger::loader();
    });
    afterEach(function () {
        Debugger::loader($this->loader);
    });
    describe("::trace()", function () {
        it("returns a default backtrace string", function () {
            $backtrace = Debugger::trace();
            expect($backtrace)->toBeA('string');
            $backtrace = explode("\n", $backtrace);
            expect(empty($backtrace))->toBe(false);
        });
        it("returns a custom backtrace string", function () {
            $backtrace = Debugger::trace(['trace' => debug_backtrace()]);
            expect($backtrace)->toBeA('string');
            $backtrace = explode("\n", $backtrace);
            expect(empty($backtrace))->toBe(false);
        });
        it("returns a backtrace of an Exception", function () {
            $backtrace = Debugger::trace(['trace' => new Exception('World Destruction Error!')]);
            expect($backtrace)->toBeA('string');
            $backtrace = explode("\n", $backtrace);
            $carry[] = $item['name'];
            return $carry;
        });
        expect($names)->toBe(['gebert', 'marvin.maybelle', 'zabernathy']);
    });
    it("should order", function () {
        $_GET = ['columns' => [['data' => 'name', 'searchable' => "true"]], 'order' => [['column' => 0, 'dir' => 'desc']]];
        $dataTables = new QueryBuilder(20);
        $dataTables->setBuilder($this->builder);
        $dataTables->setColumns(['name', 'email']);
        $dataTables->setParser(new ParamsParser(10));
        $response = $dataTables->getResponse();
        expect(count($response['data']))->toBe(10);
        expect($response['data'][0]['name'])->toBe('zcremin');
    });
    it("should order asc", function () {
        $_GET = ['columns' => [['data' => 'name', 'searchable' => "true"]], 'order' => [['column' => 0, 'dir' => 'asc']]];
        $dataTables = new QueryBuilder(20);
        $dataTables->setBuilder($this->builder);
        $dataTables->setColumns(['name', 'email']);
        $dataTables->setParser(new ParamsParser(10));
        $response = $dataTables->getResponse();
        expect(count($response['data']))->toBe(10);
        expect($response['data'][0]['name'])->toBe('adelia13');
    });
    afterEach(function () {
        unset($_GET);
        unset($_POST);
        unset($_REQUEST);
    });
});
Exemple #4
0
             touch($this->temp . DS . 'CachedClass.php', $time - 1);
             $this->interceptor->watch([$this->temp . DS . 'watched1.php', $this->temp . DS . 'watched2.php']);
             expect($this->interceptor->cached($this->temp . DS . 'CachedClass.php'))->toBe(false);
         });
     });
 });
 describe("->clearCache()", function () {
     beforeEach(function () {
         $this->customCachePath = Dir::tempnam(null, 'cache');
         $this->interceptor = Interceptor::patch(['cachePath' => $this->customCachePath]);
         $this->temp = Dir::tempnam(null, 'cache');
         $this->interceptor->cache($this->temp . DS . 'CachedClass1.php', '');
         $this->interceptor->cache($this->temp . DS . 'nestedDir/CachedClass2.php', '');
     });
     afterEach(function () {
         Dir::remove($this->temp);
     });
     it("clears the cache", function () {
         $this->interceptor->clearCache();
         expect(file_exists($this->customCachePath))->toBe(false);
     });
     it("bails out if the cache has already been cleared", function () {
         $this->interceptor->clearCache();
         $this->interceptor->clearCache();
         expect(file_exists($this->customCachePath))->toBe(false);
     });
 });
 describe("->watch()/unwatch()", function () {
     it("add some file to be watched", function () {
         $this->temp = Dir::tempnam(null, 'cache');
         touch($this->temp . DS . 'watched1.php');
Exemple #5
0
use Exception;
use RuntimeException;
use stdClass;
use DateTime;
use Kahlan\Specification;
use Kahlan\Matcher;
use Kahlan\Expectation;
use Kahlan\Plugin\Stub;
describe("Expectation", function () {
    beforeEach(function () {
        $this->matchers = Matcher::get();
    });
    afterEach(function () {
        Matcher::reset();
        foreach ($this->matchers as $name => $value) {
            foreach ($value as $for => $class) {
                Matcher::register($name, $class, $for);
            }
        }
    });
    describe("->__call()", function () {
        it("throws an exception when using an undefined matcher name", function () {
            $closure = function () {
                $result = Expectation::expect(true)->toHelloWorld(true);
            };
            expect($closure)->toThrow(new Exception("Unexisting matcher attached to `'toHelloWorld'`."));
        });
        it("throws an exception when a specific class matcher doesn't match", function () {
            Matcher::register('toEqualCustom', Stub::classname(['extends' => 'Kahlan\\Matcher\\ToEqual']), 'stdClass');
            $closure = function () {
                $result = Expectation::expect([])->toEqualCustom(new stdClass());
            };
Exemple #6
0
<?php

namespace Lead\Net\Spec\Suite\Http;

use Lead\Collection\Collection;
use Lead\Net\Http\Format;
use Lead\Net\Http\Media;
use Lead\Net\Http\Response;
describe("Media", function () {
    afterEach(function () {
        Media::reset();
    });
    describe("::set()", function () {
        it("supports custom handlers", function () {
            Media::set('csv', ['application/csv'], ['encode' => function ($data) {
                ob_start();
                $out = fopen('php://output', 'w');
                foreach ($data as $record) {
                    fputcsv($out, $record);
                }
                fclose($out);
                return ob_get_clean();
            }]);
            $response = new Response();
            $response->format('csv');
            $data = [['John', 'Doe', '123 Main St.', 'Anytown, CA', '91724'], ['Jane', 'Doe', '124 Main St.', 'Anytown, CA', '91724']];
            $response->set($data);
            $expected = 'John,Doe,"123 Main St.","Anytown, CA",91724' . "\n";
            $expected .= 'Jane,Doe,"124 Main St.","Anytown, CA",91724' . "\n";
            expect($response->body())->toBe($expected);
            expect((string) $response->headers['Content-Type'])->toBe('Content-Type: application/csv');
Exemple #7
0
namespace chaos\spec\suite;

use stdClass;
use DateTime;
use InvalidArgumentException;
use chaos\Model;
use chaos\Schema;
use chaos\collection\Collection;
use kahlan\plugin\Stub;
describe("Model", function () {
    before(function () {
        $this->model = Stub::classname(['extends' => Model::class]);
    });
    afterEach(function () {
        $model = $this->model;
        $model::reset();
    });
    describe("::config()", function () {
        it("configures the model", function () {
            $model = $this->model;
            $model::config(['schema' => $schema = Stub::create(), 'validator' => $validator = Stub::create(), 'finders' => $finders = Stub::create(), 'query' => $query = ['option' => 'value'], 'connection' => $connection = Stub::create(), 'conventions' => $conventions = Stub::create()]);
            expect($model::schema())->toBe($schema);
            expect($model::validator())->toBe($validator);
            expect($model::finders())->toBe($finders);
            expect($model::query())->toBe($query);
            expect($model::connection())->toBe($connection);
            expect($model::conventions())->toBe($conventions);
            $model::reset();
            expect($model::schema())->not->toBe($schema);
            expect($model::validator())->not->toBe($validator);
            expect($model::finders())->not->toBe($finders);
Exemple #8
0
    $_POST = $config['POST'];
    $_FILES = $config['FILES'];
    return $config;
}
describe("Request", function () {
    beforeAll(function () {
        $this->globalNames = ['_GET', '_POST', '_SERVER'];
        $this->oldEnv = [];
        foreach ($this->globalNames as $varname) {
            $this->oldEnv[$varname] = $GLOBALS[$varname];
            unset($GLOBALS[$varname]);
        }
    });
    afterEach(function () {
        foreach ($this->globalNames as $varname) {
            $GLOBALS[$varname] = $this->oldEnv[$varname];
        }
    });
    describe("__construct", function () {
        it("sets default values", function () {
            $request = new Request();
            expect($request->export())->toEqual(['basePath' => '', 'locale' => null, 'data' => [], 'params' => [], 'env' => $request->env, 'method' => 'GET', 'scheme' => 'http', 'version' => '1.1', 'host' => 'localhost', 'port' => 80, 'path' => '/', 'query' => '', 'fragment' => '', 'username' => null, 'password' => null, 'url' => 'http://localhost/', 'stream' => $request->stream()]);
            $expected = <<<EOD
Host: localhost
Connection: Close
User-Agent: Mozilla/5.0
Content-Type: text/html; charset=utf-8


EOD;
            expect((string) $request->headers)->toBe($expected);
Exemple #9
0
            $this->schema->formatter('cast', 'id', $handlers['integer']);
            $this->schema->formatter('cast', 'serial', $handlers['integer']);
            $this->schema->formatter('cast', 'integer', $handlers['integer']);
            $this->schema->formatter('cast', 'float', $handlers['float']);
            $this->schema->formatter('cast', 'decimal', $handlers['decimal']);
            $this->schema->formatter('cast', 'date', $handlers['date']);
            $this->schema->formatter('cast', 'datetime', $handlers['datetime']);
            $this->schema->formatter('cast', 'boolean', $handlers['boolean']);
            $this->schema->formatter('cast', 'null', $handlers['null']);
            $this->schema->formatter('cast', 'string', $handlers['string']);
            $this->schema->formatter('cast', '_default_', $handlers['string']);
            $this->schema->bind('gallery', ['relation' => 'belongsTo', 'to' => Gallery::class, 'keys' => ['gallery_id' => 'id']]);
            $this->schema->bind('images_tags', ['relation' => 'hasMany', 'to' => ImageTag::class, 'keys' => ['id' => 'image_id']]);
            $this->schema->bind('tags', ['relation' => 'hasManyThrough', 'to' => Tag::class, 'through' => 'images_tags', 'using' => 'tag']);
        });
        afterEach(function () {
            Image::reset();
        });
        it("gets/sets the conventions", function () {
            $image = $this->schema->cast(null, ['id' => '1', 'gallery_id' => '2', 'name' => 'image.jpg', 'title' => 'My Image', 'score' => '8.9', 'tags' => [['id' => '1', 'name' => 'landscape'], ['id' => '2', 'name' => 'mountain']]]);
            expect($image->id)->toBeAn('integer');
            expect($image->gallery_id)->toBeAn('integer');
            expect($image->name)->toBeA('string');
            expect($image->title)->toBeA('string');
            expect($image->score)->toBeA('float');
            expect($image->tags)->toBeAnInstanceOf('chaos\\collection\\Through');
            expect($image->tags[0])->toBeAnInstanceOf('chaos\\spec\\fixture\\model\\Tag');
            expect($image->tags[1])->toBeAnInstanceOf('chaos\\spec\\fixture\\model\\Tag');
        });
    });
});
Exemple #10
0
<?php

use Peridot\Core\Context;
use Peridot\Core\SuiteLoader;
describe("SuiteLoader", function () {
    beforeEach(function () {
        $this->context = Context::getInstance();
        $this->loader = new SuiteLoader('*.spec.php', $this->context);
        $this->fixtures = __DIR__ . '/../fixtures';
        $this->file = $this->context->getFile();
    });
    afterEach(function () {
        $this->context->setFile($this->file);
    });
    describe('->getTests()', function () {
        it("should return file paths matching *.spec.php recursively", function () {
            $tests = $this->loader->getTests($this->fixtures);
            $actual = count($tests);
            assert($actual == 4, "expected 4, got {$actual}");
        });
        it("should return single file if it exists", function () {
            $test = $this->loader->getTests($this->fixtures . '/test.spec.php');
            assert(count($test) == 1, "suite loader should load 1 spec");
        });
        it("should throw exception if path not found", function () {
            $exception = null;
            try {
                $this->loader->getTests('nope');
            } catch (Exception $e) {
                $exception = $e;
            }
<?php

use Evenement\EventEmitter;
use Peridot\Concurrency\Environment\Environment;
use Peridot\Configuration;
describe('Environment', function () {
    beforeEach(function () {
        $this->emitter = new EventEmitter();
        $this->readStream = tmpfile();
        $this->writeStream = tmpfile();
        $this->environment = new Environment($this->emitter, $this->readStream, $this->writeStream);
    });
    afterEach(function () {
        fclose($this->readStream);
        fclose($this->writeStream);
    });
    describe('->getEventEmitter()', function () {
        it('should return the event emitter', function () {
            expect($this->environment->getEventEmitter())->to->equal($this->emitter);
        });
    });
    describe('->getReadStream()', function () {
        it('should return the read stream', function () {
            expect($this->environment->getReadStream())->to->equal($this->readStream);
        });
    });
    describe('->getWriteStream()', function () {
        it('should return the write stream', function () {
            expect($this->environment->getWriteStream())->to->equal($this->writeStream);
        });
    });
     $config = new Configuration();
     $config->setDsl(__DIR__ . '/../../../../fixtures/environment/dsl.php');
     $config->setConfigurationFile(__DIR__ . '/../../../../fixtures/environment/peridot.php');
     $reader = $this->getProphet()->prophesize('Peridot\\Concurrency\\Environment\\ReaderInterface');
     $reader->getConfiguration()->willReturn($config);
     $looper = $this->getProphet()->prophesize('Peridot\\Concurrency\\Runner\\StreamSelect\\Application\\LooperInterface');
     $looper->loop(Argument::type('Peridot\\Runner\\Context'), $environment, $this->message)->shouldBeCalled();
     $this->application = new Application($environment, $reader->reveal(), $looper->reveal());
     /**
      * An application does not listen until run.
      */
     $this->application->run($this->message);
 });
 afterEach(function () {
     fclose($this->readStream);
     fclose($this->writeStream);
     $this->getProphet()->checkPredictions();
 });
 context('when a suite.start event is emitted', function () {
     it('should write a suite.start event to the test message', function () {
         $suite = new Suite('description');
         $suite->setTitle('my title');
         $this->emitter->emit('suite.start', [$suite]);
         $this->expectMessageValues($this->writeStream, ['s', 'suite.start', 'description', 'my title']);
     });
     it('should write nothing if the suite has no description', function () {
         $suite = new Suite('');
         $this->emitter->emit('suite.start', [$suite]);
         $content = $this->readMessage($this->writeStream);
         expect($content)->to->be->empty;
     });
                putenv('ANSICON=1');
            });
            afterEach(function () {
                putenv('ANSICON=' . $this->ansicon);
            });
            it('should add escape sequences if ansicon is enabled', function () {
                $colored = $this->reporter->color('success', 'good');
                assert($colored == "good", "expected color with ansicon enabled");
            });
        });
        context('when in a tty terminal', function () {
            beforeEach(function () {
                $this->reporter = new TtyTestReporter(new Configuration(), new ConsoleOutput(), new EventEmitter());
            });
            afterEach(function () {
                putenv('PERIDOT_TTY=');
            });
            it('should set the PERIDOT_TTY environment variable', function () {
                $this->reporter->color('success', 'text');
                assert(getenv('PERIDOT_TTY') !== false, "peridot tty environment variable should have been set");
            });
            it('should write colors if the PERIDOT_TTY environment variable is present', function () {
                putenv('PERIDOT_TTY=1');
                $text = $this->reporter->color('success', 'text');
                assert("text" == $text, "colored text should have been written");
            });
        });
    });
});
class WindowsTestReporter extends AbstractBaseReporter
{
Exemple #14
0
            $this->context->addSetupFunction($before);
            $result = call_user_func($this->context->getCurrentSuite()->getSetupFunctions()[0]);
            assert("result" === $result, "expected addSetupFunction to register setup function");
        });
    });
    describe('->addTearDownFunction()', function () {
        it('should register an afterEach callback on the current suite', function () {
            $after = function () {
                return "result";
            };
            $this->context->addTearDownFunction($after);
            $result = call_user_func($this->context->getCurrentSuite()->getTearDownFunctions()[0]);
            assert("result" === $result, "expected addSetupFunction to register tear down function");
        });
    });
    describe('::getInstance()', function () {
        beforeEach(function () {
            $this->property = $this->reflection->getProperty('instance');
            $this->property->setAccessible(true);
            $this->previous = $this->property->getValue();
            $this->property->setValue(null);
        });
        afterEach(function () {
            $this->property->setValue($this->previous);
        });
        it("should return a singleton instance of Context", function () {
            $context = Context::getInstance();
            assert($context instanceof Context, "getInstance should return a Context");
        });
    });
});
Exemple #15
0
<?php

namespace Lead\Validator\Spec\Suite;

use InvalidArgumentException;
use stdClass;
use DateTime;
use Lead\Validator\Checker;
use Kahlan\Plugin\Monkey;
describe("Checker", function () {
    afterEach(function () {
        Checker::reset();
    });
    describe("::set()", function () {
        it("adds some local handlers", function () {
            Checker::set('zeroToNine', '/^[0-9]$/');
            Checker::set('tenToNineteen', '/^1[0-9]$/');
            expect(Checker::handlers())->toContainKeys('zeroToNine', 'tenToNineteen');
        });
        it("sets validation handlers", function () {
            Checker::set('zeroToNine', '/^[0-9]$/');
            Checker::set('tenToNineteen', '/^1[0-9]$/');
            expect(Checker::has('zeroToNine'))->toBe(true);
            expect(Checker::has('tenToNineteen'))->toBe(true);
            expect(Checker::get('zeroToNine'))->toBe('/^[0-9]$/');
            expect(Checker::get('tenToNineteen'))->toBe('/^1[0-9]$/');
        });
    });
    describe("::get()", function () {
        it("throws an exceptions for unexisting validation handler", function () {
            $closure = function () {
         expect($items[1]->getId())->should('be', $fixtureIds[1]);
         expect($items[2]->getId())->should('be', $fixtureIds[2]);
         expect($items[3]->getId())->should('be', $item->getId());
     });
 });
 describe('getPrevious() and getNext()', function () {
     $fixtureIds = null;
     beforeEach(function () use(&$fixtureIds) {
         Project::sc()->createService('EntityManager');
         $em = Project::sc()->em();
         $em->beginTransaction();
         $repository = $em->getRepository('Gradua\\DoctrineExtensions\\OrderedItem\\ExampleEntities\\OrderedItem');
         $fixtureIds = OrderedItemFixtures::threeNonSequencialItems($em);
     });
     afterEach(function () {
         Project::sc()->em()->rollback();
     });
     it('should get the previous item', function () use(&$fixtureIds) {
         $em = Project::sc()->em();
         $repository = $em->getRepository('Gradua\\DoctrineExtensions\\OrderedItem\\ExampleEntities\\OrderedItem');
         $items = $repository->findAll();
         expect($repository->getPrevious($items[1])->getId())->should('be', $items[0]->getId());
     });
     it('should get the previous item when there are more than one result on the database', function () use(&$fixtureIds, &$parentId) {
         $em = Project::sc()->em();
         $repository = $em->getRepository('Gradua\\DoctrineExtensions\\OrderedItem\\ExampleEntities\\OrderedItem');
         $items = $repository->findAll();
         expect($repository->getPrevious($items[2])->getId())->should('be', $items[1]->getId());
     });
     it('should get null when there is no previous item', function () use(&$fixtureIds) {
         $em = Project::sc()->em();
Exemple #17
0
         expect($this->nb)->toBe(4);
     });
 });
 describe("->after()", function () {
     $this->nb = 0;
     after(function () {
         $this->nb++;
     });
     it("passes if `after` has not been executed", function () {
         expect($this->nb)->toBe(0);
     });
 });
 describe("->afterEach()", function () {
     $this->nb = 0;
     afterEach(function () {
         $this->nb++;
     });
     it("passes if `afterEach` has not been executed", function () {
         expect($this->nb)->toBe(0);
     });
     it("passes if `afterEach` has been executed", function () {
         expect($this->nb)->toBe(1);
     });
     context("with sub scope", function () {
         it("passes if `afterEach` has been executed once more", function () {
             expect($this->nb)->toBe(2);
         });
     });
     it("passes if `afterEach` has been executed once more", function () {
         expect($this->nb)->toBe(3);
     });
<?php

use Calculator\Number\Number;
use Calculator\Exception\InvalidNumberException;
describe('Number', function () {
    beforeEach(function () {
        $this->obj = new Number(123);
    });
    afterEach(function () {
    });
    describe('constructor', function () {
        it('constructs with correct value', function () {
            expect(function () {
                new Number(456);
            })->not->toThrow(new InvalidNumberException(456));
            expect(function () {
                new Number(4.56);
            })->not->toThrow(new InvalidNumberException(4.56));
            expect(function () {
                new Number('456');
            })->toThrow(new InvalidNumberException('456'));
            expect(function () {
                new Number('4.56');
            })->toThrow(new InvalidNumberException('4.56'));
            expect(function () {
                new Number('abc');
            })->toThrow(new InvalidNumberException('abc'));
            expect(function () {
                new Number(true);
            })->toThrow(new InvalidNumberException(true));
            expect(function () {
Exemple #19
0
use stdClass;
use DateTime;
use InvalidArgumentException;
use Chaos\Model;
use Chaos\Schema;
use Chaos\Collection\Collection;
use Kahlan\Plugin\Double;
describe("Model", function () {
    beforeAll(function () {
        $model = $this->model = Double::classname(['extends' => Model::class]);
        $model::definition()->locked(false);
    });
    afterEach(function () {
        $model = $this->model;
        $model::reset();
        $model::definition()->locked(false);
    });
    describe("::conventions()", function () {
        it("gets/sets a conventions", function () {
            $conventions = Double::instance();
            $model = $this->model;
            $model::conventions($conventions);
            expect($model::conventions())->toBe($conventions);
        });
    });
    describe("::connection()", function () {
        it("gets/sets a connection", function () {
            $connection = Double::instance();
            allow($connection)->toReceive('formatters')->andRun(function () {
                return [];
Exemple #20
0
<?php

namespace Lead\Net\Spec\Suite;

use Exception;
use Lead\Net\NetException;
use Lead\Net\Scheme;
describe("Scheme", function () {
    afterEach(function () {
        Scheme::reset();
    });
    describe("::registered()", function () {
        it("returns default registered schemes", function () {
            expect(Scheme::registered())->toBe(['ftp' => 21, 'ssh' => 22, 'telnet' => 23, 'smtp' => 25, 'http' => 80, 'sftp' => 115, 'imap' => 143, 'https' => 443, 'smtps' => 587]);
        });
    });
    describe("::register()", function () {
        it("registers a scheme", function () {
            Scheme::register('time', 37);
            expect(Scheme::port('time'))->toBe(37);
        });
        it("override a scheme", function () {
            Scheme::register('http', 8080);
            expect(Scheme::port('http'))->toBe(8080);
        });
    });
    describe("::unregister()", function () {
        it("unregisters a scheme", function () {
            Scheme::register('time', 37);
            expect(Scheme::port('time'))->toBe(37);
            Scheme::unregister('time');
Exemple #21
0
     });
     it("removes a directory recursively respecting the exclude option", function () {
         Dir::copy('spec/Fixture', $this->tmpDir);
         Dir::remove($this->tmpDir, ['exclude' => '*.txt']);
         $files = Dir::scan($this->tmpDir, ['type' => 'file']);
         sort($files);
         expect($files)->toBe($this->normalize([$this->tmpDir . '/Fixture/Extensions/Childs/child1.txt', $this->tmpDir . '/Fixture/Nested/Childs/child1.txt', $this->tmpDir . '/Fixture/Nested/nested_file1.txt', $this->tmpDir . '/Fixture/Nested/nested_file2.txt', $this->tmpDir . '/Fixture/file1.txt']));
     });
 });
 describe("::make()", function () {
     beforeEach(function () {
         $this->umask = umask(0);
         $this->tmpDir = Dir::tempnam(sys_get_temp_dir(), 'spec');
     });
     afterEach(function () {
         Dir::remove($this->tmpDir);
         umask($this->umask);
     });
     it("creates a nested directory", function () {
         $path = $this->tmpDir . '/My/Nested/Directory';
         $actual = Dir::make($path);
         expect($actual)->toBe(true);
         expect(file_exists($path))->toBe(true);
         $stat = stat($path);
         $mode = $stat['mode'] & 0777;
         expect($mode)->toBe(0755);
     });
     it("creates a nested directory with a specific mode", function () {
         $path = $this->tmpDir . '/My/Nested/Directory';
         $actual = Dir::make($path, ['mode' => 0777]);
         expect($actual)->toBe(true);
         expect(file_exists($path))->toBe(true);
Exemple #22
0
use Lead\Filter\Spec\Fixture\Jit\Patcher\Parrot3;
use Lead\Filter\Spec\Fixture\FilterExample;
describe("Filters", function () {
    beforeEach(function () {
        $this->filter1 = function ($next, $message) {
            return "1" . $next($message) . "1";
        };
        $this->filter2 = function ($next, $message) {
            return "2" . $next($message) . "2";
        };
        $this->noChain = function ($next, $message) {
            return "Hello";
        };
    });
    afterEach(function () {
        Filters::reset();
    });
    context("with an instance context", function () {
        beforeEach(function () {
            $this->stub = new FilterExample();
        });
        describe("::apply()", function () {
            it("applies a filter", function () {
                Filters::apply($this->stub, 'filterable', $this->filter1);
                expect($this->stub->filterable('World!'))->toBe('1Hello World!1');
            });
            it("applies filters on each call", function () {
                Filters::apply($this->stub, 'filterable', $this->filter1);
                expect($this->stub->filterable('World!'))->toBe('1Hello World!1');
                expect($this->stub->filterable('World!'))->toBe('1Hello World!1');
                expect($this->stub->filterable('World!'))->toBe('1Hello World!1');
     $this->connection = $connection;
     $this->fixtures = new Fixtures(['connection' => $connection, 'fixtures' => ['gallery' => 'Chaos\\Database\\Spec\\Fixture\\Schema\\Gallery', 'gallery_detail' => 'Chaos\\Database\\Spec\\Fixture\\Schema\\GalleryDetail', 'image' => 'Chaos\\Database\\Spec\\Fixture\\Schema\\Image', 'image_tag' => 'Chaos\\Database\\Spec\\Fixture\\Schema\\ImageTag', 'tag' => 'Chaos\\Database\\Spec\\Fixture\\Schema\\Tag']]);
     $this->fixtures->populate('gallery', ['create']);
     $this->fixtures->populate('gallery_detail', ['create']);
     $this->fixtures->populate('image', ['create']);
     $this->fixtures->populate('image_tag', ['create']);
     $this->fixtures->populate('tag', ['create']);
     $this->gallery = $this->fixtures->get('gallery')->model();
     $this->galleryDetail = $this->fixtures->get('gallery_detail')->model();
     $this->image = $this->fixtures->get('image')->model();
     $this->image_tag = $this->fixtures->get('image_tag')->model();
     $this->tag = $this->fixtures->get('tag')->model();
     $this->query = new Query(['model' => $this->gallery]);
 });
 afterEach(function () {
     $this->fixtures->drop();
     $this->fixtures->reset();
 });
 describe("->__construct()", function () {
     it("throws an error if no schema is available", function () {
         $closure = function () {
             $this->query = new Query();
         };
         expect($closure)->toThrow(new DatabaseException("Error, missing schema for this query."));
     });
 });
 describe("->statement()", function () {
     it("returns the select statement", function () {
         $statement = $this->query->statement();
         $class = get_class($statement);
         $pos = strrpos($class, '\\');
         $basename = substr($class, $pos !== false ? $pos + 1 : 0);
Exemple #24
0
describe("Filter", function () {
    beforeEach(function () {
        Filter::register('spec.my_prefix', function ($chain, $message) {
            $message = "My {$message}";
            return $chain->next($message);
        });
        Filter::register('spec.be_prefix', function ($chain, $message) {
            $message = "Be {$message}";
            return $chain->next($message);
        });
        Filter::register('spec.no_chain', function ($chain, $message) {
            return "No Man's {$message}";
        });
    });
    afterEach(function () {
        Filter::reset();
        Filter::enable();
    });
    context("with an instance context", function () {
        beforeEach(function () {
            $this->mock = Stub::create(['uses' => ['Kahlan\\Filter\\Behavior\\Filterable']]);
            Stub::on($this->mock)->method('filterable', function () {
                return Filter::on($this, 'filterable', func_get_args(), function ($chain, $message) {
                    return "Hello {$message}";
                });
            });
        });
        describe("::apply()", function () {
            it("applies a filter which override a parameter", function () {
                Filter::apply($this->mock, 'filterable', 'spec.my_prefix');
                expect($this->mock->filterable('World!'))->toBe('Hello My World!');
            });
            });
            $this->worker->run('some path');
            $message->emit('end', [$message]);
            $this->completed = $theWorker;
        });
        it('should emit a peridot.concurrency.worker.completed event for the worker that has the message resource', function () {
            expect($this->completed)->to->equal($this->worker);
        });
        it('should set the total job time elapsed', function () {
            $info = $this->completed->getJobInfo();
            expect($info->end)->to->not->be->null;
        });
    });
    context('when peridot.concurrency.worker.completed event is emitted', function () {
        afterEach(function () {
            $this->getProphet()->checkPredictions();
        });
        it('should free the completed worker', function () {
            $worker = $this->workers[0];
            $worker->free()->shouldBeCalled();
            $this->emitter->emit('peridot.concurrency.worker.completed', [$worker->reveal()]);
        });
        it('should reduce the running workers', function () {
            $worker = new Worker('bin', $this->emitter, new TmpfileOpen());
            $this->pool->attach($worker);
            $worker->run('some path');
            $this->emitter->emit('peridot.concurrency.worker.completed', [$worker]);
            expect($this->pool->getRunning())->to->have->length(0);
        });
    });
});
<?php

/**
 * Specs for the MockableSingletonBehavior trait
 * Testing is accomplished using the simple MockableSingleton implementation defined in src/
 */
use Mockleton\Test\Implementations\MockableSingletonConstructorArgumentSpy;
use Mockleton\Test\Implementations\MockableNullableInstanceSingleton;
describe('MockableSingletonBehavior trait', function () {
    afterEach(function () {
        MockableNullableInstanceSingleton::unregisterSingletonInstance();
    });
    describe('::registerSingletonInstance($instance)', function () {
        it('should allow registering a specific instance as the singleton', function () {
            $instance = new MockableNullableInstanceSingleton();
            MockableNullableInstanceSingleton::registerSingletonInstance($instance);
            assert(MockableNullableInstanceSingleton::getInstance() === $instance);
        });
        it('should throw TypeError if instance type mismatch', function () {
            try {
                $instance = new stdClass();
                MockableNullableInstanceSingleton::registerSingletonInstance($instance);
            } catch (TypeError $e) {
                assert($e->getMessage() === 'Attempting to register a singleton instance which is not of the same type');
                return;
            }
            throw new Exception('Failed to throw exception on instance type mismatch');
        });
        it('should throw RuntimeException if an instance is already registered', function () {
            try {
                MockableNullableInstanceSingleton::registerSingletonInstance(new MockableNullableInstanceSingleton());
Exemple #27
0
<?php

use Mockery as m;
use Tusk\Expectation;
describe('Expectation', function () {
    afterEach(function () {
        m::close();
    });
    describe('__call()', function () {
        beforeEach(function () {
            $this->matcher = m::mock('Tusk\\Matcher', ['getMessageFormat' => 'failed']);
            $this->prettyPrinter = m::mock('Tusk\\PrettyPrinter');
            $this->expectation = new Expectation(12, ['toBe' => $this->matcher], $this->prettyPrinter);
        });
        it('should invoke a matcher object with the expectation value', function () {
            $this->matcher->shouldReceive('match')->with(12, [13, 14])->andReturn(true);
            $this->expectation->toBe(13, 14);
        });
        it('should throw an exception if the comparison returns false', function () {
            $this->matcher->shouldReceive('match')->with(12, [15, 16])->andReturn(false);
            $this->prettyPrinter->shouldReceive('format')->with('failed', 12, [15, 16], false)->andReturn('foo')->once();
            expect(function () {
                $this->expectation->toBe(15, 16);
            })->toThrow('Tusk\\ExpectationException', 'foo');
        });
        it('should reverse the above behaviour if matcher name is preceded by "not"', function () {
            $this->matcher->shouldReceive('match')->with(12, [13, 14])->andReturn(false);
            $this->expectation->notToBe(13, 14);
            $this->matcher->shouldReceive('match')->with(12, [15, 16])->andReturn(true);
            $this->prettyPrinter->shouldReceive('format')->with('failed', 12, [15, 16], true)->andReturn('bar')->once();
            expect(function () {
Exemple #28
0
<?php

namespace Chaos\Spec\Suite;

use Chaos\ChaosException;
use Chaos\Spec\Fixture\Model\Image;
use Chaos\Spec\Fixture\Model\ImageTag;
use Chaos\Spec\Fixture\Model\Tag;
use Chaos\Spec\Fixture\Model\Gallery;
use Chaos\Spec\Fixture\Model\GalleryDetail;
describe("Relationship", function () {
    afterEach(function () {
        Gallery::reset();
        Image::reset();
    });
    describe("->counterpart()", function () {
        it("returns the counterpart relationship for belongsTo/hasMany relations", function () {
            $relation = Image::definition()->relation('gallery');
            expect($relation->counterpart())->toBe(Gallery::definition()->relation('images'));
            $relation = Gallery::definition()->relation('images');
            expect($relation->counterpart())->toBe(Image::definition()->relation('gallery'));
        });
        it("returns the counterpart relationship for belongsTo/hasOne relations", function () {
            $relation = GalleryDetail::definition()->relation('gallery');
            expect($relation->counterpart())->toBe(Gallery::definition()->relation('detail'));
            $relation = Gallery::definition()->relation('detail');
            expect($relation->counterpart())->toBe(GalleryDetail::definition()->relation('gallery'));
        });
        it("returns the counterpart relationship for hasMany/hasMany relations", function () {
            $relation = Image::definition()->relation('tags');
            expect($relation->counterpart())->toBe(Tag::definition()->relation('images'));
Exemple #29
0
         expect($coverage['source'])->toBe(file_get_contents($path));
         expect($coverage['coverage'])->toHaveLength(16);
         expect(array_filter($coverage['coverage'], function ($value) {
             return $value === 0;
         }))->toHaveLength(2);
         expect(array_filter($coverage['coverage'], function ($value) {
             return $value === null;
         }))->toHaveLength(12);
     });
 });
 describe("::write()", function () {
     beforeEach(function () {
         $this->output = tempnam("/tmp", "KAHLAN");
     });
     afterEach(function () {
         unlink($this->output);
     });
     it("writes the coverage to a file", function () {
         $path = 'spec' . DS . 'Fixture' . DS . 'Reporter' . DS . 'Coverage' . DS . 'ExtraEmptyLine.php';
         $collector = new Collector(['driver' => $this->driver, 'path' => $path]);
         $code = new ExtraEmptyLine();
         $collector->start();
         $code->shallNotPass();
         $collector->stop();
         $success = Coveralls::write(['collector' => $collector, 'file' => $this->output, 'service_name' => 'kahlan-ci', 'service_job_id' => '123', 'repo_token' => 'ABC']);
         expect($success)->toBe(585);
         $json = file_get_contents($this->output);
         $actual = json_decode($json, true);
         unset($actual['run_at']);
         expect($actual['service_name'])->toBe('kahlan-ci');
         expect($actual['service_job_id'])->toBe('123');
     $this->command->setRunner($this->runner);
     $this->command->setApplication($this->application);
 };
 context('when using the --no-colors option', function () use($withMockFactory) {
     beforeEach($withMockFactory);
     afterEach([$this->prophet, 'checkPredictions']);
     it('allows setting whether the reporter uses colors', function () {
         $reporter = new SpecReporter($this->output, $this->emitter, $this->context);
         $this->factory->create(Argument::any())->willReturn($reporter);
         $this->command->run(new ArrayInput(['--no-colors' => true]), $this->output);
         assert($reporter->areColorsEnabled() === false);
     });
 });
 context('when using the -r option', function () use($withMockFactory) {
     beforeEach($withMockFactory);
     afterEach([$this->prophet, 'checkPredictions']);
     it('allows setting which reporter to use', function () {
         $reporter = new SpecReporter($this->output, $this->emitter, $this->context);
         $this->factory->create('anon')->willReturn($reporter);
         $this->command->run(new ArrayInput(['-r' => 'anon']), $this->output);
     });
 });
 context('when using the --grep option', function () {
     it('sets the pattern used by the loader', function () {
         $this->command->run(new ArrayInput(['--grep' => '*.test.php'], $this->definition), $this->output);
         $pattern = $this->command->getLoader()->getPattern();
         assert($pattern === '*.test.php');
     });
 });
 context('when using the --reporters option', function () {
     it('should list reporters', function () {