Esempio n. 1
0
    });
    describe('->getBody', function () {
        it('returns an instance of StreamInterface when empty', function () {
            $message = Stub::create(['uses' => MessageTrait::class]);
            expect($message->getBody())->toBeAnInstanceOf(StreamInterface::class);
            expect($message->getBody()->extract())->toBeNull();
        });
        it('returns stream given in ->withBody', function () {
            $stream = new Stream(NULL);
            $message = Stub::create(['uses' => MessageTrait::class]);
            $message = $message->withBody($stream);
            expect($message->getBody())->toBe($stream);
        });
    });
    describe('->withBody', function () {
        it('returns a copy with the given stream', function () {
            $stream = new Stream(NULL);
            $msg0 = Stub::create(['uses' => MessageTrait::class]);
            $msg1 = $msg0->withBody($stream);
            expect($msg0->getBody())->not->toBe($stream);
            expect($msg1->getBody())->toBe($stream);
        });
        it('returns same instance when body already assigned', function () {
            $stream = new Stream(NULL);
            $msg0 = Stub::create(['uses' => MessageTrait::class]);
            $msg0 = $msg0->withBody($stream);
            $msg1 = $msg0->withBody($stream);
            expect($msg0)->toBe($msg1);
        });
    });
});
Esempio n. 2
0
        $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');
    });
});
Esempio n. 3
0
         $collection = new Collection(['data' => [1, 2, 3]]);
         $collection2 = new Collection(['data' => [4, 5, 6, 7]]);
         $collection->merge($collection2);
         expect($collection->data())->toBe([1, 2, 3, 4, 5, 6, 7]);
     });
     it("merges two collection with key preservation", function () {
         $collection = new Collection(['data' => [1, 2, 3]]);
         $collection2 = new Collection(['data' => [4, 5, 6, 7]]);
         $collection->merge($collection2, true);
         expect($collection->data())->toBe([4, 5, 6, 7]);
     });
 });
 describe("->embed()", function () {
     it("deletages the call up to the schema instance", function () {
         $model = Stub::classname(['extends' => Model::class]);
         $schema = Stub::create();
         $model::config(['schema' => $schema]);
         $galleries = $model::create([], ['type' => 'set']);
         expect($schema)->toReceive('embed')->with($galleries, ['relation1.relation2']);
         $galleries->embed(['relation1.relation2']);
     });
 });
 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 () {
Esempio n. 4
0
     });
     it("stubs an instance with an extra method returning by reference", function () {
         $stub = Stub::create(['methods' => ['&method1']]);
         $stub->method1();
         expect(method_exists($stub, 'method1'))->toBe(true);
         $array = [];
         Stub::on($stub)->method('method1', function () use(&$array) {
             $array[] = 'in';
         });
         $result = $stub->method1();
         $result[] = 'out';
         expect($array)->toBe(['in']);
         //I guess that's the limit of the system.
     });
     it("applies constructor parameters to the stub", function () {
         $stub = Stub::create(['extends' => 'Kahlan\\Spec\\Fixture\\Plugin\\Stub\\ConstrDoz', 'params' => ['a', 'b']]);
         expect($stub->a)->toBe('a');
         expect($stub->b)->toBe('b');
     });
 });
 describe("::classname()", function () {
     it("stubs class", function () {
         $stub = Stub::classname();
         expect($stub)->toMatch("/^Kahlan\\\\Spec\\\\Plugin\\\\Stub\\\\Stub\\d+\$/");
     });
     it("names a stub class", function () {
         $stub = Stub::classname(['class' => 'Kahlan\\Spec\\Stub\\MyStaticStub']);
         expect(is_string($stub))->toBe(true);
         expect($stub)->toBe('Kahlan\\Spec\\Stub\\MyStaticStub');
     });
     it("stubs a stub class with multiple methods", function () {
Esempio n. 5
0
 public static function getAMQPEnvelope()
 {
     return Stub::create(['extends' => 'AMQPEnvelope', 'methods' => ['__construct', 'getDeliveryTag']]);
 }
Esempio n. 6
0
     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');
Esempio n. 7
0
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');
        });
    });
});
Esempio n. 8
0
                });
            });
            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);
        });
    });
});
Esempio n. 9
0
         expect($this->finders->set('myfinder', $closure))->toBe($this->finders);
         expect($this->finders->get('myfinder'))->toBe($closure);
     });
 });
 describe("->exists()", function () {
     it("checks if a finder exists", function () {
         $closure = function () {
         };
         expect($this->finders->exists('myfinder'))->toBe(false);
         $this->finders->set('myfinder', $closure);
         expect($this->finders->exists('myfinder'))->toBe(true);
     });
 });
 describe("->_call()", function () {
     it("calls a finder", function () {
         $closure = Stub::create();
         $this->finders->set('myfinder', $closure);
         expect($closure)->toReceive('__invoke')->with('a', 'b', 'c');
         $this->finders->myfinder('a', 'b', 'c');
     });
     it("throws an exception if no finder exists", function () {
         $closure = function () {
             $this->finders->myfinder('a', 'b', 'c');
         };
         expect($closure)->toThrow(new ChaosException("Unexisting finder `'myfinder'`."));
     });
 });
 describe("->remove()", function () {
     it("removes a finder", function () {
         $closure = function () {
         };
Esempio n. 10
0
<?php

use kahlan\Arg;
use Carbon\Carbon;
use kahlan\plugin\Stub;
use Sofa\LaravelScopes\Periods;
use Illuminate\Database\Query\Builder;
describe('Sofa\\LaravelScopes\\Periods', function () {
    before(function () {
        (new Periods())->apply();
    });
    beforeEach(function () {
        $this->query = Stub::create(['extends' => Builder::class, 'methods' => ['__construct']]);
    });
    context('->getPeriodRange()', function () {
        it('prepares valid period range', function () {
            $range = [Carbon::now()->startOfYear(), Carbon::now()->addYears(2)->endOfYear()];
            expect((new Periods())->getPeriodRange('year', 2, true))->toEqual($range);
            $range = [Carbon::parse('-1 hour')->minute(0)->second(0), Carbon::parse('-1 hour')->minute(59)->second(59)];
            expect((new Periods())->getPeriodRange('hour', -1, false))->toEqual($range);
            $range = [Carbon::parse('+1 minute')->second(0), Carbon::parse('+1 minute')->second(59)];
            expect((new Periods())->getPeriodRange('minute', 1, false))->toEqual($range);
        });
    });
    context('Query macros', function () {
        it('complains about invalid period unit', function () {
            expect(function () {
                $this->query->periods('invalid', 1);
            })->toThrow(new InvalidArgumentException());
        });
        it('->lastPeriods() with current inclusive', function () {
Esempio n. 11
0
<?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');
    });
});
Esempio n. 12
0
         expect($stub1)->toReceive('process')->with(Arg::toMatch($matcher), $path);
         expect($stub2)->toReceive('process')->with(Arg::toMatch($matcher), $path);
         $this->patchers->process($code, $path);
     });
     it("bails out if code to process is an empty string", function () {
         expect($this->patchers->process(''))->toBe('');
     });
 });
 describe("->findFile()", function () {
     beforeEach(function () {
         $this->loader = Stub::create();
         $this->class = Stub::classname();
         $this->file = 'some/path/file.php';
         $this->stub1 = Stub::create();
         $this->patchers->add('patcher1', $this->stub1);
         $this->stub2 = Stub::create();
         $this->patchers->add('patcher2', $this->stub2);
         $file = $this->file;
         Stub::on($this->stub1)->method('findFile', function () use($file) {
             return $file;
         });
         Stub::on($this->stub2)->method('findFile', function () use($file) {
             return $file;
         });
     });
     it("runs findFile() on all patchers", function () {
         expect($this->stub1)->toReceive('findFile')->with($this->loader, $this->class, $this->file);
         expect($this->stub2)->toReceive('findFile')->with($this->loader, $this->class, $this->file);
         $actual = $this->patchers->findFile($this->loader, $this->class, $this->file);
         expect($actual)->toBe('some/path/file.php');
     });
Esempio n. 13
0
 it('requires a timezone id', function () {
     expect(function () {
         new ZoneInfo();
     })->toThrow();
 });
 it('requires a timestamp', function () {
     expect(function () {
         new ZoneInfo('UTC');
     })->toThrow();
 });
 it('is a ' . DateTimeZone::class, function () {
     $zone = new ZoneInfo('UTC', time());
     expect($zone)->toBeAnInstanceOf(DateTimeZone::class);
 });
 it('will set info null on error', function () {
     $dtz = Stub::create(['extends' => ZoneInfo::class, 'params' => ['UTC', time()], 'layer' => true]);
     Stub::on($dtz)->method('getTransitions')->andReturn(false);
     expect($dtz->isDst())->toBeNull();
 });
 context('America', function () {
     context('Los Angeles', function () {
         before(function () {
             $this->id = 'America/Los_Angeles';
             $this->zone = new ZoneInfo($this->id, $this->feb2016);
             $this->dstZone = new ZoneInfo($this->id, $this->apr2016);
         });
         it('->getAbbreviation()', function () {
             expect($this->zone->getAbbreviation())->toBe('PST');
             expect($this->dstZone->getAbbreviation())->toBe('PDT');
         });
         it('->getCountry()', function () {
Esempio n. 14
0
     });
     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!');
         });
         it("applies a filter which break the chain", function () {
             Filter::apply($this->mock, 'filterable', 'spec.no_chain');
             expect($this->mock->filterable('World!'))->toBe("No Man's World!");
         });
Esempio n. 15
0
             return $this->_exception($e);
         });
     });
     it("throws an exception when PDO can't connect to the host", function () {
         $closure = function () {
             $e = Stub::create();
             Stub::on($e)->method('getCode', function () {
                 return 'HY000';
             });
             $this->database->exception($e);
         };
         expect($closure)->toThrow(new DatabaseException("Unable to connect to host `localhost` [HY000]."));
     });
     it("throws an exception when PDO can't connect to the database", function () {
         $closure = function () {
             $e = Stub::create();
             Stub::on($e)->method('getCode', function () {
                 return '28000';
             });
             $this->database->exception($e);
         };
         expect($closure)->toThrow(new DatabaseException("Host connected, but could not access database ``.", 28000));
     });
 });
 describe("->disconnect()", function () {
     it("disconnects the connection", function () {
         expect($this->database->connected())->toBe(true);
         expect($this->database->disconnect())->toBe(true);
         expect($this->database->connected())->toBe(false);
     });
 });
