public function testHelperAllow() { $app = $this->app; $app['acl']::setPermission('sample.view', 'value', 'allow'); $status = allow('sample.view'); $this->assertTrue($status); }
<?php session_start(); function allow() { if (!$_SESSION['uid']) { //display and error message header('Location: login.php'); } } allow(); function getFiles() { require './settings.php'; $con = mysql_connect($host, $user, $password) or die(mysql_error()); $db = mysql_select_db($database, $con) or die(mysql_error()); $user = $_SESSION['uid']; //echo $user; $blah = mysql_query("SELECT * FROM `files` WHERE `user` = 1"); //mysql_fetch_assoc() while ($file = $blah) { // $string = mysql_fetch_assoc($file); // echo $string['user']; echo 'string'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="reset.css" />
if ($user->AsPostfixAdministrator == false) { $tpl = new templates(); echo "alert('" . $tpl->javascript_parse_text("{ERROR_NO_PRIVS}") . "');"; die; exit; } if (isset($_GET["popup"])) { popup(); exit; } if (isset($_GET["allow"])) { allow(); exit; } if (isset($_GET["deny"])) { allow(1); exit; } if (isset($_POST["value-del"])) { item_delete(); exit; } if (isset($_POST["value-add"])) { item_add(); exit; } if (isset($_GET["help"])) { help_page(); exit; } js();
} $db = dbconnect(); if ($_POST && array_key_exists('tid', $_POST) && array_key_exists('fid', $_POST)) { $newThread = false; $tid = $_POST['tid']; $uid = $_SESSION['user']->uid; $title = strip_tags($_POST['title']); require_once "bbcode.php"; $content = parse_bbcode_html(strip_tags($_POST['content'], '<br>')); $approved = !isModerated($_POST['fid']) || allow('mod_approve') ? 1 : 0; $date = time(); if (array_key_exists('pid', $_POST)) { $pid = $_POST['pid']; $res = dbquery("SELECT uid FROM posts WHERE pid=:pid", array('pid' => $pid)); $uid = $res->fetchColumn(); if (!(allow("mod_edit") || allow("forum_posting") && $_SESSION['user']->uid == $uid)) { echo '<script>window.location="/";</script>'; die; } $pid = $_POST['pid']; $res = dbquery("UPDATE posts SET title=:title, content=:content, approved=:approved\n WHERE pid=:pid;", array('title' => $title, 'content' => $content, 'pid' => $pid, 'approved' => $approved)); if ($res) { $tid = getThread($pid); echo "<script>window.location='/?page=thread&tid={$tid}#p{$pid}';</script>"; } else { echo "Something went wrong"; } } else { $res = dbquery("INSERT INTO posts (uid, title, content, date, tid, approved)\n VALUES (:uid, :title, :content, FROM_UNIXTIME(:date), :tid, :approved)", array("uid" => $uid, "title" => $title, "content" => $content, "date" => $date, "tid" => $tid, "approved" => $approved)); $pid = $db->lastInsertId(); if ($res && $tid == "") {
Connection: Close User-Agent: Mozilla/5.0 Transfer-Encoding: chunked Content-Type: application/x-www-form-urlencoded 19 name1=value1&name2=value2 0 EOD; expect($request->toMessage())->toBe($expected); }); it("throws an exception when Content-Length is required but not be determined", function () { $closure = function () { $stream = Double::instance(['extends' => 'Lead\\Storage\\Stream\\Stream']); allow($stream)->toReceive('length')->andReturn(null); $request = new Request(['method' => 'POST', 'type' => 'application/x-www-form-urlencoded', 'body' => $stream]); $request->toMessage(); }; expect($closure)->toThrow(new NetException('A Content-Length header is required but the request stream has a `null` length.')); }); }); describe("->export()", function () { it("exports default values", function () { $request = new Request(); expect($request->export())->toEqual(['method' => 'GET', 'scheme' => 'http', 'version' => '1.1', 'host' => 'localhost', 'port' => 80, 'path' => '/', 'query' => '', 'fragment' => '', 'username' => null, 'password' => null, 'url' => 'http://localhost/', 'stream' => $request->stream()]); }); it("exports a request", function () { $request = new Request(['scheme' => 'http', 'host' => 'www.domain.com', 'port' => 80, 'username' => 'username', 'password' => 'password', 'path' => 'index.php']); expect($request->export())->toEqual(['method' => 'GET', 'scheme' => 'http', 'version' => '1.1', 'host' => 'www.domain.com', 'port' => 80, 'path' => '/index.php', 'query' => '', 'fragment' => '', 'username' => 'username', 'password' => 'password', 'url' => 'http://www.domain.com/index.php', 'stream' => $request->stream()]); });
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('~src[/|\\\\]Specification.php~'); }); describe("::_line()", function () { beforeEach(function () { $this->debugger = Double::classname(['extends' => 'Kahlan\\Analysis\\Debugger', 'methods' => ['::line']]); allow($this->debugger)->toReceive('::line')->andRun(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 . 'Debugger.spec.php')) + 1; $trace = ['file' => 'spec' . DS . 'Suite' . DS . 'Analysis' . DS . 'Debugger.spec.php', 'line' => $nbline + 1]; expect($debugger::line($trace))->toBe(null); }); });
<?php namespace Kahlan\Spec\Suite\Filter\Behavior; use Kahlan\Plugin\Double; use Kahlan\Filter\MethodFilters; describe('Filterable', function () { beforeEach(function () { $this->mock = Double::instance(['uses' => ['Kahlan\\Filter\\Behavior\\Filterable']]); allow($this->mock)->toReceive('filterable')->andRun(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('Kahlan\\Filter\\MethodFilters'); }); it("sets a new `MethodFilters` instance", function () { $methodFilters = new MethodFilters(); expect($this->mock->methodFilters($methodFilters))->toBeAnInstanceOf('Kahlan\\Filter\\MethodFilters'); expect($this->mock->methodFilters())->toBe($methodFilters); }); }); });
it("merges two collection", function () { $collection = new Collection(['data' => [['name' => "5"], ['name' => "6"]]]); $this->through->merge($collection); expect($this->through->data())->toBe([['name' => "0"], ['name' => "1"], ['name' => "2"], ['name' => "3"], ['name' => "4"], ['name' => "5"], ['name' => "6"]]); }); it("merges two collection with key preservation", function () { $collection = new Collection(['data' => [['name' => "5"], ['name' => "6"]]]); $this->through->merge($collection, true); expect($this->through->data())->toBe([['name' => "5"], ['name' => "6"], ['name' => "2"], ['name' => "3"], ['name' => "4"]]); }); }); describe("->embed()", function () { it("delegates the call up to the schema instance", function () { $model = $this->tagModel; $schema = $model::definition(); allow($schema)->toReceive('embed'); expect($schema)->toReceive('embed')->with($this->through, ['relation1.relation2']); $this->through->embed(['relation1.relation2']); }); }); describe("->data()", function () { it("calls `to()`", function () { expect($this->through)->toReceive('to')->with('array', []); $this->through->data([]); }); }); describe("->validates()", function () { it("returns `true` when no validation error occur", function () { $image = Image::create(); $image->tags[] = Tag::create(); $image->tags[] = Tag::create();
$this->loader = Double::instance(); $this->class = Double::classname(); $this->file = 'some/path/file.php'; $this->stub1 = Double::instance(); $this->patchers->add('patcher1', $this->stub1); $this->stub2 = Double::instance(); $this->patchers->add('patcher2', $this->stub2); $file = $this->file; allow($this->stub1)->toReceive('findFile')->andRun(function () use($file) { return $file; }); allow($this->stub2)->toReceive('findFile')->andRun(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'); }); it("returns patchers overriding if available", function () { $path = 'new/path/file.php'; allow($this->stub2)->toReceive('findFile')->andRun(function () use($path) { return $path; }); $actual = $this->patchers->findFile($this->loader, $this->class, $this->file); expect($actual)->toBe($path); }); }); });
expect(http_response_code())->toEqual(404); }); it('should redirect to 500 status page for exception', function () { allow(Routeur::class)->toReceive('::stopExecution')->andRun(function () { }); Routeur::set('bad', 'bad', function () { throw new \Exception(); }); $closure = function () { Routeur::dispatch('bad'); }; expect($closure)->toEcho('Erreur serveur ...'); expect(http_response_code())->toEqual(500); }); it('should redirect to specific page with 500 status for exception', function () { allow(Routeur::class)->toReceive('::stopExecution')->andRun(function () { }); Routeur::set('bad', 'bad', function () { throw new \Exception(); }); Routeur::set('500', '500', function () { echo "erreur serveur"; }); $closure = function () { Routeur::dispatch('bad'); }; expect($closure)->toEcho('erreur serveur'); expect(http_response_code())->toEqual(500); }); }); describe('url', function () {
require 'dbconfig.php'; if (isset($_GET['page'])) { $page = $_GET['page']; } else { $page = 'creation'; } if (!is_file('admin/' . $page . '.php') || !is_readable('admin/' . $page . '.php')) { $page = '../404'; } elseif ($page == 'management') { echo " <link rel='stylesheet' type='text/css' href='../styles/main.css'>"; } elseif ($page == 'moderation') { echo " <link rel='stylesheet' type='text/css' href='../styles/thread.css'>"; } ?> </head> <body> <?php require "header.php"; if (allow('acp_view')) { echo '<div id="main">'; require 'admin/header.php'; require 'admin/' . $page . '.php'; echo '<br /></div>'; } else { echo "You are not allowed to view this page"; } require "footer.php"; ?> </body> </html>
$desc = $row['description']; $posts = $row['posts']; $threads = $row['threads']; echo "\n <a href='?page=forum&fid={$sfid}'>\n <div class='forum'>\n <div class='forum-data'>\n <h3>{$title}</h3>\n <p>{$desc}</p>\n </div>\n <div class='forum-activity'>\n <p>Posts: {$posts}</p>\n <p>Topics: {$threads}</p>\n </div>\n </div>\n </a>\n "; } echo "</div>"; } echo "<div class='threads'><h2>Threads</h2>"; if (allow('forum_posting') && $locked == 0) { echo "<a href='/?page=discussion&fid={$fid}'><div class='thread newthread'><div class='thread-data'><h3>+ New Thread</h3></div></div></a>"; } $res = dbquery("SELECT COUNT(*) FROM threads \n WHERE fid=:fid \n ORDER BY lastpost_date;", array('fid' => $fid)); if ($res->fetchColumn() == 0) { echo "<div class='error'><h3>No threads in this forum yet!</h3></div>"; } if (allow('mod_approve')) { $res = dbquery("SELECT * FROM threads \n WHERE fid=:fid \n ORDER BY lastpost_date DESC;", array('fid' => $fid)); } else { $res = dbquery("SELECT * FROM threads \n WHERE fid=:fid AND approved=1\n ORDER BY lastpost_date DESC;", array('fid' => $fid)); } while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $title = $row['title']; $tid = $row['tid']; $uid = $row['uid']; $date = date("D, d M Y H:i", strtotime($row['date'])); $posts = $row['posts']; $lastpost_uid = $row['lastpost_uid']; $lastpost_date = date("D, d M Y H:i", strtotime($row['lastpost_date'])); $user = getUsername($uid); $lastpost_user = getUsername($lastpost_uid); echo "\n <a href='?page=thread&tid={$tid}'>\n <div class='thread'>\n <div class='thread-data'>\n <h3>{$title}</h3>\n <span>By: <a href='?page=profile&uid={$uid}'>{$user}</a> on {$date}</span>\n </div>\n <div class='thread-activity'>\n <p>Posts: {$posts}</p>\n <span>Last post by: <a href='?page=profile&uid={$lastpost_uid}'>{$lastpost_user}</a></span>\n <p>{$lastpost_date}</p>\n </div>\n </div>\n </a>\n ";
expect($this->database->convert('cast', '_default_', 123))->toBe(123); expect($this->database->convert('cast', '_undefined_', 123))->toBe(123); }); it("formats `null` values", function () { expect($this->database->convert('datasource', 'id', null))->toBe('NULL'); expect($this->database->convert('datasource', 'serial', null))->toBe('NULL'); expect($this->database->convert('datasource', 'integer', null))->toBe('NULL'); expect($this->database->convert('datasource', 'float', null))->toBe('NULL'); expect($this->database->convert('datasource', 'decimal', null))->toBe('NULL'); expect($this->database->convert('datasource', 'date', null))->toBe('NULL'); expect($this->database->convert('datasource', 'datetime', null))->toBe('NULL'); expect($this->database->convert('datasource', 'boolean', null))->toBe('NULL'); expect($this->database->convert('datasource', 'null', null))->toBe('NULL'); expect($this->database->convert('datasource', 'string', null))->toBe('NULL'); expect($this->database->convert('datasource', '_default_', null))->toBe('NULL'); expect($this->database->convert('datasource', '_undefined_', null))->toBe('NULL'); }); }); describe("->errorMsg()", function () { it("retuns the last error", function () { allow($this->client)->toReceive('errorInfo')->andRun(function () { return ['0000', null, null]; }); expect($this->database->errorMsg())->toBe(''); allow($this->client)->toReceive('errorInfo')->andRun(function () { return ['42S02', -204, "Error"]; }); expect($this->database->errorMsg())->toBe('42S02 (-204):Error'); }); }); });
expect($mon->time())->toBe(456); }); it("expects stubbed method to be stubbed only when the with constraint is respected", function () { $mon = new Mon(); allow('Kahlan\\Spec\\Fixture\\Plugin\\Monkey\\rand')->toBeCalled()->with(10, 20)->andReturn(40); expect($mon->rand(0, 10))->toBe(5); expect($mon->rand(10, 20))->toBe(40); }); it('makes built-in PHP function to work', function () { allow('file_get_contents')->toBeOK(); $mon = new Mon(); expect($mon->loadFile())->toBe(null); }); it("throws an exception when trying to call `toReceive()`", function () { expect(function () { allow('time')->toReceive('something')->andReturn(123, 456); })->toThrow(new Exception("Error `toReceive()` are only available on classes/instances not functions.")); }); }); it("throws an exception when trying to call `andReturn()` right away", function () { expect(function () { allow('time')->andReturn(123); })->toThrow(new Exception("You must to call `toReceive()/toBeCalled()` before defining a return value.")); }); it("throws an exception when trying to call `andReturn()` right away", function () { expect(function () { allow('time')->andRun(function () { }); })->toThrow(new Exception("You must to call `toReceive()/toBeCalled()` before defining a return value.")); }); });
skipIf(!$box->has('source.database.sqlite')); }); beforeEach(function () { $box = box('chaos.spec'); $this->adapter = $box->get('source.database.sqlite'); }); describe("::enabled()", function () { it("returns `true` for enabled features, false otherwise.", function () { expect(Sqlite::enabled())->toEqual(['arrays' => false, 'transactions' => false, 'booleans' => true, 'default' => false]); expect(Sqlite::enabled('arrays'))->toBe(false); expect(Sqlite::enabled('transactions'))->toBe(false); expect(Sqlite::enabled('booleans'))->toBe(true); expect(Sqlite::enabled('default'))->toBe(false); }); it("throws an exception if the extension is not loaded.", function () { allow('extension_loaded')->toBeCalled()->andReturn(false); expect(function () { Sqlite::enabled(); })->toThrow(new DatabaseException("The PDO SQLite extension is not installed.")); }); }); describe("->connect()", function () { it("throws an exception if no database name is set", function () { $closure = function () { new Sqlite(['database' => null]); }; expect($closure)->toThrow(new DatabaseException('Error, no database name has been configured.')); }); }); describe("->sources()", function () { it("shows sources", function () {
$select = $query::newQuery(); $select::from(); }); }); context("with chain of methods and arguments requirements", function () { it("expects stubbed chain called with matching arguments are called", function () { $foo = new Foo(); allow('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Foo')->toReceive('::getQuery', '::newQuery', '::from'); expect('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Foo')->toReceive('::getQuery', '::newQuery', '::from')->where(['::getQuery' => [1], '::newQuery' => [2], '::from' => [3]]); $query = Foo::getQuery(1); $select = $query::newQuery(2); $select::from(3); }); it("expects stubbed chain not called with matching arguments are uncalled", function () { $foo = new Foo(); allow('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Foo')->toReceive('::getQuery', '::newQuery', '::from'); expect('Kahlan\\Spec\\Fixture\\Plugin\\Pointcut\\Foo')->not->toReceive('::getQuery', '::newQuery', '::from')->where(['::getQuery' => [1], '::newQuery' => [2], '::from' => [3]]); $query = Foo::getQuery(1); $select = $query::newQuery(2); $select::from(0); }); }); }); context("with ordered enabled", function () { describe("::match()", function () { it("expects called methods to be called in a defined order", function () { $foo = new Foo(); expect($foo)->toReceive('message')->ordered; expect($foo)->toReceive('::version')->ordered; expect($foo)->toReceive('bar')->ordered; $foo->message();
}); describe("->data()", function () { it("calls `to()`", function () { $collection = new Collection(['data' => [1 => 1]]); expect($collection)->toReceive('to')->with('array', []); $collection->data([]); }); }); describe("::toArray()", function () { it("converts a collection to an array", function () { $collection = new Collection(['data' => [1, 2, 3, 4, 5]]); expect(Collection::toArray($collection))->toBe([1, 2, 3, 4, 5]); }); it("converts objects which support __toString", function () { $stringable = Double::classname(); allow($stringable)->toReceive('__toString')->andReturn('hello'); $collection = new Collection(['data' => [new $stringable()]]); expect(Collection::toArray($collection))->toBe(['hello']); }); it("converts objects using handlers", function () { $handlable = Double::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']); });
use InvalidArgumentException; use Lead\Text\Text; use Kahlan\Plugin\Double; describe("Text", function () { describe("::insert()", function () { it("inserts scalar variables in a string", function () { $string = 'Obi-Wan is {:adjective}.'; $expected = 'Obi-Wan is awesome.'; $result = Text::insert($string, ['adjective' => 'awesome']); expect($result)->toBe($expected); }); it("inserts object variables supporting `__toString()` in a string", function () { $string = 'Obi-Wan is a {:noun}.'; $expected = 'Obi-Wan is a jedi.'; $double = Double::instance(); allow($double)->toReceive('__toString')->andReturn('jedi'); $result = Text::insert($string, ['noun' => $double]); expect($result)->toBe($expected); }); it("inserts a blank for object variables which doesn't support `__toString()`", function () { $string = 'Obi-Wan is a {:noun}.'; $expected = 'Obi-Wan is a .'; $result = Text::insert($string, ['noun' => new stdClass()]); expect($result)->toBe($expected); }); it("inserts a variable as many time as it exists a placeholder", function () { $string = '{:a} {:b} {:a} {:a}'; $expected = '1 2 1 1'; $result = Text::insert($string, ['a' => 1, 'b' => 2]); expect($result)->toBe($expected); });
$subclass = Double::classname(['extends' => $class]); allow($subclass)->toReceive('::filterable')->andRun(function () { return Filters::run(get_called_class(), 'filterable', func_get_args(), function ($next, $message) { return "Hello {$message}"; }); }); Filters::apply($class, 'filterable', $this->filter1); Filters::apply($subclass, 'filterable', $this->filter2); expect($subclass::filterable('World!'))->toBe('21Hello World!12'); Filters::apply($subclass, 'filterable', $this->noChain); expect($subclass::filterable('World!'))->toBe("Hello"); }); it("applies filters in order", function () { $class = $this->class; $subclass = Double::classname(['extends' => $class]); allow($subclass)->toReceive('::filterable')->andRun(function () { return Filters::run(get_called_class(), 'filterable', func_get_args(), function ($next, $message) { return "Hello {$message}"; }); }); Filters::apply($subclass, 'filterable', $this->filter1); Filters::apply($subclass, 'filterable', $this->filter2); expect($subclass::filterable('World!'))->toBe('21Hello World!12'); }); }); describe("::get()", function () { it("exports filters setted as a class level", function () { Filters::apply($this->class, 'filterable', $this->filter1); $filters = Filters::get(); expect($filters)->toHaveLength(1); expect(isset($filters[$this->class . '::filterable']))->toBe(true);
$stub = allow($foo)->toReceive('message'); $stub->andRun(function () { return 'Aloha!'; }, function () { return 'Hello!'; }); expect($foo->message())->toBe('Aloha!'); expect($stub->actualReturn())->toBe('Aloha!'); expect($foo->message())->toBe('Hello!'); expect($foo->message())->toBe('Hello!'); expect($stub->actualReturn())->toBe('Hello!'); }); it("throws when return is already set", function () { expect(function () { $foo = new Foo(); $stub = allow($foo)->toReceive('message'); $stub->andReturn('Ahoy!'); $stub->andRun(function ($param) { return $param; }); })->toThrow(new Exception('Some return value(s) has already been set.')); }); it("throws when trying to pass non callable", function () { expect(function () { $foo = new Foo(); $stub = allow($foo)->toReceive('message'); $stub->andRun('String'); })->toThrow(new Exception('The passed parameter is not callable.')); }); }); });
<?php namespace App\Spec; use App\UsageFunctions; describe('UsageFunctions', function () { describe('getCurrentTime()', function () { it('returns expected current time', function () { $expected = 1477897159; allow('time')->toBeCalled()->andReturn($expected); $actual = (new UsageFunctions())->getCurrentTime(); expect($actual)->toBe($expected); }); }); });
* This function will handle all of our file uploading */ session_start(); //connect to the database so we can check, edit, or insert data to our users table require 'settings.php'; $con = mysql_connect($host, $user, $password) or die(mysql_error()); $db = mysql_select_db($database, $con) or die(mysql_error()); $user = $_SESSION['uid']; function allow($user) { if (!$user) { //display and error message header('Location: index.php'); } } allow($user); $user = $_SESSION['uid']; $user_code = mysql_query("SELECT * FROM `users` WHERE `id` = '" . $user . "'"); $user_assoc = mysql_fetch_assoc($user_code); $username = $user_assoc['username']; function uploadFile($username) { require 'settings.php'; $user = $_SESSION['uid']; $characters = 'acefhijklrstuvwxyz123456789'; $ran = ''; for ($i = 0; $i < 5; $i++) { $ran .= $characters[rand(0, strlen($characters) - 1)]; } if (isset($_POST['upload_button'])) { $file = $_FILES['file_upload'];
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::load(1, ['option' => 'value'], ['fetch' => 'options']); }); }); describe("::all()", function () { beforeEach(function () { $model = $this->model; $schema = $model::definition(); $this->query = $query = Double::instance(); allow($schema)->toReceive('query')->andRun(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("::definition()", function () { it("returns the model", function () { $model = $this->model; $schema = $model::definition(); expect($schema)->toBeAnInstanceOf('chaos\\Schema');
$schema->column('id', ['type' => 'serial']); $schema->locked(false); }); describe("->__construct()", function () { it("loads the data", function () { $date = new DateTime('2014-10-26 00:25:15'); $model = $this->model; $entity = $model::create(['title' => 'Hello', 'body' => 'World', 'created' => $date]); expect($entity->title)->toBe('Hello'); expect($entity->body)->toBe('World'); expect($entity->created)->toBe($date); expect($entity)->toHaveLength(3); }); it("throws an exception if exists is `null` but no record actually exists", function () { $model = $this->model; allow($model)->toReceive('::load')->andRun(function () { return; }); $closure = function () { $model = $this->model; $entity = $model::create(['id' => 1, 'title' => 'Good Bye', 'body' => 'Folks'], ['exists' => null]); }; expect($closure)->toThrow(new ChaosException("The entity id:`1` doesn't exists.")); }); }); describe("->model()", function () { it("returns the model class name", function () { $model = $this->model; $entity = $model::create(); expect($entity->model())->toBe($model); });
$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 = Double::instance(); allow($stub)->toReceive('__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 .*?" . DS . "Text.spec.php.*?\$~"); $dump = Text::toString(new Exception('error', 500)); $this->expect($dump)->toMatch("~`Exception` Code\\(500\\) with message \"error\" in .*?" . DS . "Text.spec.php.*?\$~");
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 () { allow($this->patcher1)->toReceive('findFile')->andRun(function ($interceptor, $class, $file) { return $file . '1'; }); allow($this->patcher2)->toReceive('findFile')->andRun(function ($interceptor, $class, $file) { return $file . '2'; }); $expected = realpath('spec/Fixture/Interceptor/ClassA.php'); $actual = $this->interceptor->findFile('Lead\\Jit\\Spec\\Fixture\\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} {} ?>";
given('dependency', function () { return Double::instance(['extends' => Dependency::class, 'methods' => ['__construct'], 'implements' => [DependencyInterface::class, AnotherInterface::class], 'uses' => [ProcessTrait::class]]); }); given('foo', function () { return new Foo($this->dependency); }); describe('instance of check', function () { it('return "Foo" instance', function () { expect($this->foo)->toBeAnInstanceOf(Foo::class); }); }); describe('->process', function () { it('return "$param processed" string', function () { $param = 'foo'; $expected = $param . ' processed'; allow($this->dependency)->toReceive('process')->with($param)->andReturn($expected); $result = $this->foo->process($param); expect($result)->toBe($expected); }); }); describe('->fooString', function () { it('return "foo" string', function () { $expected = 'foo'; $result = $this->foo->fooString(); expect($result)->toBe($expected); }); it('Quit from the execution', function () { Quit::disable(); $closure = function () { $this->foo->fooString(false); };
<?php namespace App\Spec; use App\Dependency; use App\Bar; describe('Bar', function () { given('bar', function () { return new Bar(); }); describe('instance', function () { it('return "Bar" instance', function () { expect($this->bar)->toBeAnInstanceOf(Bar::class); }); }); describe('->process', function () { it('return "$param processed" string', function () { $param = 'foo'; $expected = $param . ' processed'; allow(Dependency::class)->toReceive('process')->with($param)->andReturn($expected); $result = $this->bar->process($param); expect($result)->toBe($expected); }); }); });
$cursor->rewind(); expect($cursor->next())->toBe(1); }); }); describe("->current()", function () { it("returns `false` when the `PDOStatement` returns `false`", function () { $resource = Double::instance(); allow($resource)->toReceive('fetch')->andRun(function () { return false; }); $cursor = new Cursor(['resource' => $resource]); expect($cursor->current())->toBe(false); }); it("returns `false` when the `PDOStatement` throws an exception", function () { $resource = Double::instance(); allow($resource)->toReceive('fetch')->andRun(function () { throw new PDOException(); }); $cursor = new Cursor(['resource' => $resource]); expect($cursor->current())->toBe(false); }); it("sets the resource extracted data on success", function () { $resource = Double::instance(); allow($resource)->toReceive('fetch')->andRun(function () { return 'data'; }); $cursor = new Cursor(['resource' => $resource]); expect($cursor->current())->toBe('data'); }); }); });
public function foo(\$a) {return parent::foo(\$a);} public function foo2(\$b = NULL) {return parent::foo2(\$b);} public function foo3(array \$b = array()) {return parent::foo3(\$b);} public function foo4(callable \$fct) {return parent::foo4(\$fct);} public function foo5(\\Closure \$fct) {return parent::foo5(\$fct);} public function foo6(\\Exception \$e) {return parent::foo6(\$e);} public function foo7(\\Kahlan\\Spec\\Fixture\\Plugin\\Double\\DozInterface \$instance) {return parent::foo7(\$instance);} } ?> EOD; expect($result)->toBe($expected); }); it("overrides by default all parent class method of internal classes if the layer option is not defined", function () { $double = Double::instance(['extends' => 'DateTime']); allow($double)->toReceive('getTimestamp')->andReturn(12345678); expect($double->getTimestamp())->toBe(12345678); }); it("adds ` = NULL` to optional parameter in PHP core method", function () { skipIf(defined('HHVM_VERSION')); $result = Double::generate(['class' => 'Kahlan\\Spec\\Plugin\\Double\\Double', 'extends' => 'LogicException', 'layer' => true]); $expected = <<<EOD <?php namespace Kahlan\\\\Spec\\\\Plugin\\\\Double; class Double extends \\\\LogicException { public function __construct\\(\\\$message = NULL, \\\$code = NULL, \\\$previous = NULL\\) EOD; expect($result)->toMatch('~' . $expected . '~i'); });