public function test_ensure() { ensure(true); assert_fails(function () { ensure(false); }); }
public function test_get_arguments_returns_array_of_arguments() { $args = $this->list->get_arguments(); assert_equal(2, count($args)); foreach ($args as $a) { ensure($a instanceof phpx\Argument); } }
public function test_any() { ensure(any(array(1, 2, 3), function ($v) { return $v > 2; })); ensure(!any(array(1, 2, 3), function ($v) { return $v > 4; })); }
public function test_effective_access() { $s = new phpx\AccessStack(); $s->push(new phpx\Access('public static')); $s->push(new phpx\Access('protected instance')); $s->push(new phpx\Access('private')); $s->pop(); $s->push(new phpx\Access('final')); $a = $s->effective_access(); ensure($a->is_protected()); ensure(!$a->is_static()); ensure($a->is_final()); ensure(!$a->is_abstract()); }
/** * Capture output * * @param lang.Runnable r * @param array<string, string> initial * @return array<string, string> */ public static function capture(Runnable $r, $initial = array()) { self::$streams = $initial; stream_wrapper_unregister('php'); stream_wrapper_register('php', __CLASS__); try { $r->run(); } catch (Exception $e) { } ensure($e); stream_wrapper_restore('php'); if ($e) { throw $e; } return self::$streams; }
/** * @param $method * @param $path * @param $cms * @return mixed */ function __invoke($method, $path, $cms) { $this->cms = $cms = $this; // inclide prepend PHP file first is_file($php = \dir\content($path . '/index.php')) ? include_once $php : null || is_file($php = \dir\content($path . '.php')) ? include_once $php : null; // search page (html, md, latte, phtml) $this->page = Page::fromPath(\dir\content() . '/' . $path, (array) config()->meta); // include functions.php from $path and working directory is_file($php = \dir\content($path . '/function.php')) ? include_once $php : null; is_file(getcwd() . '/functions.php') ? include_once getcwd() . '/functions.php' : null; if ($this->page) { echo ensure('render.page', [$this, 'render'], $this); // render page } else { error(404, $method, $path, $this); // trigger router error } }
public function test_annotation_parsing() { $string = <<<ANNOTATION /** * Implicit true: * :super_user * * :count = 100 * :extensions = [1,2,3] * :extensions[] = 4 * :access = { "jason": "allow", "captain hook": "deny" } */ ANNOTATION; $parser = new phpx\AnnotationParser(); $annotes = $parser->parse($string); ensure($annotes['super_user']); assert_equal(100, $annotes['count']); assert_equal(array(1, 2, 3, 4), $annotes['extensions']); assert_equal(array('jason' => 'allow', 'captain hook' => 'deny'), $annotes['access']); }
public function boxResource() { $fd = Streams::readableFd(new MemoryInputStream('test')); try { Primitive::boxed($fd); } catch (IllegalArgumentException $expected) { // OK } ensure($expected); fclose($fd); // Necessary, PHP will segfault otherwise if ($expected) { return; } $this->fail('Expected exception not caught', NULL, 'lang.IllegalArgumentException'); }
function assert_not_matches($pattern, $subject) { ensure(!preg_match($pattern, $subject)); }
public function test_generation_from_reflection() { $r = new ReflectionMethod('AccessTestThing', 'foo'); $a = phpx\Access::for_reflection($r); ensure($a->is_public()); ensure($a->is_static()); ensure($a->is_final()); ensure(!$a->is_abstract()); }
public function test_value_is_coerced_to_value_object() { ensure($this->c->get_value() instanceof phpx\Value); }
/** * Get table by name * * @param string table * @param string database default NULL if omitted, uses current database * @return rdbms.DBTable a DBTable object */ public function getTable($table, $database = NULL) { try { $this->prepareTemporaryIndexesTable(); $t = $this->dbTableObjectFor($table, $database); } catch (SQLException $e) { delete($t); } ensure($e); $this->dropTemporaryIndexesTable(); if ($e) { throw $e; } return $t; }
}); it("should match /book(/:id) to /book", function () { Router::prepare(function ($r) { $r->match("/book(/:id)")->to(array("controller" => "store", "action" => "books")); }); $r = Router::getInstance(); $pattern = $r->arrays_to_regexps(array("path" => "/book(/:id)")); $match = preg_match("/" . $pattern . "/", "/book", $matches); ensure($match, "Failed to match route /book with path: /book(/:id) using pattern: {$pattern}"); $r->reset(); }); it("should match /book(/:id) to /book/100", function () { $r = Router::getInstance(); $pattern = $r->arrays_to_regexps(array("path" => "/book(/:id)")); $match = preg_match("/" . $pattern . "/", "/book/100", $matches); ensure($match, "Failed to match route /book/100 with path: /book(/:id) using pattern: {$pattern}"); $r->reset(); }); }); describe("Router -> param_keys_for_path", function () { it("should extract :controller, :action, :id for /:controller/:action/:id", function () { $r = Router::getInstance(); $params = $r->param_keys_for_path("/:controller/:action/:id"); assert_equal($params[0], ":controller", "Failed to match :controller"); assert_equal($params[1], ":action", "Failed to match :action"); assert_equal($params[2], ":id", "Failed to match :id"); assert_equal(count($params), 3, "Failed to have 3 keys"); $r->reset(); }); it("should extract :controller, :action for /:controller/:action", function () { $r = Router::getInstance();
public function test_literal_or_object_returns_wrapping_value() { $object = phpx\literal_or_object("foreach"); ensure($object instanceof phpx\Literal); assert_equal("foreach", $object->to_php()); }
/** * Callback for the "STOR" command * * @param peer.Socket socket * @param string params */ public function onStor($socket, $params) { if (!($dataSocket = $this->openDatasock($socket))) { return; } if (!($entry = $this->storage->lookup($socket->hashCode(), $params))) { // Invoke interceptor $entry = $this->storage->createEntry($socket->hashCode(), $params, ST_ELEMENT); if (!$this->checkInterceptors($socket, $entry, 'onCreate')) { $dataSocket->close(); return; } try { $entry = $this->storage->create($socket->hashCode(), $params, ST_ELEMENT); } catch (XPException $e) { $this->answer($socket, 550, $params . ': ' . $e->getMessage()); $dataSocket->close(); return; } } else { if ($entry instanceof StorageCollection) { $this->answer($socket, 550, $params . ': is a directory'); $dataSocket->close(); return; } } $this->answer($socket, 150, sprintf('Opening %s mode data connection for %s', $this->sessions[$socket->hashCode()]->getType(), $entry->getName())); try { $entry->open(SE_WRITE); while (!$dataSocket->eof() && ($buf = $dataSocket->readBinary(32768))) { $entry->write($buf); } $entry->close(); } catch (XPException $e) { $this->answer($socket, 550, $params . ': ' . $e->getMessage()); } ensure($e); $dataSocket->close(); if ($e) { return; } // Post check interception if (!$this->checkInterceptors($socket, $entry, 'onStored')) { $entry->delete(); return; } $this->answer($socket, 226, 'Transfer complete'); }
/** * @param string $directory * @param int $order_flag * @param resource|null $context * @return array */ function directory_list($directory, $order_flag = SCANDIR_SORT_ASCENDING, $context = null) { debug_enforce(is_dir($directory), "Parameter " . var_dump_human_compact($directory) . " is not a directory."); debug_enforce(in_array($order_flag, [SCANDIR_SORT_DESCENDING, SCANDIR_SORT_ASCENDING, SCANDIR_SORT_NONE]), "Invalid order flag " . var_dump_human_compact($order_flag)); debug_enforce(is_null($context) || is_resource($context), "Invalid resource context " . var_dump_human_compact($context)); $directory = ensure($directory, str_endswith_dg(DIRECTORY_SEPARATOR), str_append_dg(DIRECTORY_SEPARATOR)); if (is_null($context)) { $ret = scandir($directory, $order_flag); } else { $ret = scandir($directory, $order_flag, $context); } debug_enforce(false !== $ret, posix_get_last_error()); return array_chain($ret, array_filter_key_dg(not_dg(in_array_dg(['..', '.']))), array_map_val_dg(str_prepend_dg($directory))); }
public function entriesInLang() { $c = new ArchiveCollection($this->archive, 'lang'); try { $c->open(); $expect = array('lang/Object.xp' => 'io.collections.IOElement', 'lang/Type.xp' => 'io.collections.IOElement', 'lang/reflect' => 'io.collections.IOCollection', 'lang/types' => 'io.collections.IOCollection', 'lang/Runnable.xp' => 'io.collections.IOElement'); for (reset($expect); $element = $c->next(), $name = key($expect); next($expect)) { $this->assertSubclass($element, $expect[$name]); $this->assertXarUri($name, $element->getURI()); } $this->assertEquals(NULL, $c->next()); } catch (Throwable $e) { } ensure($e); $c->close(); if ($e) { throw $e; } }
function test_resolve_include_path() { $filename_with_extension = basename(__FILE__); $filename = preg_replace('/\\.[^\\.]+$/', '', $filename_with_extension); ensure(!Environmentalist::resolve_include_path($filename)); Environmentalist::append_include_path(__DIR__); assert_equal(__DIR__ . DIRECTORY_SEPARATOR . $filename_with_extension, Environmentalist::resolve_include_path($filename)); Environmentalist::remove_include_path(__DIR__); }
// </root> /* * Add attr="attr1" to the newly added <bar> element */ $xml->set('foo/bar[ding]', 'attr1'); ensure($xml->get('foo/bar[ding]') == 'attr1'); ensure((string) $xml->root()->foo->bar['ding'] == 'attr1'); // <root attr="attr0"> // <foo> // <bar ding="attr1">el1</bar> // </foo> // </root> /* * Add a new <foo> element to the root. * Inside that, add a <bar> element with the contents "el2" */ $xml->set('foo[]/bar', 'el2'); ensure($xml->get('foo[1]/bar') == 'el2'); ensure((string) $xml->root()->foo[1]->bar == 'el2'); // <root attr="attr0"> // <foo> // <bar ding="attr1">el1</bar> // </foo> // <foo> // <bar>el2</bar> // </foo> // </root> foreach ($xml->root()->xpath('//*') as $element) { print PHP_EOL; print_r($element->asXml()); }
public function test_access_is_applied_to_added_members() { $this->def->set_abstract(true); $this->def->with_access('protected static abstract', function ($c) { $c->define_method('foo', ''); $c->define_variable('bar'); }); $this->with_class(function ($i, $r, $d) { $methods = $r->getMethods(); assert_equal(1, count($methods)); ensure($methods[0]->isProtected()); ensure($methods[0]->isStatic()); ensure($methods[0]->isAbstract()); $vars = $r->getProperties(); assert_equal(1, count($vars)); ensure($vars[0]->isProtected()); ensure($vars[0]->isStatic()); }); }
public function split($by = ' ') { ensure('Argument', $by, 'is_a_string', __CLASS__, __METHOD__); return V(explode($by, $this->string)); }
public function test_reference() { $this->arg->set_reference(true); $this->expect('&$arg'); ensure($this->arg->is_reference()); }
private function add_happiness() { try { // Save happiness data... // We expect: // _ location (INT) // _ happiness (INT) // _ unhappiness (INT) ensure(array_key_exists('location', $_POST), 'Location required'); ensure(array_key_exists('happiness', $_POST), 'Happiness required'); ensure(array_key_exists('unhappiness', $_POST), 'Unhappiness required'); list($location, $happiness, $unhappiness) = array(intval($_POST['location']), intval($_POST['happiness']), intval($_POST['unhappiness'])); } catch (Exception $e) { $this->bad_request($e); } // http://uk2.php.net/manual/en/sqlite3.open.php $db = new SQLite3('./happy-balls.db', SQLITE3_OPEN_READWRITE); $sql = sprintf('INSERT INTO happiness(location, happiness, unhappiness) VALUES (%d, %d, %d);', $location, $happiness, $unhappiness); $db->exec($sql); $id = $db->lastInsertRowID(); $db->close(); print "OK, id={$id}\n"; }
function with() { $args = func_get_args(); if (($block = array_pop($args)) instanceof \Closure) { try { call_user_func_array($block, $args); } catch (\lang\Throwable $e) { // Fall through } ensure($e); foreach ($args as $arg) { if (!$arg instanceof \lang\Closeable) { continue; } try { $arg->close(); } catch (\lang\Throwable $ignored) { // } } if ($e) { throw $e; } } }
<?php require_once "lib/init.php"; ensure("post"); expects(array("name" => "string", "description" => "string", "price" => "int")); json(RecommendedItem::create($params));
function test_should_separate_response_headers_from_body() { ensure(is_array($this->response->headers)); assert_matches('#^<!doctype#', $this->response->body); }
function split_uri($uri) { ensure('URI', $uri, 'is_a_string', __FUNCTION__); $splitted_uri = explode('/', $uri); // Remove empty strings from beginning and end if (count($splitted_uri) > 1) { $last = end($splitted_uri); $first = reset($splitted_uri); if (empty($last)) { array_pop($splitted_uri); } if (empty($first)) { array_shift($splitted_uri); } } return $splitted_uri; }
function assert_not_null($v, $msg = "") { ensure($v !== null, $msg); }
function test_error_handler() { $file = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'open_struct.php'; ensure(!OpenStruct::error_handler(1, 'error message', __FILE__, 1, array())); ensure(!OpenStruct::error_handler(1, 'error message', $file, 1, array())); ensure(!OpenStruct::error_handler(OpenStruct::NON_STATIC_METHOD_CALL_ERROR, 'error message', __FILE__, 1, array())); ensure(!OpenStruct::error_handler(OpenStruct::NON_STATIC_METHOD_CALL_ERROR, 'error message', $file, 1, array())); assert_null(OpenStruct::error_handler(OpenStruct::NON_STATIC_METHOD_CALL_ERROR, 'error message', $file . '-eval', 1, array())); }