use kahlan\plugin\Stub;
use Sofa\Searchable\Subquery;
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');
Esempio n. 17
0
    });
    it("should create a from a empty QueryBuilder", function () {
        $builder = $this->di->get('modelsManager')->createBuilder()->columns('id, name, email, balance')->from('Spec\\Models\\User')->where('balance < 0');
        $dataTables = new DataTable();
        $response = $dataTables->fromBuilder($builder)->getResponse();
        expect($response)->toBe(['draw' => null, 'recordsTotal' => 0, 'recordsFiltered' => 0, 'data' => []]);
    });
    it("should create a QueryBuilder", function () {
        $builder = $this->di->get('modelsManager')->createBuilder()->columns('id, name, email, balance')->from('Spec\\Models\\User');
        $dataTables = new DataTable();
        $response = $dataTables->fromBuilder($builder)->getResponse();
        expect(count($response['data']))->toBe(20);
        expect(array_keys($response))->toBe(['draw', 'recordsTotal', 'recordsFiltered', 'data']);
        foreach ($response['data'] as $data) {
            expect(array_keys($data))->toBe(['id', 'name', 'email', 'balance', 'DT_RowId']);
            expect($data['DT_RowId'])->toBe($data['id']);
        }
    });
    it("should disable view & send response", function () {
        $this->di->set('view', function () {
            $view = Stub::create();
            return $view;
        });
        \Phalcon\DI::setDefault($this->di);
        $builder = $this->di->get('modelsManager')->createBuilder()->columns('id, name, email, balance')->from('Spec\\Models\\User');
        $dataTables = new DataTable();
        expect(function () use($dataTables, $builder) {
            $dataTables->fromBuilder($builder)->sendResponse();
        })->toEcho("{\"draw\":null,\"recordsTotal\":100,\"recordsFiltered\":100,\"data\":[{\"id\":\"0\",\"name\":\"wolff.jamel\",\"email\":\"rkuhn@dicki.com\",\"balance\":\"500\",\"DT_RowId\":\"0\"},{\"id\":\"1\",\"name\":\"violet36\",\"email\":\"imedhurst@paucek.com\",\"balance\":\"100\",\"DT_RowId\":\"1\"},{\"id\":\"2\",\"name\":\"beahan.abbigail\",\"email\":\"kenna23@mertz.biz\",\"balance\":\"200\",\"DT_RowId\":\"2\"},{\"id\":\"3\",\"name\":\"rickie05\",\"email\":\"echamplin@terry.com\",\"balance\":\"200\",\"DT_RowId\":\"3\"},{\"id\":\"4\",\"name\":\"runolfsdottir.evert\",\"email\":\"vern.goldner@rau.org\",\"balance\":\"200\",\"DT_RowId\":\"4\"},{\"id\":\"5\",\"name\":\"judson99\",\"email\":\"homenick.angeline@greenfelder.com\",\"balance\":\"200\",\"DT_RowId\":\"5\"},{\"id\":\"6\",\"name\":\"walter.eliseo\",\"email\":\"eleanore.gusikowski@yahoo.com\",\"balance\":\"100\",\"DT_RowId\":\"6\"},{\"id\":\"7\",\"name\":\"monserrate.lebsack\",\"email\":\"abraham.hane@gmail.com\",\"balance\":\"500\",\"DT_RowId\":\"7\"},{\"id\":\"8\",\"name\":\"llangworth\",\"email\":\"anderson.delphia@gmail.com\",\"balance\":\"100\",\"DT_RowId\":\"8\"},{\"id\":\"9\",\"name\":\"krajcik.rylee\",\"email\":\"franecki.conor@gmail.com\",\"balance\":\"500\",\"DT_RowId\":\"9\"},{\"id\":\"10\",\"name\":\"vsauer\",\"email\":\"maia14@conroy.com\",\"balance\":\"100\",\"DT_RowId\":\"10\"},{\"id\":\"11\",\"name\":\"green.german\",\"email\":\"hegmann.jane@hotmail.com\",\"balance\":\"200\",\"DT_RowId\":\"11\"},{\"id\":\"12\",\"name\":\"gebert\",\"email\":\"sdicki@gmail.com\",\"balance\":\"200\",\"DT_RowId\":\"12\"},{\"id\":\"13\",\"name\":\"michale68\",\"email\":\"qblock@yahoo.com\",\"balance\":\"200\",\"DT_RowId\":\"13\"},{\"id\":\"14\",\"name\":\"ismitham\",\"email\":\"hirthe.marjory@hotmail.com\",\"balance\":\"200\",\"DT_RowId\":\"14\"},{\"id\":\"15\",\"name\":\"jarrell09\",\"email\":\"cedrick04@gmail.com\",\"balance\":\"100\",\"DT_RowId\":\"15\"},{\"id\":\"16\",\"name\":\"iharvey\",\"email\":\"jude.christiansen@hotmail.com\",\"balance\":\"100\",\"DT_RowId\":\"16\"},{\"id\":\"17\",\"name\":\"bode.maxine\",\"email\":\"tmosciski@yahoo.com\",\"balance\":\"100\",\"DT_RowId\":\"17\"},{\"id\":\"18\",\"name\":\"murray.jeff\",\"email\":\"fjacobs@strosin.com\",\"balance\":\"200\",\"DT_RowId\":\"18\"},{\"id\":\"19\",\"name\":\"gmertz\",\"email\":\"marquardt.nicolas@williamson.com\",\"balance\":\"100\",\"DT_RowId\":\"19\"}]}");
    });
});
Esempio n. 18
0
     });
     it("stubs an instance with an extra method returning by reference", function () {
         $stub = Stub::create(['methods' => ['&method1']]);
         $stub->method1();
         expect(method_exists($stub, 'method1'))->toBe(true);
         $array = [];
         Stub::on($stub)->method('method1', function () use(&$array) {
             $array[] = 'in';
         });
         $result = $stub->method1();
         $result[] = 'out';
         expect($array)->toBe(['in']);
         //I guess that's the limit of the system.
     });
     it("applies constructor parameters to the stub", function () {
         $stub = Stub::create(['extends' => 'kahlan\\spec\\fixture\\plugin\\stub\\ConstrDoz', 'params' => ['a', 'b']]);
         expect($stub->a)->toBe('a');
         expect($stub->b)->toBe('b');
     });
 });
 describe("::classname()", function () {
     it("stubs class", function () {
         $stub = Stub::classname();
         expect($stub)->toMatch("/^kahlan\\\\spec\\\\plugin\\\\stub\\\\Stub\\d+\$/");
     });
     it("names a stub class", function () {
         $stub = Stub::classname(['class' => 'kahlan\\spec\\stub\\MyStaticStub']);
         expect(is_string($stub))->toBe(true);
         expect($stub)->toBe('kahlan\\spec\\stub\\MyStaticStub');
     });
     it("stubs a stub class with multiple methods", function () {
Esempio n. 19
0
     expect($uri->getPath())->toBe('');
     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 () {
Esempio n. 20
0
 context('without providers', function () {
     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);
         });
Esempio n. 21
0
            $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']);
        });
    });
});
Esempio n. 22
0
<?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');
        });
    });
});
Esempio n. 23
0
     });
     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' => ['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!');
         });
         it("applies a filter which break the chain", function () {
             Filter::apply($this->mock, 'filterable', 'spec.no_chain');
             expect($this->mock->filterable('World!'))->toBe("No Man's World!");
         });
