public static function initializeAMQPStubs() { Stub::on('AMQPChannel')->method('__construct'); Stub::on('AMQPChannel')->method('qos'); Stub::on('AMQPExchange')->method('__construct'); Stub::on('AMQPExchange')->method('declareExchange'); Stub::on('AMQPQueue')->method('__construct'); Stub::on('AMQPQueue')->method('declareQueue'); Stub::on('AMQPQueue')->method('bind'); }
/** * Constructor * * @param string|object $actual A fully-namespaced class name or an object instance. * @param string $expected The expected method method name to be called. */ public function __construct($actual) { if (is_string($actual)) { $actual = ltrim($actual, '\\'); } if (!is_string($actual) || class_exists($actual)) { $this->_isClass = true; $this->_stub = Stub::on($actual); } $this->_actual = $actual; }
it("bails out if no relation data hasn't been setted", function () { $belongsTo = Image::relation('gallery'); $image = Image::create(['id' => 1, 'gallery_id' => 1, 'title' => 'Amiga 1200']); expect($belongsTo->save($image))->toBe(true); }); it("saves a belongsTo relationship", function () { $belongsTo = Image::relation('gallery'); $image = Image::create(['id' => 1, 'title' => 'Amiga 1200'], ['exists' => true]); $image->gallery = ['name' => 'Foo Gallery']; Stub::on($image->gallery)->method('save', function () use($image) { $image->gallery->id = 1; return true; }); expect($image->gallery)->toReceive('save'); expect($belongsTo->save($image))->toBe(true); expect($image->gallery_id)->toBe($image->gallery->id); }); it("throws an exception if the saves relation didn't populate any ID", function () { $closure = function () { $belongsTo = Image::relation('gallery'); $image = Image::create(['id' => 1, 'gallery_id' => 1, 'title' => 'Amiga 1200'], ['exists' => true]); $image->gallery = ['name' => 'Foo Gallery']; Stub::on($image->gallery)->method('save', function () { return true; }); $belongsTo->save($image); }; expect($closure)->toThrow(new ChaosException("The `'id'` key is missing from related data.")); }); }); });
}); describe("->data()", function () { it("calls `toArray()`", function () { $collection = new Collection(['data' => [1 => 1]]); expect(Collection::class)->toReceive('::toArray')->with($collection); $collection->data(); }); }); describe("::toArray()", function () { it("converts a collection to an array", function () { $collection = new Collection(['data' => [1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5]]); expect(Collection::toArray($collection))->toBe([1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5]); }); it("converts objects which support __toString", function () { $stringable = Stub::classname(); Stub::on($stringable)->method('__toString')->andReturn('hello'); $collection = new Collection(['data' => [new $stringable()]]); expect(Collection::toArray($collection))->toBe(['hello']); }); it("converts objects using handlers", function () { $handlable = Stub::classname(); $handlers = [$handlable => function ($value) { return 'world'; }]; $collection = new Collection(['data' => [new $handlable()]]); expect(Collection::toArray($collection, compact('handlers')))->toBe(['world']); }); it("doesn't convert unsupported objects", function () { $collection = new Collection(['data' => [(object) 'an object']]); expect(Collection::toArray($collection))->toEqual([(object) 'an object']); });
it('throws an exception', function () { expect(function () { $chain = new Chain(); $chain->find($this->lat, $this->lng); })->toThrow(); }); }); context('with multiple providers', function () { beforeEach(function () { $this->time = time(); $this->p1 = Stub::create(); Stub::on($this->p1)->method('find', function ($lat, $lng, $timestamp = null) { return new ZoneInfo('America/Chicago', $timestamp); }); $this->p2 = Stub::create(); Stub::on($this->p2)->method('find', function ($lat, $lng, $timestamp = null) { throw new \RuntimeException(); }); }); context('when the first result succeeds', function () { it('returns the first successful result', function () { $chain = new Chain([$this->p1, $this->p2]); $zone = $chain->find($this->lat, $this->lng, $this->time); expect($zone->getTimestamp())->toBe($this->time); }); it('will not call any subsequent providers', function () { expect($this->p2)->not->toReceive('find'); $chain = new Chain([$this->p1, $this->p2]); $chain->find($this->lat, $this->lng, $this->time); }); });
expect($actual)->toBe($expected); }); context("with some patchers defined", function () { beforeEach(function () { $this->interceptor = Interceptor::patch(['cachePath' => $this->cachePath]); $this->patcher1 = new Patcher(); $this->patcher2 = new Patcher(); $this->patchers = $this->interceptor->patchers(); $this->patchers->add('patch1', $this->patcher1); $this->patchers->add('patch2', $this->patcher2); }); it("delegates find to patchers", function () { Stub::on($this->patcher1)->method('findFile', function ($interceptor, $class, $file) { return $file . '1'; }); Stub::on($this->patcher2)->method('findFile', function ($interceptor, $class, $file) { return $file . '2'; }); $expected = realpath('spec/Fixture/Jit/Interceptor/ClassA.php'); $actual = $this->interceptor->findFile('Kahlan\\Spec\\Fixture\\Jit\\Interceptor\\ClassA'); expect($actual)->toBe($expected . '12'); }); }); }); describe("->loadFile()", function () { beforeEach(function () { $this->interceptor = Interceptor::patch(['cachePath' => $this->cachePath]); $this->loadFileNamespacePath = Dir::tempnam(null, 'loadFileNamespace'); $this->interceptor->addPsr4('loadFileNamespace\\', $this->loadFileNamespacePath); $this->classBuilder = function ($name) { return "<?php namespace loadFileNamespace; class {$name} {} ?>";
use Illuminate\Database\Query\Builder; describe('Subquery - working with subqueries in Laravel made easy', function () { given('builder', function () { return Stub::create(['extends' => Builder::class, 'methods' => ['__construct']]); }); given('subquery', function () { return new Subquery($this->builder, 'alias'); }); it('handles query alias', function () { expect($this->subquery->getAlias())->toBe('alias'); expect($this->subquery->setAlias('different')->getAlias())->toBe('different'); }); it('provides fluent interface and evaluates to valid sql', function () { $grammar = Stub::create(); Stub::on($grammar)->method('wrapTable', function ($value) { return '`' . $value . '`'; }); $builder = $this->builder; Stub::on($builder)->methods(['from' => [$builder], 'getGrammar' => [$grammar], 'toSql' => ['select * from `users`']]); expect($this->subquery->setQuery($builder)->from('users')->getValue())->toBe('(select * from `users`) as `alias`'); }); it('Proxies methods calls to the builder', function () { expect($this->builder)->toReceive('where')->with('column', 'value'); $this->subquery->where('column', 'value'); }); it('Proxies property calls to the builder', function () { $this->subquery->prop = 'value'; expect($this->subquery->getQuery()->prop)->toBe('value'); expect($this->subquery->prop)->toBe('value'); }); });
it("lazy loads a hasOne relation", function () { Stub::on(GalleryDetail::class)->method('::all', function ($options = [], $fetchOptions = []) { $details = GalleryDetail::create([['id' => 1, 'description' => 'Foo Gallery Description', 'gallery_id' => 1]], ['type' => 'set', 'exists' => true, 'collector' => $fetchOptions['collector']]); return $details; }); $gallery = Gallery::create(['id' => 1, 'name' => 'Foo Gallery'], ['exists' => true]); expect(GalleryDetail::class)->toReceive('::all')->with(['conditions' => ['gallery_id' => 1]], ['collector' => $gallery->collector()]); expect($gallery->detail->gallery_id)->toBe($gallery->id); expect($gallery->detail->collector())->toBe($gallery->collector()); }); }); describe("->save()", function () { it("bails out if no relation data hasn't been setted", function () { $hasOne = Gallery::relation('detail'); $gallery = Gallery::create(['id' => 1, 'name' => 'Foo Gallery'], ['exists' => true]); expect($hasOne->save($gallery))->toBe(true); }); it("saves a hasOne relationship", function () { $hasOne = Gallery::relation('detail'); $gallery = Gallery::create(['id' => 1, 'name' => 'Foo Gallery'], ['exists' => true]); $gallery->detail = ['description' => 'Foo Gallery Description']; Stub::on($gallery->detail)->method('save', function () use($gallery) { $gallery->detail->id = 1; return true; }); expect($gallery->detail)->toReceive('save'); expect($hasOne->save($gallery))->toBe(true); expect($gallery->detail->gallery_id)->toBe($gallery->id); }); }); });
$hasManyThrough->embed($images, ['fetchOptions' => ['return' => 'array']]); foreach ($images as $image) { foreach ($image['images_tags'] as $index => $image_tag) { expect($image_tag['tag'])->toBe($image['tags'][$index]); expect($image['tags'][$index])->toBeAn('array'); } } }); }); describe("->get()", function () { it("lazy loads a belongsTo relation", function () { Stub::on(ImageTag::class)->method('::all', function ($options = [], $fetchOptions = []) { $imagesTags = ImageTag::create([['id' => 1, 'image_id' => 1, 'tag_id' => 1], ['id' => 2, 'image_id' => 1, 'tag_id' => 3]], ['type' => 'set', 'exists' => true, 'collector' => $fetchOptions['collector']]); return $imagesTags; }); Stub::on(Tag::class)->method('::all', function ($options = [], $fetchOptions = []) { $tags = Tag::create([['id' => 1, 'name' => 'High Tech'], ['id' => 3, 'name' => 'Computer']], ['type' => 'set', 'exists' => true, 'collector' => $fetchOptions['collector']]); return $tags; }); $image = Image::create(['id' => 1, 'gallery_id' => 1, 'title' => 'Amiga 1200'], ['exists' => true]); expect(ImageTag::class)->toReceive('::all')->with(['conditions' => ['image_id' => 1]], ['collector' => $image->collector()]); expect(Tag::class)->toReceive('::all')->with(['conditions' => ['id' => [1, 3]]], ['collector' => $image->collector()]); expect(count($image->tags))->toBe(2); expect($image->tags[0]->data())->toBe(['id' => 1, 'name' => 'High Tech']); expect($image->tags[1]->data())->toBe(['id' => 3, 'name' => 'Computer']); expect($image->tags[0]->collector())->toBe($image->collector()); expect($image->tags[1]->collector())->toBe($image->collector()); }); }); describe("->broadcast()", function () { it("bails out on save since it's just an alias", function () {
<?php namespace filter\spec\suite\behavior; use kahlan\plugin\Stub; use filter\MethodFilters; describe('Filterable', function () { beforeEach(function () { $this->mock = Stub::create(['uses' => ['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("methodFilters", function () { it("gets the `MethodFilters` instance", function () { expect($this->mock->methodFilters())->toBeAnInstanceOf('filter\\MethodFilters'); }); it("sets a new `MethodFilters` instance", function () { $methodFilters = new MethodFilters(); expect($this->mock->methodFilters($methodFilters))->toBeAnInstanceOf('filter\\MethodFilters'); expect($this->mock->methodFilters())->toBe($methodFilters); }); }); });
expect($uri->getQuery())->toBe(''); expect($uri->getFragment())->toBe(''); }); it('accepts an array with the path components', function () { $uri = new Uri(['path' => '/', 'query' => 'foo&bar']); expect($uri->getPath())->toBe('/'); expect($uri->getQuery())->toBe('foo&bar'); }); it('accepts an instance of iself and extracts the components', function () { $uri0 = new Uri('/'); $uri1 = new Uri($uri0); expect($uri1->getPath())->toBe('/'); }); it('accepts an instance of UriInterface and re-generate the components', function () { $uri0 = Stub::create(['implements' => [UriInterface::class]]); Stub::on($uri0)->method('getPath')->andReturn('/'); $uri1 = new Uri($uri0); expect($uri1->getPath())->toBe('/'); }); it('throws InvalidArgumentException when uri is malformed', function () { expect(function () { new Uri('https://@/path'); })->toThrow(new InvalidArgumentException()); }); it('throws InvalidArgumentException when uri is invalid', function () { expect(function () { new Uri(fopen('php://memory', 'r')); })->toThrow(new InvalidArgumentException()); }); it('throws InvalidArgumentException when given scheme is not allowed', function () { expect(function () {
expect($toUnset->exists())->toBe(true); expect($toUnset->gallery_id)->toBe(null); expect($gallery->images[0]->gallery_id)->toBe($gallery->id); }); it("assures removed associative entity to be deleted", function () { $toDelete = ImageTag::create(['id' => 5, 'image_id' => 4, 'tag_id' => 6], ['exists' => true]); $toKeep = ImageTag::create(['id' => 6, 'image_id' => 4, 'tag_id' => 3], ['exists' => true]); Stub::on(ImageTag::class)->method('::all', function ($options = [], $fetchOptions = []) use($toDelete, $toKeep) { $images = ImageTag::create([$toDelete, $toKeep], ['type' => 'set']); return $images; }); $hasMany = Image::relation('images_tags'); $image = Image::create(['id' => 4, 'gallery_id' => 2, 'title' => 'Silicon Valley'], ['exists' => true]); $image->images_tags = [['tag_id' => 1], $toKeep]; Stub::on($image->images_tags[0])->method('save', function () use($image) { $image->images_tags[0]->id = 7; return true; }); $schema = ImageTag::schema(); Stub::on($schema)->method('delete', function () { return true; }); expect($image->images_tags[0])->toReceive('save'); expect($toKeep)->toReceive('save'); expect($schema)->toReceive('delete')->with(['id' => 5]); expect($hasMany->save($image))->toBe(true); expect($toDelete->exists())->toBe(false); expect($image->images_tags[0]->image_id)->toBe($image->id); }); }); });
expect($this->database->format('cast', 'serial', '123'))->toBe(123); expect($this->database->format('cast', 'integer', '123'))->toBe(123); expect($this->database->format('cast', 'float', '12.3'))->toBe(12.3); expect($this->database->format('cast', 'decimal', '12.3'))->toBe(12.3); $date = DateTime::createFromFormat('Y-m-d', '2014-11-21'); expect($this->database->format('cast', 'date', $date)->format('Y-m-d'))->toBe('2014-11-21'); expect($this->database->format('cast', 'date', '2014-11-21')->format('Y-m-d'))->toBe('2014-11-21'); $datetime = DateTime::createFromFormat('Y-m-d H:i:s', '2014-11-21 10:20:45'); expect($this->database->format('cast', 'datetime', $datetime)->format('Y-m-d H:i:s'))->toBe('2014-11-21 10:20:45'); expect($this->database->format('cast', 'datetime', '2014-11-21 10:20:45')->format('Y-m-d H:i:s'))->toBe('2014-11-21 10:20:45'); expect($this->database->format('cast', 'datetime', '1416565245')->format('Y-m-d H:i:s'))->toBe('2014-11-21 10:20:45'); expect($this->database->format('cast', 'boolean', 'TRUE'))->toBe(true); expect($this->database->format('cast', 'null', 'NULL'))->toBe(null); expect($this->database->format('cast', 'string', 'abc'))->toBe('abc'); expect($this->database->format('cast', '_default_', 'abc'))->toBe('abc'); expect($this->database->format('cast', '_undefined_', 'abc'))->toBe('abc'); }); }); describe("->errmsg()", function () { it("retuns the last error", function () { Stub::on($this->client)->method('errorInfo', function () { return ['0000', null, null]; }); expect($this->database->errmsg())->toBe(''); Stub::on($this->client)->method('errorInfo', function () { return ['42S02', -204, "Error"]; }); expect($this->database->errmsg())->toBe('42S02 (-204):Error'); }); }); });
use PDOException; use chaos\database\Cursor; use kahlan\plugin\Stub; describe("Cursor", function () { describe("->current()", function () { it("returns `false` when the `PDOStatement` returns `false`", function () { $resource = Stub::create(); Stub::on($resource)->method('fetch', function () { return false; }); $cursor = new Cursor(['resource' => $resource]); expect($cursor->current())->toBe(false); }); it("returns `false` when the `PDOStatement` throws an exception", function () { $resource = Stub::create(); Stub::on($resource)->method('fetch', function () { throw new PDOException(); }); $cursor = new Cursor(['resource' => $resource]); expect($cursor->current())->toBe(false); }); it("sets the resource extracted data on success", function () { $resource = Stub::create(); Stub::on($resource)->method('fetch', function () { return 'data'; }); $cursor = new Cursor(['resource' => $resource]); expect($cursor->current())->toBe('data'); }); }); });
expect(Stub::registered('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Foo'))->toBe(true); }); }); }); describe("::on()", function () { it("throw when stub a method using closure and using andReturn()", function () { expect(function () { $foo = new Foo(); Stub::on($foo)->method('message', function ($param) { return $param; })->andReturn(true); })->toThrow(new Exception("Some closure(s) has already been set.")); }); }); describe("::reset()", function () { beforeEach(function () { Stub::on('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Foo')->method('foo', function () { }); Stub::on('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Bar')->method('bar', function () { }); }); it("clears all stubs", function () { Stub::reset(); expect(Stub::registered())->toBe([]); }); it("clears one stub", function () { Stub::reset('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Foo'); expect(Stub::registered())->toBe(['Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Bar']); }); }); });
$class = $this->class; $subclass = Stub::classname(['extends' => $class]); Stub::on($subclass)->method('::filterable', function () { return Filter::on(get_called_class(), 'filterable', func_get_args(), function ($chain, $message) { return "Hello {$message}"; }); }); Filter::apply($class, 'filterable', 'spec.be_prefix'); Filter::apply($subclass, 'filterable', 'spec.my_prefix'); expect($subclass::filterable('World!'))->toBe('Hello Be My World!'); expect($subclass::filterable('World!'))->toBe('Hello Be My World!'); }); it("invalidates parent cached filters", function () { $class = $this->class; $subclass = Stub::classname(['extends' => $class]); Stub::on($subclass)->method('::filterable', function () { return Filter::on(get_called_class(), 'filterable', func_get_args(), function ($chain, $message) { return "Hello {$message}"; }); }); Filter::apply($class, 'filterable', 'spec.be_prefix'); Filter::apply($subclass, 'filterable', 'spec.my_prefix'); expect($subclass::filterable('World!'))->toBe('Hello Be My World!'); Filter::apply($subclass, 'filterable', 'spec.no_chain'); expect($subclass::filterable('World!'))->toBe("No Man's My World!"); }); it("throws an Exception when trying to apply a filter using an unexisting closure", function () { $class = $this->class; $closure = function () use($class) { Filter::apply($class, 'filterable', 'spec.unexisting_closure'); };
it("bails out if no relation data hasn't been setted", function () { $belongsTo = Image::definition()->relation('gallery'); $image = Image::create(['id' => 1, 'gallery_id' => 1, 'title' => 'Amiga 1200']); expect($belongsTo->broadcast($image))->toBe(true); }); it("saves a belongsTo relationship", function () { $belongsTo = Image::definition()->relation('gallery'); $image = Image::create(['id' => 1, 'title' => 'Amiga 1200'], ['exists' => true]); $image->gallery = ['name' => 'Foo Gallery']; Stub::on($image->gallery)->method('broadcast', function () use($image) { $image->gallery->id = 1; return true; }); expect($image->gallery)->toReceive('broadcast'); expect($belongsTo->broadcast($image))->toBe(true); expect($image->gallery_id)->toBe($image->gallery->id); }); it("throws an exception if the saves relation didn't populate any ID", function () { $closure = function () { $belongsTo = Image::definition()->relation('gallery'); $image = Image::create(['id' => 1, 'gallery_id' => 1, 'title' => 'Amiga 1200'], ['exists' => true]); $image->gallery = ['name' => 'Foo Gallery']; Stub::on($image->gallery)->method('broadcast', function () { return true; }); $belongsTo->broadcast($image); }; expect($closure)->toThrow(new ChaosException("The `'id'` key is missing from related data.")); }); }); });
$result = Text::clean('{:a}, 2 and {:c}'); $this->expect($result)->toBe('2'); }); }); describe("::toString()", function () { it("exports an empty array", function () { $dump = Text::toString([]); $this->expect($dump)->toBe("[]"); }); it("exports an object", function () { $dump = Text::toString(new stdClass()); $this->expect($dump)->toBe("`stdClass`"); }); it("exports an object supporting __toString()", function () { $stub = Stub::create(); Stub::on($stub)->method('__toString')->andReturn('jedi'); $dump = Text::toString($stub); $this->expect($dump)->toBe("jedi"); }); it("exports an object using a closure", function () { $toString = function ($instance) { return 'an instance of `' . get_class($instance) . '`'; }; $dump = Text::toString(new stdClass(), ['object' => ['method' => $toString]]); $this->expect($dump)->toBe("an instance of `stdClass`"); }); it("exports an exception", function () { $dump = Text::toString(new Exception()); $this->expect($dump)->toMatch("/`Exception` Code\\(0\\) with no message in .*?\\/TextSpec.php.*?\$/"); $dump = Text::toString(new Exception('error', 500)); $this->expect($dump)->toMatch("/`Exception` Code\\(500\\) with message \"error\" in .*?\\/TextSpec.php.*?\$/");
use Kastilyo\RabbitHole\Exceptions\ImplementationException; use Kastilyo\RabbitHole\AMQP\QueueBuilder; use Kastilyo\RabbitHole\AMQP\ExchangeBuilder; describe('BatchSubscriber', function () { beforeEach(function () { $this->amqp_connection = Helper::getAMQPConnection(); $this->batch_subscriber = new BatchSubscriber($this->amqp_connection); }); describe('->processMessage', function () { beforeEach(function () { $this->envelopes = array_map(function ($ignore) { $envelope = Helper::getAMQPEnvelope(); Stub::on($envelope)->method('getDeliveryTag')->andReturn('some_delivery_tag'); return $envelope; }, array_fill(0, $this->batch_subscriber->getBatchCount(), null)); Stub::on($this->batch_subscriber)->method('acknowledgeMessage'); // process three ahead of time $this->batch_subscriber->processMessage($this->envelopes[0]); $this->batch_subscriber->processMessage($this->envelopes[1]); $this->batch_subscriber->processMessage($this->envelopes[2]); }); it("doesn't acknowledge messages if the limit hasn't been reached", function () { array_map(function ($envelope) { expect($this->batch_subscriber)->not->toReceive('acknowledgeMessage')->with($envelope); }, $this->envelopes); $this->batch_subscriber->processMessage($this->envelopes[3]); }); it('acknowledges messages if the limit has been reached', function () { array_map(function ($envelope) { expect($this->batch_subscriber)->toReceive('acknowledgeMessage')->with($envelope); }, $this->envelopes);
namespace chaos\spec\suite\model\collection; use InvalidArgumentException; use chaos\Model; use chaos\collection\Collection; use chaos\collection\Through; use kahlan\plugin\Stub; use chaos\spec\fixture\model\Image; use chaos\spec\fixture\model\Tag; use chaos\spec\fixture\model\ImageTag; describe("Through", function () { beforeEach(function () { $this->images_tags = []; $this->imageTagModel = $imageTagModel = Stub::classname(['extends' => ImageTag::class]); $this->tagModel = $tagModel = Stub::classname(['extends' => Tag::class, 'methods' => ['tagMethod']]); Stub::on($tagModel)->method('tagMethod', function ($options) { return $options; }); for ($i = 0; $i < 5; $i++) { $image_tag = new $imageTagModel(); $tag = new $tagModel(); $tag->name = $i; $image_tag->tag = $tag; $this->images_tags[] = $image_tag; } $this->image = new Image(['data' => ['id' => 1, 'name' => 'amiga_1200.jpg', 'title' => 'Amiga 1200', 'images_tags' => $this->images_tags]]); $this->through = new Through(['parent' => $this->image, 'model' => $this->tagModel, 'through' => 'images_tags', 'using' => 'tag']); }); describe("->parent()", function () { it("gets the parent", function () { expect($this->through->parent())->toBe($this->image);
return $query; }); }); it("delegates to `::find`", function () { $model = $this->model; expect($model)->toReceive('::find')->with(['conditions' => ['id' => 1], 'option' => 'value']); expect($this->query)->toReceive('first')->with(['fetch' => 'options']); $model::id(1, ['option' => 'value'], ['fetch' => 'options']); }); }); describe("::all()", function () { beforeEach(function () { $model = $this->model; $schema = $model::schema(); $this->query = $query = Stub::create(); Stub::on($schema)->method('query', function () use($query) { return $query; }); }); it("delegates to `::all`", function () { $model = $this->model; expect($model)->toReceive('::find')->with(['query' => ['field' => 'value']]); expect($this->query)->toReceive('all')->with(['fetch' => 'options']); $model::all(['query' => ['field' => 'value']], ['fetch' => 'options']); }); }); describe("::schema()", function () { it("returns the model", function () { $model = $this->model; $schema = $model::schema(); expect($schema)->toBeAnInstanceOf('chaos\\Schema');
after(function () { Interceptor::load($this->previous); }); describe("->run()", function () { it("should set closure", function () { $foo = new Foo(); $stub = Stub::on($foo)->method('message'); $stub->run(function ($param) { return $param; }); expect($foo->message('Aloha!'))->toBe('Aloha!'); }); it("should throw when return is already set", function () { expect(function () { $foo = new Foo(); $stub = Stub::on($foo)->method('message'); $stub->andReturn('Ahoy!'); $stub->run(function ($param) { return $param; }); })->toThrow(new Exception('Some return values are already set.')); }); it("should throw when trying to pass non callable", function () { expect(function () { $foo = new Foo(); $stub = Stub::on($foo)->method('message'); $stub->run('String'); })->toThrow(new Exception('The passed parameter is not callable.')); }); }); });
describe("Schema", function () { beforeEach(function () { $this->schema = new Schema(['model' => Image::class]); $this->schema->set('id', ['type' => 'serial']); $this->schema->set('gallery_id', ['type' => 'integer']); $this->schema->set('name', ['type' => 'string', 'default' => 'Enter The Name Here']); $this->schema->set('title', ['type' => 'string', 'default' => 'Enter The Title Here', 'length' => 50]); $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']); }); describe("->__construct()", function () { it("correctly sets config options", function () { $connection = Stub::create(); $conventions = Stub::create(); Stub::on($connection)->method('formatters')->andReturn([]); $schema = new Schema(['connection' => $connection, 'source' => 'image', 'model' => Image::class, 'primaryKey' => 'key', 'locked' => false, 'fields' => ['id' => 'serial', 'age' => 'integer'], 'meta' => ['some' => ['meta']], 'conventions' => $conventions]); expect($schema->connection())->toBe($connection); expect($schema->source())->toBe('image'); expect($schema->model())->toBe(Image::class); expect($schema->primaryKey())->toBe('key'); expect($schema->locked())->toBe(false); expect($schema->fields())->toBe(['id' => ['type' => 'serial', 'array' => false, 'null' => false], 'age' => ['type' => 'integer', 'array' => false, 'null' => true]]); expect($schema->meta())->toBe(['some' => ['meta']]); expect($schema->conventions())->toBe($conventions); }); }); describe("->connection()", function () { it("gets/sets the connection", function () { $connection = Stub::create(); $schema = new Schema();
<?php use kahlan\plugin\Stub; use Sofa\Hookable\Hookable; describe('Sofa\\Hookable\\Hookable', function () { it('resolves hooks in instance scope', function () { $parent = Stub::classname(); Stub::on($parent)->method('getAttribute', function () { return 'value'; }); $hookableClass = Stub::classname(['uses' => Hookable::class, 'extends' => $parent]); $hookableClass::hook('getAttribute', function ($next, $value, $args) { $this->instanceMethod(); }); $hookable = new $hookableClass(); expect($hookable)->toReceive('instanceMethod'); $hookable->getAttribute('attribute'); }); it('flushes all hooks with the flushHooks method', function () { $parent = Stub::classname(); $hookableClass = Stub::classname(['uses' => Hookable::class, 'extends' => $parent]); $hookableClass::hook('method1', function ($next, $value, $args) { }); $hookableClass::hook('method2', function ($next, $value, $args) { }); $reflectedClass = new ReflectionClass($hookableClass); $reflectedProperty = $reflectedClass->getProperty('hooks'); $reflectedProperty->setAccessible(true); $hooks = $reflectedProperty->getValue(); expect($hooks)->toHaveLength(2); $hookableClass::flushHooks();
expect($backtrace)->toBeA('string'); $backtrace = explode("\n", $backtrace); expect(empty($backtrace))->toBe(false); }); it("returns a trace from eval'd code", function () { $trace = debug_backtrace(); $trace[1]['file'] = "eval()'d code"; $backtrace = Debugger::trace(['trace' => $trace]); expect($backtrace)->toBeA('string'); $trace = current(explode("\n", $backtrace)); expect($trace)->toMatch('~kahlan[/|\\\\]src[/|\\\\]Specification.php~'); }); describe("::_line()", function () { beforeEach(function () { $this->debugger = Stub::classname(['extends' => 'Kahlan\\Analysis\\Debugger', 'methods' => ['::line']]); Stub::on($this->debugger)->method('::line', function ($trace) { return static::_line($trace); }); }); it("returns `null` with non-existing files", function () { $debugger = $this->debugger; $trace = ['file' => DS . 'some' . DS . 'none' . DS . 'existant' . DS . 'path' . DS . 'file.php', 'line' => null]; expect($debugger::line($trace))->toBe(null); }); it("returns `null` when a line can't be found", function () { $debugger = $this->debugger; $nbline = count(file('spec' . DS . 'Suite' . DS . 'Analysis' . DS . 'DebuggerSpec.php')) + 1; $trace = ['file' => 'spec' . DS . 'Suite' . DS . 'Analysis' . DS . 'DebuggerSpec.php', 'line' => $nbline + 1]; expect($debugger::line($trace))->toBe(null); }); });
$pipes = [function ($next, $payload) { $payload .= ',first'; return $next($payload); }, function ($next, $payload) { $payload .= ',second'; return $next($payload); }, function ($next, $payload) { $payload .= ',third'; return $next($payload); }]; $result = $pipeline->send($payload)->through($pipes)->to($destination); expect($result)->toBe('start,first,second,third,end'); }); it('passes additional arguments along with the parcel', function () { $payload = 'start'; $pipes = [function ($next, $payload, $args) { $payload .= ',pipe-' . $args->get('foo'); return $next($payload, $args); }]; $destination = function ($payload, $args) { return $payload . ',end-' . $args->get('foo'); }; $pipeline = new Pipeline($pipes); $args = Stub::create(['implements' => ['Sofa\\Hookable\\Contracts\\ArgumentBag']]); Stub::on($args)->method('get')->andReturn('bar', 'bar'); expect($args)->toReceive('get'); expect($args)->toReceiveNext('get'); $result = $pipeline->send($payload)->with($args)->to($destination); expect($result)->toBe('start,pipe-bar,end-bar'); }); });
expect(is_string($stub))->toBe(true); expect($stub)->toBe('Kahlan\\Spec\\Stub\\MyStaticStub'); }); it("stubs a stub class with multiple methods", function () { $classname = Stub::classname(); Stub::on($classname)->methods(['message' => ['Good Evening World!', 'Good Bye World!'], 'bar' => ['Hello Bar!']]); $stub = new $classname(); expect($stub->message())->toBe('Good Evening World!'); $stub2 = new $classname(); expect($stub->message())->toBe('Good Bye World!'); $stub3 = new $classname(); expect($stub->bar())->toBe('Hello Bar!'); }); it("stubs static methods on a stub class", function () { $classname = Stub::classname(); Stub::on($classname)->methods(['::magicCallStatic' => ['Good Evening World!', 'Good Bye World!']]); expect($classname::magicCallStatic())->toBe('Good Evening World!'); expect($classname::magicCallStatic())->toBe('Good Bye World!'); }); it("produces unique classname", function () { $stub = Stub::classname(); $stub2 = Stub::classname(); expect($stub)->not->toBe($stub2); }); it("stubs classes with `construct()` if no parent defined", function () { $class = Stub::classname(); expect($class)->toReceive('__construct'); $stub = new $class(); }); }); describe("::generate()", function () {
beforeEach(function () { Helper::initializeAMQPStubs(); $this->connection = Helper::getAMQPConnection(); $this->exchange_builder = new ExchangeBuilder($this->connection); }); context('->get', function () { beforeEach(function () { $this->exchange_name = 'some_exchange'; $this->exchange_builder->setName($this->exchange_name); }); it("makes the connection if it hasn't been made yet", function () { expect($this->connection)->toReceive('connect'); $this->exchange_builder->get(); }); it("doesn't make the connection if it's been made already", function () { Stub::on($this->connection)->method('isConnected')->andReturn(true); expect($this->connection)->not->toReceive('connect'); $this->exchange_builder->get(); }); context('Exchange declaration', function () { it('sets the name of the exchange', function () { expect('AMQPExchange')->toReceive('setName')->with($this->exchange_name); $this->exchange_builder->get(); }); it("sets the exchange to be of type 'topic'", function () { expect('AMQPExchange')->toReceive('setType')->with(AMQP_EX_TYPE_TOPIC); $this->exchange_builder->get(); }); it('sets the exchange as durable', function () { expect('AMQPExchange')->toReceive('setFlags')->with(AMQP_DURABLE); $this->exchange_builder->get();
}); it('uses valid case insensitive operator in postgres', function () { $connection = Stub::create(['extends' => Connection::class, 'methods' => ['__construct']]); $grammar = new Illuminate\Database\Query\Grammars\PostgresGrammar(); $processor = new Illuminate\Database\Query\Processors\PostgresProcessor(); $sql = 'select * from (select "users".*, max(case when "users"."last_name" = ? then 150 else 0 end ' . '+ case when "users"."last_name" ilike ? then 50 else 0 end ' . '+ case when "users"."last_name" ilike ? then 10 else 0 end) ' . 'as relevance from "users" where ("users"."last_name" ilike ?) ' . 'group by "users"."id") as "users" where "relevance" >= 2.5 order by "relevance" desc'; $bindings = ['jarek', 'jarek%', '%jarek%', '%jarek%']; $query = (new Builder($connection, $grammar, $processor))->from('users')->search(' jarek ', ['last_name' => 10]); expect($query->toSql())->toBe($sql); expect($query->toBase()->getBindings())->toBe($bindings); }); it('supports length aware pagination', function () { $sql = 'select count(*) as aggregate from (select `users`.*, max(case when `users`.`last_name` = ? then 150 else 0 end ' . '+ case when `users`.`last_name` like ? then 50 else 0 end ' . '+ case when `users`.`last_name` like ? then 10 else 0 end) ' . 'as relevance from `users` where (`users`.`last_name` like ?) ' . 'group by `users`.`id`) as `users` where `relevance` >= 2.5'; $bindings = ['jarek', 'jarek%', '%jarek%', '%jarek%']; $query = $this->query->search(' jarek ', ['last_name' => 10]); Stub::on($query->getConnection())->method('select', []); expect($query->getConnection())->toReceive('select')->with($sql, $bindings, Arg::toBeA('boolean')); $query->getCountForPagination(); }); it('moves order clauses after the relevance ordering', function () { $sql = 'select * from (select `users`.*, max(case when `users`.`name` = ? then 15 else 0 end) as relevance ' . 'from `users` where (`users`.`name` like ?) group by `users`.`id`) as `users` ' . 'where `relevance` >= 1 order by `relevance` desc, `first_name` asc'; $bindings = ['jarek', 'jarek']; $query = $this->query->orderBy('first_name')->search('jarek', ['name'], false, 1); expect($query->toSql())->toBe($sql); expect($query->toBase()->getBindings())->toBe($bindings); }); it('doesn\'t split quoted string and treats it as a single keyword to search for', function () { $sql = 'select * from (select `users`.*, max(case when `users`.`first_name` = ? then 15 else 0 end ' . '+ case when `users`.`first_name` like ? then 5 else 0 end) as relevance from `users` ' . 'where (`users`.`first_name` like ?) group by `users`.`id`) ' . 'as `users` where `relevance` >= 0.25 order by `relevance` desc'; $bindings = ['jarek tkaczyk', 'jarek tkaczyk%', 'jarek tkaczyk%']; $query = $this->query->search('"jarek tkaczyk*"', ['first_name'], false); expect($query->toSql())->toBe($sql);
<?php use kahlan\plugin\Stub; use Sofa\Hookable\Builder; describe('Sofa\\Hookable\\Builder', function () { beforeEach(function () { $query = Stub::create(['class' => 'Illuminate\\Database\\Query\\Builder']); $this->eloquent = Stub::classname(['class' => 'Illuminate\\Database\\Eloquent\\Builder']); $this->builder = new Builder(new $query()); }); it('fallbacks to base builder for prefixed columns', function () { Stub::on($this->eloquent)->method('where', function () { return 'query'; }); expect($this->builder->where('prefixed.column', 'value'))->toBe('query'); }); it('calls hook defined on the model', function () { $model = Stub::create(); expect($model)->toReceive('queryHook'); Stub::on($this->builder)->method('getModel', function () use($model) { return $model; }); $this->builder->select('column', 'value'); }); });