/** * 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; }
$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 () {
expect($failure->backtrace())->toBeAn('array'); }); it("logs the not attribute", function () { $this->spec = new Specification(['closure' => function () { $this->expect(true)->not->toBe(true); }]); expect($this->spec->process())->toBe(null); expect($this->spec->passed())->toBe(false); $failures = $this->spec->results()['failed']; expect($failures)->toHaveLength(1); $failure = reset($failures); expect($failure->not())->toBe(true); }); it("logs the not attribute with a deferred matcher", function () { $this->spec = new Specification(['closure' => function () { $stub = Stub::create(); $this->expect($stub)->not->toReceive('methodName'); $stub->methodName(); }]); expect($this->spec->process())->toBe(null); expect($this->spec->passed())->toBe(false); $failures = $this->spec->results()['failed']; expect($failures)->toHaveLength(1); $failure = reset($failures); expect($failure->not())->toBe(true); expect($failure->not())->toBe(true); }); it("logs sub spec fails", function () { $this->spec = new Specification(['message' => 'runs a spec', 'closure' => function () { $this->waitsFor(function () { $this->expect(true)->toBe(false);
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()); }; expect($closure)->toThrow(new Exception("Unexisting matcher attached to `'toEqualCustom'` for `stdClass`.")); }); it("doesn't wait when the spec passes", function () { $start = microtime(true); $result = Expectation::expect(true, 1)->toBe(true); $end = microtime(true); expect($end - $start)->toBeLessThan(1); }); it("loops until the timeout is reached on failure", function () { $start = microtime(true); $result = Expectation::expect(true, 0.1)->toBe(false); $end = microtime(true);
<?php declare (strict_types=1); use Kahlan\Plugin\Stub; use ochenta\psr7\RequestTrait; describe('psr7\\RequestTrait', function () { describe('->getRequestTarget', function () { it('returns request target, default empty string', function () { expect(Stub::create(['uses' => RequestTrait::class])->getRequestTarget())->toBe(''); }); it('returns given request target', function () { $req = Stub::create(['uses' => RequestTrait::class]); $req = $req->withRequestTarget('/path'); expect($req->getRequestTarget())->toBe('/path'); }); }); });
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} {} ?>";
public static function getAMQPEnvelope() { return Stub::create(['extends' => 'AMQPEnvelope', 'methods' => ['__construct', 'getDeliveryTag']]); }
$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'); }); });
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("returns all relation names", function () { $relations = $this->schema->relations(); sort($relations); expect($relations)->toBe(['gallery', 'images_tags', 'tags']); }); it("includes embedded relations using `true` as first parameter", function () { $model = Stub::classname(['extends' => Model::class]); $schema = new Schema(['model' => $model]); $schema->set('embedded', ['type' => 'object', 'model' => $model]); expect($schema->relations())->toBe(['embedded']); expect($schema->relations(false))->toBe([]); }); }); describe("->conventions()", function () { it("gets/sets the conventions", function () { $conventions = Stub::create(); $schema = new Schema(); expect($schema->conventions($conventions))->toBe($schema); expect($schema->conventions())->toBe($conventions); }); }); describe("->expand()", function () { it("expands schema paths", function () { expect($this->schema->expand(['gallery', 'tags']))->toBe(['gallery' => null, 'tags' => null, 'images_tags.tag' => null]); }); it("perserves values", function () { $actual = $this->schema->expand(['gallery' => ['conditions' => ['name' => 'My Gallery']], 'tags' => ['conditions' => ['name' => 'landscape']]]); expect($actual)->toBe(['gallery' => ['conditions' => ['name' => 'My Gallery']], 'tags' => ['conditions' => ['name' => 'landscape']], 'images_tags.tag' => ['conditions' => ['name' => 'landscape']]]); }); }); describe("->treeify()", function () {
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(); $hooks = $reflectedProperty->getValue(); expect($hooks)->toHaveLength(0); }); });
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.')); }); }); });
$this->reporters->add('my_reporter', $stub); $actual = $this->reporters->exists('my_reporter'); expect($actual)->toBe(true); $this->reporters->remove('my_reporter'); $actual = $this->reporters->exists('my_reporter'); expect($actual)->toBe(false); }); }); describe("->clear()", function () { it("clears all reporters", function () { $stub = Stub::create(); $this->reporters->add('my_reporter', $stub); $actual = $this->reporters->exists('my_reporter'); expect($actual)->toBe(true); $this->reporters->clear(); $actual = $this->reporters->exists('my_reporter'); expect($actual)->toBe(false); }); }); describe("->process()", function () { it("runs a method on all reporters", function () { $stub1 = Stub::create(); $this->reporters->add('reporter1', $stub1); $stub2 = Stub::create(); $this->reporters->add('reporter2', $stub2); expect($stub1)->toReceive('action')->with(['value']); expect($stub2)->toReceive('action')->with(['value']); $this->reporters->process('action', ['value']); }); }); });
$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.*?\$/");
}); }); error_reporting(E_ALL ^ E_NOTICE); $this->suite->run(); error_reporting(E_ALL); expect($this->suite->passed())->toBe(true); }); }); describe("->reporters()", function () { it("returns the reporters", function () { $describe = $this->suite->describe("", function () { }); $reporters = Stub::create(); $this->suite->run(['reporters' => $reporters]); expect($this->suite->reporters())->toBe($reporters); }); }); describe("->stop()", function () { it("sends the stop event", function () { $describe = $this->suite->describe("", function () { }); $reporters = Stub::create(); expect($reporters)->toReceive('process')->with('stop', Arg::toMatch(function ($actual) { return isset($actual['specs']) && isset($actual['focuses']); })); $this->suite->run(['reporters' => $reporters]); $this->suite->stop(); expect($this->suite->reporters())->toBe($reporters); }); }); });
expect($arg->match(true))->not->toBe(true); expect($arg->match(true))->toBe(false); }); it("registers a matcher for a specific class", function () { Matcher::register('toEqualCustom', Stub::classname(['extends' => 'kahlan\\matcher\\ToEqual']), 'stdClass'); $arg = Arg::toEqualCustom(new stdClass()); expect($arg->match(new stdClass()))->toBe(true); $arg = Arg::toEqualCustom(new DateTime()); expect($arg->match(new stdClass()))->not->toBe(true); }); it("makes registered matchers for a specific class available for sub classes", function () { Matcher::register('toEqualCustom', Stub::classname(['extends' => 'kahlan\\matcher\\ToEqual']), 'SplHeap'); $arg = Arg::toEqualCustom(new SplMaxHeap()); expect($arg->match(new SplMaxHeap()))->toBe(true); }); it("throws an exception using an undefined matcher name", function () { $closure = function () { $arg = Arg::toHelloWorld(true); }; expect($closure)->toThrow(new Exception("Unexisting matchers attached to `'toHelloWorld'`.")); }); it("throws an exception using an matcher name which doesn't match actual", function () { Matcher::register('toEqualCustom', Stub::classname(['extends' => 'kahlan\\matcher\\ToEqual']), 'SplHeap'); $closure = function () { $arg = Arg::toEqualCustom(new SplMaxHeap()); $arg->match(true); }; expect($closure)->toThrow(new Exception("Unexisting matcher attached to `'toEqualCustom'` for `SplHeap`.")); }); }); });
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'); expect($schema)->toBe($model::schema()); }); it("gets/sets a finders", function () { $schema = Stub::create(); $model = $this->model; $model::schema($schema); expect($model::schema())->toBe($schema); }); }); describe("::relations()", function () { it("delegates calls to schema", function () { $model = $this->model; expect($model::schema())->toReceive('relations')->with('hasMany'); $model::relations('hasMany'); }); }); describe("::relation()", function () { it("delegates calls to schema", function () { $model = $this->model;
$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'); };
/** * Helper for `Layer::process()`. * * @param array $nodes A array of nodes to patch. */ protected function _processTree($nodes) { foreach ($nodes as $node) { if ($node->processable && $node->type === 'class' && $node->extends) { $namespace = $node->namespace->name . '\\'; $parent = $node->extends; $extends = ltrim($parent[0] === '\\' ? $parent : $namespace . $parent, '\\'); if (!isset($this->_override[$extends])) { continue; } $layerClass = $node->name . $this->_suffix; $node->extends = $layerClass; $pattern = preg_quote($parent); $node->body = preg_replace("~(extends\\s+){$pattern}~", "\\1{$layerClass}", $node->body); $code = Stub::generate(['class' => $layerClass, 'extends' => $extends, 'openTag' => false, 'closeTag' => false, 'layer' => true]); $parser = $this->_classes['parser']; $nodes = $parser::parse($code, ['php' => true]); $node->close .= str_replace("\n", '', $parser::unparse($this->_pointcut->process($nodes))); } elseif (count($node->tree)) { $this->_processTree($node->tree); } } }
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.")); }); }); });
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); }); });
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); }); }); });
it("formats an exception as a string message", function () { $message = Debugger::message(new Exception('World Destruction Error!')); expect($message)->toBe('`Exception` Code(0): World Destruction Error!'); }); it("formats a backtrace array as a string message", function () { $backtrace = ['message' => 'E_ERROR Error!', 'code' => E_ERROR]; $message = Debugger::message($backtrace); expect($message)->toBe("`E_ERROR` Code(1): E_ERROR Error!"); $backtrace = ['message' => 'Invalid Error!', 'code' => 404]; $message = Debugger::message($backtrace); expect($message)->toBe("`<INVALID>` Code(404): Invalid Error!"); }); }); describe("::loader()", function () { it("gets/sets a loader", function () { $loader = Stub::create(); expect(Debugger::loader($loader))->toBe($loader); }); }); describe("::errorType()", function () { it("returns some reader-friendly error type string", function () { expect(Debugger::errorType(E_ERROR))->toBe('E_ERROR'); expect(Debugger::errorType(E_WARNING))->toBe('E_WARNING'); expect(Debugger::errorType(E_PARSE))->toBe('E_PARSE'); expect(Debugger::errorType(E_NOTICE))->toBe('E_NOTICE'); expect(Debugger::errorType(E_CORE_ERROR))->toBe('E_CORE_ERROR'); expect(Debugger::errorType(E_CORE_WARNING))->toBe('E_CORE_WARNING'); expect(Debugger::errorType(E_CORE_ERROR))->toBe('E_CORE_ERROR'); expect(Debugger::errorType(E_COMPILE_ERROR))->toBe('E_COMPILE_ERROR'); expect(Debugger::errorType(E_CORE_WARNING))->toBe('E_CORE_WARNING'); expect(Debugger::errorType(E_COMPILE_WARNING))->toBe('E_COMPILE_WARNING');
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);
$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("converts nested collections", function () { $collection = new Collection(['data' => [1, 2, 3, new Collection(['data' => [4, 5, 6]])]]); expect(Collection::toArray($collection))->toBe([1, 2, 3, [4, 5, 6]]); }); it("converts mixed nested collections & arrays", function () {
it("throws an exception when using an undefined matcher name", function () { $closure = function () { Matcher::get('toHelloWorld'); }; expect($closure)->toThrow(new Exception("Unexisting default matcher attached to `'toHelloWorld'`.")); }); it("throws an exception when using an undefined matcher name for a specific class", function () { $closure = function () { Matcher::get('toHelloWorld', 'stdClass'); }; expect($closure)->toThrow(new Exception("Unexisting matcher attached to `'toHelloWorld'` for `stdClass`.")); }); }); describe("::unregister()", function () { it("unregisters a matcher", function () { Matcher::register('toBeOrNotToBe', Stub::classname(['extends' => 'kahlan\\matcher\\ToBe'])); expect(Matcher::exists('toBeOrNotToBe'))->toBe(true); Matcher::unregister('toBeOrNotToBe'); expect(Matcher::exists('toBeOrNotToBe'))->toBe(false); }); it("unregisters all matchers", function () { expect(Matcher::get())->toBeGreaterThan(1); Matcher::unregister(true); Matcher::register('toHaveLength', 'kahlan\\matcher\\ToHaveLength'); expect(Matcher::get())->toHaveLength(1); }); }); describe("::reset()", function () { it("unregisters all matchers", function () { expect(Matcher::get())->toBeGreaterThan(1); Matcher::reset();
expect($result)->toBe($expected); }); it("adds ` = NULL` to optional parameter in PHP core method", function () { skipIf(defined('HHVM_VERSION')); $result = Stub::generate(['class' => 'Kahlan\\Spec\\Plugin\\Stub\\Stub', 'extends' => 'LogicException', 'layer' => true]); $expected = <<<EOD <?php namespace Kahlan\\\\Spec\\\\Plugin\\\\Stub; class Stub extends \\\\LogicException { public function __construct\\(\\\$message = NULL, \\\$code = NULL, \\\$previous = NULL\\) EOD; expect($result)->toMatch('~' . $expected . '~i'); }); it("generates code without PHP tags", function () { $result = Stub::generate(['class' => 'Kahlan\\Spec\\Plugin\\Stub\\Stub', 'magicMethods' => false, 'openTag' => false, 'closeTag' => false]); $expected = <<<EOD namespace Kahlan\\Spec\\Plugin\\Stub; class Stub { } EOD; expect($result)->toBe($expected); }); }); });
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('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 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); }); }); });