Esempio n. 24
0
     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);
Esempio n. 25
0
     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 () {
     expect($query->toSql())->toBe($sql);
     expect($query->toBase()->getBindings())->toBe($bindings);
 });
 it('runs fulltext search by default and allows custom key for grouping', function () {
     $sql = 'select * 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`.`custom_key`) as `users` where `relevance` >= 2.5 order by `relevance` desc';
     $bindings = ['jarek', 'jarek%', '%jarek%', '%jarek%'];
     $query = $this->query->search(' jarek ', ['last_name' => 10], true, null, 'custom_key');
     expect($query->toSql())->toBe($sql);
     expect($query->toBase()->getBindings())->toBe($bindings);
 });
 it('fails silently if no words or columns were provided', function () {
     $sql = 'select * from `users`';
     expect($this->query->search('   ', [])->toSql())->toBe($sql);
 });
 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();
Esempio n. 27
0
use kahlan\Arg;
use AMQPEnvelope;
use Eloquent\Liberator\Liberator;
use Kastilyo\RabbitHole\Subscriber\SubscriberInterface;
use Kastilyo\RabbitHole\Subscriber\SubscriberTrait;
use Kastilyo\RabbitHole\Exceptions\ImplementationException;
use Kastilyo\RabbitHole\AMQP\QueueBuilder;
use Kastilyo\RabbitHole\AMQP\ExchangeBuilder;
describe('Subscriber', function () {
    beforeEach(function () {
        $this->amqp_connection = Helper::getAMQPConnection();
        $this->subscriber = new Subscriber($this->amqp_connection);
        Stub::on(QueueBuilder::class)->method('get')->andReturn($this->amqp_queue_spy = Helper::getAMQPQueue());
        Stub::on(ExchangeBuilder::class)->method('get');
        $this->queue_builder_spy = Stub::create(['extends' => QueueBuilder::class, 'methods' => ['__construct']]);
        $this->exchange_builder_spy = Stub::create(['extends' => ExchangeBuilder::class, 'methods' => ['__construct']]);
        Stub::on($this->amqp_queue_spy)->method('consume');
        $this->subscriber->setQueueBuilder($this->queue_builder_spy);
        $this->subscriber->setExchangeBuilder($this->exchange_builder_spy);
        $this->subscriber->setAMQPConnection($this->amqp_connection);
    });
    describe('getBatchCount', function () {
        it('has a default implementation of 1', function () {
            expect($this->subscriber->getBatchCount())->toBe(1);
        });
    });
    describe('->consume', function () {
        context('Building the exchange', function () {
            it('sets the exchange name and then builds', function () {
                expect($this->exchange_builder_spy)->toReceive('setName')->with($this->subscriber->getExchangeName());
                expect($this->exchange_builder_spy)->toReceiveNext('get');