From 7dbe0626b6f6aa67bd9b3916778aa7e137596fb2 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Thu, 19 May 2011 13:06:56 +0000 Subject: [PATCH 02/82] Update new xml query classes with xe 1.5 with improved query argument support and update and delete queries git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8378 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 10 + classes/db/DBCubrid.class.php | 61 +- .../queryparts/condition/Condition.class.php | 87 +++ .../condition/ConditionGroup.class.php | 27 + .../expression/ClickCountExpression.class.php | 33 + .../expression/DeleteExpression.class.php | 34 ++ .../expression/Expression.class.php | 30 + .../expression/InsertExpression.class.php | 28 + .../expression/SelectExpression.class.php | 32 + .../expression/StarExpression.class.php | 16 + .../expression/UpdateExpression.class.php | 34 ++ .../queryparts/order/OrderByColumn.class.php | 16 + .../db/queryparts/table/JoinTable.class.php | 37 ++ classes/db/queryparts/table/Table.class.php | 26 + classes/display/HTMLDisplayHandler.php | 1 + classes/xml/XmlQueryParser.class.php | 574 ++---------------- classes/xml/xmlquery/DBParser.class.php | 98 +++ classes/xml/xmlquery/QueryParser.class.php | 160 +++++ .../xml/xmlquery/argument/Argument.class.php | 113 ++++ .../ConditionQueryArgument.class.php | 26 + .../queryargument/DefaultValue.class.php | 61 ++ .../queryargument/QueryArgument.class.php | 52 ++ .../ConditionQueryArgumentValidator.class.php | 20 + .../validator/DefaultCheck.class.php | 25 + .../validator/EscapeCheck.class.php | 21 + .../validator/FilterValidator.class.php | 16 + .../validator/MaxLengthValidator.class.php | 22 + .../validator/MinLengthValidator.class.php | 22 + .../validator/NotNullValidator.class.php | 18 + .../QueryArgumentValidator.class.php | 62 ++ .../validator/Validator.class.php | 7 + .../condition/ConditionGroupTag.class.php | 52 ++ .../tags/condition/ConditionTag.class.php | 49 ++ .../tags/condition/ConditionsTag.class.php | 51 ++ .../xmlquery/tags/group/GroupsTag.class.php | 36 ++ .../tags/navigation/IndexTag.class.php | 49 ++ .../tags/navigation/NavigationTag.class.php | 60 ++ .../xmlquery/tags/table/TableTag.class.php | 60 ++ .../xmlquery/tags/table/TablesTag.class.php | 33 + 39 files changed, 1619 insertions(+), 540 deletions(-) create mode 100644 classes/db/queryparts/condition/Condition.class.php create mode 100644 classes/db/queryparts/condition/ConditionGroup.class.php create mode 100644 classes/db/queryparts/expression/ClickCountExpression.class.php create mode 100644 classes/db/queryparts/expression/DeleteExpression.class.php create mode 100644 classes/db/queryparts/expression/Expression.class.php create mode 100644 classes/db/queryparts/expression/InsertExpression.class.php create mode 100644 classes/db/queryparts/expression/SelectExpression.class.php create mode 100644 classes/db/queryparts/expression/StarExpression.class.php create mode 100644 classes/db/queryparts/expression/UpdateExpression.class.php create mode 100644 classes/db/queryparts/order/OrderByColumn.class.php create mode 100644 classes/db/queryparts/table/JoinTable.class.php create mode 100644 classes/db/queryparts/table/Table.class.php create mode 100644 classes/xml/xmlquery/DBParser.class.php create mode 100644 classes/xml/xmlquery/QueryParser.class.php create mode 100644 classes/xml/xmlquery/argument/Argument.class.php create mode 100644 classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php create mode 100644 classes/xml/xmlquery/queryargument/DefaultValue.class.php create mode 100644 classes/xml/xmlquery/queryargument/QueryArgument.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php create mode 100644 classes/xml/xmlquery/queryargument/validator/Validator.class.php create mode 100644 classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php create mode 100644 classes/xml/xmlquery/tags/condition/ConditionTag.class.php create mode 100644 classes/xml/xmlquery/tags/condition/ConditionsTag.class.php create mode 100644 classes/xml/xmlquery/tags/group/GroupsTag.class.php create mode 100644 classes/xml/xmlquery/tags/navigation/IndexTag.class.php create mode 100644 classes/xml/xmlquery/tags/navigation/NavigationTag.class.php create mode 100644 classes/xml/xmlquery/tags/table/TableTag.class.php create mode 100644 classes/xml/xmlquery/tags/table/TablesTag.class.php diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 08a62d266..2d1f9dd27 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -314,6 +314,16 @@ if($source_args) $args = @clone($source_args); + require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/expression/SelectExpression.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/expression/InsertExpression.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/table/Table.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/table/JoinTable.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/condition/ConditionGroup.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/condition/Condition.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/expression/StarExpression.class.php'); + $output = @include($cache_file); if( (is_a($output, 'Object') || is_subclass_of($output, 'Object')) && !$output->toBool()) return $output; diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index d938d4001..171bf6a47 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -812,7 +812,65 @@ * to get a specific page list easily in select statement,\n * a method, navigation, is used **/ - function _executeSelectAct ($output) + function _executeSelectAct($output){ + $query = ''; + + $select = 'SELECT '; + foreach($output->columns as $column){ + if($column->show()) + $select .= $column->getExpression() . ', '; + } + $select = substr($select, 0, -2); + + $from = 'FROM '; + $simple_table_count = 0; + foreach($output->tables as $table){ + /*if($simple_table_count > 0) $from .= ', '; + + $from .= $table->toString() . ' '; + if(!$table->isJoinTable()) $simple_table_count++; + */ + if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; + else $from .= ', '.$table->toString() . ' '; + $simple_table_count++; + } + + $where = ''; + if(count($output->conditions) > 0){ + $where = 'WHERE '; + foreach($output->conditions as $conditionGroup){ + $where .= $conditionGroup->toString(); + } + } + + $groupBy = ''; + if($output->groups) if($output->groups[0] !== "") + $groupBy = 'GROUP BY ' . implode(', ', $output->groups); + + $orderBy = ''; + if(count($output->orderby) > 0){ + $orderBy = 'ORDER BY '; + foreach($output->orderby as $order){ + $orderBy .= $order->toString() .', '; + } + $orderBy = substr($orderBy, 0, -2); + } + + + $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; + + //$query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, //$groupby_query.$orderby_query); + //$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result = $this->_query ($query); + if ($this->isError ()) return; + $data = $this->_fetch ($result); + + $buff = new Object (); + $buff->data = $data; + + return $buff; + } + /*function _executeSelectAct ($output) { // tables $table_list = array (); @@ -1049,6 +1107,7 @@ return $buff; } + */ /** * @brief displays the current stack trace. Fetch the result diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php new file mode 100644 index 000000000..ea8657b71 --- /dev/null +++ b/classes/db/queryparts/condition/Condition.class.php @@ -0,0 +1,87 @@ +column_name = $column_name; + $this->value = $value; + $this->operation = $operation; + $this->pipe = $pipe; + } + + function toString(){ + return $this->pipe . ' ' . $this->getConditionPart($this->column_name, $this->value, $this->operation); + } + + function getConditionPart($name, $value, $operation) { + switch($operation) { + case 'equal' : + case 'more' : + case 'excess' : + case 'less' : + case 'below' : + case 'like_tail' : + case 'like_prefix' : + case 'like' : + case 'in' : + case 'notin' : + case 'notequal' : + // if variable is not set or is not string or number, return + if(!isset($value)) return; + if($value === '') return; + if(!in_array(gettype($value), array('string', 'integer'))) return; + break; + case 'between' : + if(!is_array($value)) return; + if(count($value)!=2) return; + + } + + switch($operation) { + case 'equal' : + return $name.' = '.$value; + break; + case 'more' : + return $name.' >= '.$value; + break; + case 'excess' : + return $name.' > '.$value; + break; + case 'less' : + return $name.' <= '.$value; + break; + case 'below' : + return $name.' < '.$value; + break; + case 'like_tail' : + case 'like_prefix' : + case 'like' : + return $name.' like '.$value; + break; + case 'in' : + return $name.' in ('.$value.')'; + break; + case 'notin' : + return $name.' not in ('.$value.')'; + break; + case 'notequal' : + return $name.' <> '.$value; + break; + case 'notnull' : + return $name.' is not null'; + break; + case 'null' : + return $name.' is null'; + break; + case 'between' : + return $name.' between ' . $value[0] . ' and ' . $value[1]; + break; + } + } + } + +?> \ No newline at end of file diff --git a/classes/db/queryparts/condition/ConditionGroup.class.php b/classes/db/queryparts/condition/ConditionGroup.class.php new file mode 100644 index 000000000..ecf5870f1 --- /dev/null +++ b/classes/db/queryparts/condition/ConditionGroup.class.php @@ -0,0 +1,27 @@ +conditions = $conditions; + $this->pipe = $pipe; + } + + function toString(){ + if($this->pipe !== "") + $group = $this->pipe .'('; + else $group = ''; + + foreach($this->conditions as $condition){ + $group .= $condition->toString() . ' '; + } + + if($this->pipe !== "") + $group .= ')'; + + return $group; + } + } +?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/ClickCountExpression.class.php b/classes/db/queryparts/expression/ClickCountExpression.class.php new file mode 100644 index 000000000..a112368e8 --- /dev/null +++ b/classes/db/queryparts/expression/ClickCountExpression.class.php @@ -0,0 +1,33 @@ +click_count = false; + return; + } + $this->click_count = $click_count; + } + + function show() { + return $this->click_count; + } + + function getExpression(){ + return "$this->column_name = $this->column_name + 1"; + } + } + +?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/DeleteExpression.class.php b/classes/db/queryparts/expression/DeleteExpression.class.php new file mode 100644 index 000000000..041173f2f --- /dev/null +++ b/classes/db/queryparts/expression/DeleteExpression.class.php @@ -0,0 +1,34 @@ +value = $value; + } + + function getExpression(){ + return "$this->column_name = $this->value"; + } + + function getValue(){ + // TODO Escape value according to column type instead of variable type + if(!is_numeric($this->value)) return "'".$this->value."'"; + return $this->value; + } + + function show(){ + if(!$this->value) return false; + return true; + } + } + + +?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/Expression.class.php b/classes/db/queryparts/expression/Expression.class.php new file mode 100644 index 000000000..bd11929f6 --- /dev/null +++ b/classes/db/queryparts/expression/Expression.class.php @@ -0,0 +1,30 @@ +column_name = $column_name; + } + + function getColumnName(){ + return $this->column_name; + } + + function show() { + return false; + } + + function getExpression() { + } + } \ No newline at end of file diff --git a/classes/db/queryparts/expression/InsertExpression.class.php b/classes/db/queryparts/expression/InsertExpression.class.php new file mode 100644 index 000000000..633bacaf5 --- /dev/null +++ b/classes/db/queryparts/expression/InsertExpression.class.php @@ -0,0 +1,28 @@ +value = $value; + } + + function getValue(){ + return $this->value; + } + + function show(){ + if(!isset($this->value)) return false; + return true; + } + } + +?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/SelectExpression.class.php b/classes/db/queryparts/expression/SelectExpression.class.php new file mode 100644 index 000000000..5de23b43a --- /dev/null +++ b/classes/db/queryparts/expression/SelectExpression.class.php @@ -0,0 +1,32 @@ +column_alias = $alias; + } + + function getExpression() { + return sprintf("%s%s", $this->column_name, $this->column_alias ? " as ".$this->column_alias : ""); + } + + function show() { + return true; + } + } +?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/StarExpression.class.php b/classes/db/queryparts/expression/StarExpression.class.php new file mode 100644 index 000000000..c718fdbc9 --- /dev/null +++ b/classes/db/queryparts/expression/StarExpression.class.php @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/classes/db/queryparts/expression/UpdateExpression.class.php b/classes/db/queryparts/expression/UpdateExpression.class.php new file mode 100644 index 000000000..fb3047ee3 --- /dev/null +++ b/classes/db/queryparts/expression/UpdateExpression.class.php @@ -0,0 +1,34 @@ +value = $value; + } + + function getExpression(){ + return "$this->column_name = $this->value"; + } + + function getValue(){ + // TODO Escape value according to column type instead of variable type + if(!is_numeric($this->value)) return "'".$this->value."'"; + return $this->value; + } + + function show(){ + if(!$this->value) return false; + return true; + } + } + + +?> \ No newline at end of file diff --git a/classes/db/queryparts/order/OrderByColumn.class.php b/classes/db/queryparts/order/OrderByColumn.class.php new file mode 100644 index 000000000..b5db8e9ce --- /dev/null +++ b/classes/db/queryparts/order/OrderByColumn.class.php @@ -0,0 +1,16 @@ +column_name = $column_name; + $this->sort_order = $sort_order; + } + + function toString(){ + return $this->column_name . ' ' . $this->sort_order; + } + } + +?> \ No newline at end of file diff --git a/classes/db/queryparts/table/JoinTable.class.php b/classes/db/queryparts/table/JoinTable.class.php new file mode 100644 index 000000000..7294a5167 --- /dev/null +++ b/classes/db/queryparts/table/JoinTable.class.php @@ -0,0 +1,37 @@ +join_type = $join_type; + $this->conditions = $conditions; + } + + function toString(){ + $part = $this->join_type . ' ' . $this->name ; + $part .= $this->alias ? ' as ' . $this->alias : ''; + $part .= ' on '; + foreach($this->conditions as $conditionGroup) + $part .= $conditionGroup->toString(); + return $part; + } + + function isJoinTable(){ + return true; + } + } + +?> \ No newline at end of file diff --git a/classes/db/queryparts/table/Table.class.php b/classes/db/queryparts/table/Table.class.php new file mode 100644 index 000000000..b2b7d5506 --- /dev/null +++ b/classes/db/queryparts/table/Table.class.php @@ -0,0 +1,26 @@ +name = $name; + $this->alias = $alias; + } + + function toString(){ + return sprintf("%s%s", $this->name, $this->alias ? ' as ' . $this->alias : ''); + } + + function getName(){ + return $this->name; + } + + function isJoinTable(){ + if(in_array($tableName,array('left join','left outer join','right join','right outer join'))) return true; + return false; + } + } + +?> \ No newline at end of file diff --git a/classes/display/HTMLDisplayHandler.php b/classes/display/HTMLDisplayHandler.php index 6df5a2c02..34c8ea3f0 100644 --- a/classes/display/HTMLDisplayHandler.php +++ b/classes/display/HTMLDisplayHandler.php @@ -151,6 +151,7 @@ class HTMLDisplayHandler { $oContext->addJsFile('./common/js/x.min.js', false, '', -100000); $oContext->addJsFile('./common/js/xe.min.js', false, '', -100000); $oContext->addCSSFile('./common/css/xe.min.css', false, 'all', '', -100000); + $oContext->addJsFile('./common/js/xml_handler.js', false, '', -100000); } // for admin page, add admin css diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 27e6692ba..6c7192bf1 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -1,558 +1,54 @@ getXmlFileContent($xml_file); + + // insert, update, delete, select action + $action = strtolower($xml_obj->query->attrs->action); + if(!$action) return; + + //$oDB = &DB::getParser(); + //$dbParser = $oDB->getParser(); + $dbParser = getDBParser(); + $parser = new QueryParser($xml_obj->query, $dbParser); + + FileHandler::writeFile($cache_file, $parser->toString()); + } + + // singleton + function getDBParser(){ + if(!$this->dbParser){ + //$oDB = &DB::getParser(); + //$dbParser = $oDB->getParser(); + $this->dbParser = new DBParser('`'); + } + return $this->dbParser; + } + + function getXmlFileContent($xml_file){ $buff = FileHandler::readFile($xml_file); $xml_obj = parent::parse($buff); if(!$xml_obj) return; unset($buff); - - $id_args = explode('.', $query_id); - if(count($id_args)==2) { - $target = 'modules'; - $module = $id_args[0]; - $id = $id_args[1]; - } elseif(count($id_args)==3) { - $target = $id_args[0]; - if(!in_array($target, array('modules','addons','widgets'))) return; - $module = $id_args[1]; - $id = $id_args[2]; - } - // actions like insert, update, delete, select and so on - $action = strtolower($xml_obj->query->attrs->action); - if(!$action) return; - // get the table list(converting an array code) - $tables = $xml_obj->query->tables->table; - $output->left_tables = array(); - - $left_conditions = array(); - - if(!$tables) return; - if(!is_array($tables)) $tables = array($tables); - foreach($tables as $key => $val) { - // get the name of tables and aliases - $table_name = $val->attrs->name; - $alias = $val->attrs->alias; - if(!$alias) $alias = $table_name; - - $output->tables[$alias] = $table_name; - - if(in_array($val->attrs->type,array('left join','left outer join','right join','right outer join')) && count($val->conditions)){ - $output->left_tables[$alias] = $val->attrs->type; - $left_conditions[$alias] = $val->conditions; - } - // get column properties from the table - $table_file = sprintf('%s%s/%s/schemas/%s.xml', _XE_PATH_, 'modules', $module, $table_name); - if(!file_exists($table_file)) { - $searched_list = FileHandler::readDir(_XE_PATH_.'modules'); - $searched_count = count($searched_list); - for($i=0;$i<$searched_count;$i++) { - $table_file = sprintf('%s%s/%s/schemas/%s.xml', _XE_PATH_, 'modules', $searched_list[$i], $table_name); - if(file_exists($table_file)) break; - } - } - - if(file_exists($table_file)) { - $table_xml = FileHandler::readFile($table_file); - $table_obj = parent::parse($table_xml); - if($table_obj->table) { - if(isset($table_obj->table->column) && !is_array($table_obj->table->column)) - { - $table_obj->table->column = array($table_obj->table->column); - } - - foreach($table_obj->table->column as $k => $v) { - $buff .= sprintf('$output->column_type["%s"] = "%s";%s', $v->attrs->name, $v->attrs->type, "\n"); - } - } - } - } - // Column list - $columns = $xml_obj->query->columns->column; - $out = $this->_setColumn($columns); - $output->columns = $out->columns; - - $conditions = $xml_obj->query->conditions; - $out = $this->_setConditions($conditions); - $output->conditions = $out->conditions; - - foreach($output->left_tables as $key => $val){ - if($left_conditions[$key]){ - $out = $this->_setConditions($left_conditions[$key]); - $output->left_conditions[$key] = $out->conditions; - } - } - - $group_list = $xml_obj->query->groups->group; - $out = $this->_setGroup($group_list); - $output->groups = $out->groups; - - //priority arrange - $priority = $xml_obj->query->priority; - if($priority) $output->priority['type'] = $priority->attrs->type; - - //index hint arrange - $index_hint = $xml_obj->query->index_hint; - if($index_hint) - { - $output->index_hint['name'] = $index_hint->attrs->name; - $output->index_hint['type'] = $index_hint->attrs->type; - } - - // Navigation - $out = $this->_setNavigation($xml_obj); - $output->order = $out->order; - $output->list_count = $out->list_count; - $output->page_count = $out->page_count; - $output->page = $out->page; - - $column_count = count($output->columns); - $priority_count = count($output->priority); - $index_hint_count = count($output->index_hint); - $condition_count = count($output->conditions); - - $buff .= '$output->tables = array( '; - foreach($output->tables as $key => $val) { - if(!array_key_exists($key,$output->left_tables)){ - $buff .= sprintf('"%s"=>"%s",', $key, $val); - } - } - $buff .= ' );'."\n"; - // generates a php script - $buff .= '$output->_tables = array( '; - foreach($output->tables as $key => $val) { - $buff .= sprintf('"%s"=>"%s",', $key, $val); - } - $buff .= ' );'."\n"; - - if(count($output->left_tables)){ - $buff .= '$output->left_tables = array( '; - foreach($output->left_tables as $key => $val) { - $buff .= sprintf('"%s"=>"%s",', $key, $val); - } - $buff .= ' );'."\n"; - } - // column info - if($column_count) { - $buff .= '$output->columns = array ( '; - $buff .= $this->_getColumn($output->columns); - $buff .= ' );'."\n"; - } - - //priority arrange - if($priority_count) { - $priority_str .= '$output->priority = array("type"=>"%s");'."\n"; - $buff .= vsprintf($priority_str, $output->priority); - } - - // index arrange - if($index_hint_count) { - $index_hint_str .= '$output->index_hint = array("name"=>"%s", "type"=>"%s");'."\n"; - $buff .= vsprintf($index_hint_str, $output->index_hint); - } - - // get conditions - if($condition_count) { - $buff .= '$output->conditions = array ( '; - $buff .= $this->_getConditions($output->conditions); - $buff .= ' );'."\n"; - } - // get conditions - if(count($output->left_conditions)) { - $buff .= '$output->left_conditions = array ( '; - foreach($output->left_conditions as $key => $val){ - $buff .= "'{$key}' => array ( "; - $buff .= $this->_getConditions($val); - $buff .= "),\n"; - } - $buff .= ' );'."\n"; - } - - // get arguments - $arg_list = $this->getArguments(); - if($arg_list) - { - foreach($arg_list as $arg) - { - $pre_buff .= 'if(is_object($args->'.$arg.')){ $args->'.$arg.' = array_values(get_method_vars($args->'.$arg.')); }'. "\n"; - $pre_buff .= 'if(is_array($args->'.$arg.') && count($args->'.$arg.')==0){ unset($args->'.$arg.'); };'."\n"; - } - } - - // order - if($output->order) { - $buff .= '$output->order = array('; - foreach($output->order as $key => $val) { - $buff .= sprintf('array($args->%s?$args->%s:"%s",in_array($args->%s,array("asc","desc"))?$args->%s:("%s"?"%s":"asc")),', $val->var, $val->var, $val->default, $val->order, $val->order, $val->order, $val->order); - } - $buff .= ');'."\n"; - } - - // list_count - if($output->list_count) { - $buff .= sprintf('$output->list_count = array("var"=>"%s", "value"=>$args->%s?$args->%s:"%s");%s', $output->list_count->var, $output->list_count->var, $output->list_count->var, $output->list_count->default,"\n"); - } - - // page_count - if($output->page_count) { - $buff .= sprintf('$output->page_count = array("var"=>"%s", "value"=>$args->%s?$args->%s:"%s");%s', $output->page_count->var, $output->page_count->var, $output->page_count->var, $output->list_count->default,"\n"); - } - - // page order - if($output->page) { - $buff .= sprintf('$output->page = array("var"=>"%s", "value"=>$args->%s?$args->%s:"%s");%s', $output->page->var, $output->page->var, $output->page->var, $output->list->default,"\n"); - } - - // group by - if($output->groups) { - $buff .= sprintf('$output->groups = array("%s");%s', implode('","',$output->groups),"\n"); - } - - // minlength check - if(count($minlength_list)) { - foreach($minlength_list as $key => $val) { - $pre_buff .= 'if($args->'.$key.'&&strlen($args->'.$key.')<'.$val.') return new Object(-1, sprintf($lang->filter->outofrange, $lang->'.$key.'?$lang->'.$key.':\''.$key.'\'));'."\n"; - } - } - - // maxlength check - if(count($maxlength_list)) { - foreach($maxlength_list as $key => $val) { - $pre_buff .= 'if($args->'.$key.'&&strlen($args->'.$key.')>'.$val.') return new Object(-1, sprintf($lang->filter->outofrange, $lang->'.$key.'?$lang->'.$key.':\''.$key.'\'));'."\n"; - } - } - - // filter check - if(count($this->filter_list)) { - foreach($this->filter_list as $key => $val) { - $pre_buff .= sprintf('if(isset($args->%s)) { unset($_output); $_output = $this->checkFilter("%s",$args->%s,"%s"); if(!$_output->toBool()) return $_output; } %s',$val->var, $val->var,$val->var,$val->filter,"\n"); - } - } - - // default check - if(count($this->default_list)) { - foreach($this->default_list as $key => $val) { - $pre_buff .= 'if(!isset($args->'.$key.')) $args->'.$key.' = '.$val.';'."\n"; - } - } - - // not null check - if(count($this->notnull_list)) { - foreach($this->notnull_list as $key => $val) { - $pre_buff .= 'if(!isset($args->'.$val.')) return new Object(-1, sprintf($lang->filter->isnull, $lang->'.$val.'?$lang->'.$val.':\''.$val.'\'));'."\n"; - } - } - - $buff = "query_id = "%s";%s', $query_id, "\n") - . sprintf('$output->action = "%s";%s', $action, "\n") - . $pre_buff - . $buff - . 'return $output; ?>'; - - // Save - FileHandler::writeFile($cache_file, $buff); + return $xml_obj; } - /** - * @brief transfer given column information to object->columns - * @param[in] column information - * @result Returns $object - */ - - function _setColumn($columns){ - if(!$columns) { - $output->column[] = array("*" => "*"); - } else { - if(!is_array($columns)) $columns = array($columns); - foreach($columns as $key => $val) { - $name = $val->attrs->name; - /* - if(strpos('.',$name)===false && count($output->tables)==1) { - $tmp = array_values($output->tables); - $name = sprintf('%s.%s', $tmp[0], $val->attrs->name); - } - */ - - $output->columns[] = array( - "name" => $name, - "var" => $val->attrs->var, - "default" => $val->attrs->default, - "notnull" => $val->attrs->notnull, - "filter" => $val->attrs->filter, - "minlength" => $val->attrs->minlength, - "maxlength" => $val->attrs->maxlength, - "alias" => $val->attrs->alias, - "click_count" => $val->attrs->click_count, - ); - } - } - return $output; - } - - /** - * @brief transfer condition information to $object->conditions - * @param[in] SQL condition information - * @result Returns $output - */ - function _setConditions($conditions){ - // Conditional clause - $condition = $conditions->condition; - if($condition) { - $obj->condition = $condition; - unset($condition); - $condition = array($obj); - } - $condition_group = $conditions->group; - if($condition_group && !is_array($condition_group)) $condition_group = array($condition_group); - - if($condition && $condition_group) $cond = array_merge($condition, $condition_group); - elseif($condition_group) $cond = $condition_group; - else $cond = $condition; - - if($cond) { - foreach($cond as $key => $val) { - unset($cond_output); - - if($val->attrs->pipe) $cond_output->pipe = $val->attrs->pipe; - else $cond_output->pipe = null; - - if(!$val->condition) continue; - if(!is_array($val->condition)) $val->condition = array($val->condition); - - foreach($val->condition as $k => $v) { - $obj = $v->attrs; - if(!$obj->alias) $obj->alias = $obj->column; - $cond_output->condition[] = $obj; - } - - $output->conditions[] = $cond_output; - } - } - return $output; - } - - /** - * @brief transfer condition information to $object->groups - * @param[in] SQL group information - * @result Returns $output - */ - function _setGroup($group_list){ - // group list - - if($group_list) { - if(!is_array($group_list)) $group_list = array($group_list); - for($i=0;$iattrs->column); - if(!$column) continue; - $group_column_list[] = $column; - } - if(count($group_column_list)) $output->groups = $group_column_list; - } - return $output; - } - - - /** - * @brief transfer pagnation information to $output - * @param[in] $xml_obj xml object containing Navigation information - * @result Returns $output - */ - function _setNavigation($xml_obj){ - $navigation = $xml_obj->query->navigation; - if($navigation) { - $order = $navigation->index; - if($order) { - if(!is_array($order)) $order = array($order); - foreach($order as $order_info) { - $output->order[] = $order_info->attrs; - } - } - - $list_count = $navigation->list_count->attrs; - $output->list_count = $list_count; - - $page_count = $navigation->page_count->attrs; - $output->page_count = $page_count; - - $page = $navigation->page->attrs; - $output->page = $page ; - } - return $output; - } - - /** - * @brief retrieve column information from $output->colums to generate corresponding php code - * @param[in] $column - * @remarks the name of this method is misleading. - * @result Returns string buffer containing php code - */ - function _getColumn($columns){ - $buff = ''; - $str = ''; - $print_vars = array(); - - foreach($columns as $key => $val) { - $str = 'array("name"=>"%s","alias"=>"%s"'; - $print_vars = array(); - $print_vars[] = $val['name']; - $print_vars[] = $val['alias']; - - $val['default'] = $this->getDefault($val['name'], $val['default']); - if($val['var'] && strpos($val['var'],'.')===false) { - - if($val['default']){ - $str .= ',"value"=>$args->%s?$args->%s:%s'; - $print_vars[] = $val['var']; - $print_vars[] = $val['var']; - $print_vars[] = $val['default']; - }else{ - $str .= ',"value"=>$args->%s'; - $print_vars[] = $val['var']; - } - - } else { - if($val['default']){ - $str .= ',"value"=>%s'; - $print_vars[] = $val['default']; - } - } - - if($val['click_count']){ - $str .= ',"click_count"=>$args->%s'; - $print_vars[] = $val['click_count']; - } - - $str .= '),%s'; - $print_vars[] = "\n"; - - $buff .= vsprintf($str, $print_vars); - } - return $buff; - } - - /** - * @brief retrieve condition information from $output->condition to generate corresponding php code - * @param[in] $conditions array containing Query conditions - * @remarks the name of this method is misleading. - * @return Returns string buffer containing php code - */ - function _getConditions($conditions){ - $buff = ''; - foreach($conditions as $key => $val) { - $buff .= sprintf('array("pipe"=>"%s",%s"condition"=>array(', $val->pipe,"\n"); - foreach($val->condition as $k => $v) { - $v->default = $this->getDefault($v->column, $v->default); - if($v->var) { - if(strpos($v->var,".")===false) { - if($v->default) $this->default_list[$v->var] = $v->default; - if($v->filter) $this->filter_list[] = $v; - if($v->notnull) $this->notnull_list[] = $v->var; - if($v->default) $buff .= sprintf('array("column"=>"%s", "value"=>$args->%s?$args->%s:%s,"pipe"=>"%s","operation"=>"%s",),%s', $v->column, $v->var, $v->var, $v->default, $v->pipe, $v->operation, "\n"); - else $buff .= sprintf('array("column"=>"%s", "value"=>$args->%s,"pipe"=>"%s","operation"=>"%s",),%s', $v->column, $v->var, $v->pipe, $v->operation, "\n"); - - $this->addArguments($v->var); - } else { - $buff .= sprintf('array("column"=>"%s", "value"=>"%s","pipe"=>"%s","operation"=>"%s",),%s', $v->column, $v->var, $v->pipe, $v->operation, "\n"); - } - } else { - if($v->default) $buff .= sprintf('array("column"=>"%s", "value"=>%s,"pipe"=>"%s","operation"=>"%s",),%s', $v->column, $v->default ,$v->pipe, $v->operation,"\n"); - else $buff .= sprintf('array("column"=>"%s", "pipe"=>"%s","operation"=>"%s",),%s', $v->column, $v->pipe, $v->operation,"\n"); - } - } - $buff .= ')),'."\n"; - } - return $buff; - } - - function addArguments($args_name) - { - $this->args[] = $args_name; - } - - function getArguments() - { - return $this->args; - } - - /** - * @brief returns predefined default values correspoding to given parameters - * @param[in] $name - * @param[in] $value - * @return Returns a default value for specified field - */ - function getDefault($name, $value) { - $db_info = Context::getDBInfo (); - if(!isset($value)) return; - $str_pos = strpos($value, '('); - if($str_pos===false) return '"'.$value.'"'; - - $func_name = substr($value, 0, $str_pos); - $args = substr($value, $str_pos+1, strlen($value)-1); - - switch($func_name) { - case 'ipaddress' : - $val = '$_SERVER[\'REMOTE_ADDR\']'; - break; - case 'unixtime' : - $val = 'time()'; - break; - case 'curdate' : - $val = 'date("YmdHis")'; - break; - case 'sequence' : - $val = '$this->getNextSequence()'; - break; - case 'plus' : - $args = abs($args); - if ($db_info->db_type == 'cubrid') { - $val = sprintf ('"\\"%s\\"+%d"', $name, $args); - } else { - $val = sprintf('"%s+%d"', $name, $args); - } - break; - case 'minus' : - $args = abs($args); - if ($db_info->db_type == 'cubrid') { - $val = sprintf ('"\\"%s\\"-%d"', $name, $args); - } else { - $val = sprintf('"%s-%d"', $name, $args); - } - break; - case 'multiply' : - $args = intval($args); - if ($db_info->db_type == 'cubrid') { - $val = sprintf ('"\\"%s\\"*%d"', $name, $args); - } else { - $val = sprintf('"%s*%d"', $name, $args); - } - break; - } - - return $val; - } + } ?> diff --git a/classes/xml/xmlquery/DBParser.class.php b/classes/xml/xmlquery/DBParser.class.php new file mode 100644 index 000000000..00b65ee93 --- /dev/null +++ b/classes/xml/xmlquery/DBParser.class.php @@ -0,0 +1,98 @@ +escape_char = $escape_char; + $this->table_prefix = $table_prefix; + } + + function getEscapeChar(){ + return $this->escape_char; + } + + function escape($name){ + return $this->escape_char . $name . $this->escape_char; + } + + function escapeString($name){ + return "'".$name."'"; + } + + function parseTableName($name){ + return $this->table_prefix . $name; + } + + function parseColumnName($name){ + return $this->escapeColumn($name); + } + + function escapeColumn($column_name){ + if($this->isUnqualifiedColumnName($column_name)) + return $this->escape($column_name); + if($this->isQualifiedColumnName($column_name)){ + list($table, $column) = explode('.', $column_name); + // $table can also be an alias, so the prefix should not be added + return $this->escape($table).'.'.$this->escape($column); + //return $this->escape($this->parseTableName($table)).'.'.$this->escape($column); + } + } + + function isUnqualifiedColumnName($column_name){ + if(strpos($column_name,'.')===false && strpos($column_name,'(')===false) return true; + return false; + } + + function isQualifiedColumnName($column_name){ + if(strpos($column_name,'.')!==false && strpos($column_name,'(')===false) return true; + return false; + } + + function parseExpression($column_name){ + $functions = preg_split('/([\+\-\*\/\ ])/', $column_name, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); + foreach($functions as &$function){ + if(strlen($function)==1) continue; // skip delimiters + $pos = strrpos("(", $function); + $matches = preg_split('/([a-zA-Z0-9_*]+)/', $function, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); + $total_brackets = substr_count($function, "("); + $brackets = 0; + foreach($matches as &$match){ + if($match == '(') {$brackets++; continue;} + if(strpos($match,')') !== false) continue; + if(in_array($match, array(',', '.'))) continue; + if($brackets == $total_brackets){ + if(!is_numeric($match)) { + $match = $this->escapeColumnExpression($match); + } + } + } + $function = implode('', $matches); + } + return implode('', $functions); + } + + function isStar($column_name){ + if(substr($column_name,-1) == '*') return true; + return false; + } + + /* + * Checks to see if expression is an aggregate star function + * like count(*) + */ + function isStarFunction($column_name){ + if(strpos($column_name, "(*)")!==false) return true; + return false; + } + + function escapeColumnExpression($column_name){ + if($this->isStar($column_name)) return $column_name; + if($this->isStarFunction($column_name)){ + return $column_name; + } + return $this->escapeColumn($column_name); + } + } + + \ No newline at end of file diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php new file mode 100644 index 000000000..00f95d5b8 --- /dev/null +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -0,0 +1,160 @@ +query = $query; + $this->action = $this->query->attrs->action; + $this->query_id = $this->query->attrs->id; + + $this->dbParser = $dbParser; + } + + function getQueryId(){ + return $this->query->attrs->query_id ? $this->query->attrs->query_id : $this->query->attrs->id; + } + + function getAction(){ + return $this->query->attrs->action; + } + + function getTableInfo($query_id, $table_name){ + $column_type = array(); + + $id_args = explode('.', $query_id); + if(count($id_args)==2) { + $target = 'modules'; + $module = $id_args[0]; + $id = $id_args[1]; + } elseif(count($id_args)==3) { + $target = $id_args[0]; + if(!in_array($target, array('modules','addons','widgets'))) return; + $module = $id_args[1]; + $id = $id_args[2]; + } + + // get column properties from the table + $table_file = sprintf('%s%s/%s/schemas/%s.xml', _XE_PATH_, 'modules', $module, $table_name); + if(!file_exists($table_file)) { + $searched_list = FileHandler::readDir(_XE_PATH_.'modules'); + $searched_count = count($searched_list); + for($i=0;$i<$searched_count;$i++) { + $table_file = sprintf('%s%s/%s/schemas/%s.xml', _XE_PATH_, 'modules', $searched_list[$i], $table_name); + if(file_exists($table_file)) break; + } + } + + if(file_exists($table_file)) { + $table_xml = FileHandler::readFile($table_file); + $xml_parser = new XmlParser(); + $table_obj = $xml_parser->parse($table_xml); + if($table_obj->table) { + if(isset($table_obj->table->column) && !is_array($table_obj->table->column)) + { + $table_obj->table->column = array($table_obj->table->column); + } + + foreach($table_obj->table->column as $k => $v) { + $column_type[$v->attrs->name] = $v->attrs->type; + } + } + } + + return $column_type; + } + + function setTableColumnTypes($tables){ + $query_id = $this->getQueryId(); + if(!isset($this->column_type[$query_id])){ + $table_tags = $tables->getTables(); + $column_type = array(); + foreach($table_tags as $table_tag){ + $tag_column_type = $this->getTableInfo($query_id, $table_tag->getTableName()); + $column_type = array_merge($column_type, $tag_column_type); + } + $this->column_type[$query_id] = $column_type; + } + } + + function toString(){ + // TODO Add tags for update, insert .. + if($this->action == 'select'){ + $columns = new SelectColumnsTag($this->query->columns->column, $this->dbParser); + }else if($this->action == 'insert'){ + $columns = new InsertColumnsTag($this->query->columns->column, $this->dbParser); + }else if($this->action == 'update') { + $columns = new UpdateColumnsTag($this->query->columns->column, $this->dbParser); + }else if($this->action == 'delete') { + $columns = new DeleteColumnsTag($this->query->columns->column, $this->dbParser); + } + + + $tables = new TablesTag($this->query->tables->table, $this->dbParser); + $conditions = new ConditionsTag($this->query->conditions, $this->dbParser); + $groups = new GroupsTag($this->query->groups->group, $this->dbParser); + $navigation = new NavigationTag($this->query->navigation, $this->dbParser); + + $this->setTableColumnTypes($tables); + + $arguments = array(); + $arguments = array_merge($arguments, $columns->getArguments()); + $arguments = array_merge($arguments, $conditions->getArguments()); + $arguments = array_merge($arguments, $navigation->getArguments()); + //foreach($arguments as $argument){ + // var_dump($argument); + // var_dump($this->column_type[$this->getQueryId()][$argument->getColumnName()]); + //} + + $prebuff = ''; + //$prebuff .= $columns->getValidatorString(); + //$prebuff .= $conditions->getValidatorString(); + //$prebuff .= $navigation->getValidatorString(); + foreach($arguments as $argument){ + if($argument->getArgumentName()){ + $prebuff .= $argument->toString(); + $prebuff .= sprintf("$%s_argument->escapeValue('%s');\n" + , $argument->getArgumentName() + , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); + } + } + $prebuff .= "\n"; + + $buff = ''; + + $buff .= '$output->columns = ' . $columns->toString() . ';'.PHP_EOL; + $buff .= '$output->tables = ' . $tables->toString() .';'.PHP_EOL; + $buff .= '$output->conditions = '.$conditions->toString() .';'.PHP_EOL; + $buff .= '$output->groups = ' . $groups->toString() . ';'; + $buff .= '$output->orderby = ' . $navigation->getOrderByString() .';'; + + return "dbParser->getEscapeChar()."');\n" + . sprintf('$output->query_id = "%s";%s', $this->query_id, "\n") + . sprintf('$output->action = "%s";%s', $this->action, "\n") + . $prebuff + . $buff + . 'return $output; ?>'; + + + } +} + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php new file mode 100644 index 000000000..9b88296bb --- /dev/null +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -0,0 +1,113 @@ +name = $name; + $this->value = $value; + $this->isValid = true; + } + + function getValue(){ + return $this->value; + } + + function isValid(){ + return $this->isValid; + } + + function getErrorMessage(){ + return $this->errorMessage; + } + + function ensureDefaultValue($default_value){ + if(!isset($this->value)) + $this->value = $default_value; + } + + function escapeValue($column_type){ + if(in_array($column_type, array('date', 'varchar', 'char'))) + $this->value = '\''.$this->value.'\''; + } + + function checkFilter($filter_type){ + if(isset($this->value)){ + $val = $this->value; + $key = $this->name; + switch($filter_type) { + case 'email' : + case 'email_address' : + if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'homepage' : + if(!preg_match('/^(http|https)+(:\/\/)+[0-9a-z_-]+\.[^ ]+$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_homepage, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'userid' : + case 'user_id' : + if(!preg_match('/^[a-zA-Z]+([_0-9a-zA-Z]+)*$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_userid, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'number' : + case 'numbers' : + if(is_array($val)) $val = join(',', $val); + if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)){ + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_number, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'alpha' : + if(!preg_match('/^[a-z]+$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'alpha_number' : + if(!preg_match('/^[0-9a-z]+$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + } + } + } + + function checkMaxLength($length){ + if($this->value && (strlen($this->value) > $length)){ + $this->isValid = false; + $key = $this->name; + $this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key); + } + } + + function checkMinLength($length){ + if($this->value && (strlen($this->value) > $length)){ + $this->isValid = false; + $key = $this->name; + $this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key); + } + } + + function checkNotNull(){ + if(!isset($this->value)){ + $this->isValid = false; + $key = $this->name; + $this->errorMessage = new Object(-1, $lang->filter->isnull, $lang->{$key} ? $lang->{$key} : $key); + } + } + } + + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php b/classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php new file mode 100644 index 000000000..8c5743dc0 --- /dev/null +++ b/classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php @@ -0,0 +1,26 @@ +argument_name = $tag->attrs->var; + + $name = $tag->attrs->column; + if(strpos($name, '.') === false) $this->column_name = $name; + else { + list($prefix, $name) = explode('.', $name); + $this->column_name = $name; + } + + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php'); + $this->argument_validator = new ConditionQueryArgumentValidator($tag); + } + + function getColumnName(){ + return $this->column_name; + } + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/DefaultValue.class.php b/classes/xml/xmlquery/queryargument/DefaultValue.class.php new file mode 100644 index 000000000..33f5776d3 --- /dev/null +++ b/classes/xml/xmlquery/queryargument/DefaultValue.class.php @@ -0,0 +1,61 @@ +column_name = $column_name; + $this->value = $value; + } + + function isString(){ + $str_pos = strpos($this->value, '('); + if($str_pos===false) return true; + return false; + } + + function toString(){ + if(!isset($this->value)) return; + + $str_pos = strpos($this->value, '('); + if($str_pos===false) return '"'.$this->value.'"'; + + $func_name = substr($this->value, 0, $str_pos); + $args = substr($this->value, $str_pos+1, strlen($value)-1); + + switch($func_name) { + case 'ipaddress' : + $val = '$_SERVER[\'REMOTE_ADDR\']'; + break; + case 'unixtime' : + $val = 'time()'; + break; + case 'curdate' : + $val = 'date("YmdHis")'; + break; + case 'sequence' : + $val = '$this->getNextSequence()'; + break; + case 'plus' : + $args = abs($args); + // TODO Make sure column name is escaped + $val = sprintf('"%s+%d"', $this->column_name, $args); + break; + case 'minus' : + $args = abs($args); + $val = sprintf('"%s-%d"', $this->column_name, $args); + break; + case 'multiply' : + $args = intval($args); + $val = sprintf('"%s*%d"', $this->column_name, $args); + break; + default : + $val = '"' . $this->value . '"'; + } + + return $val; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php new file mode 100644 index 000000000..b18e6d784 --- /dev/null +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -0,0 +1,52 @@ +argument_name = $tag->attrs->var; + + $name = $tag->attrs->name; + if(!$name) $name = $tag->attrs->column; + if(strpos($name, '.') === false) $this->column_name = $name; + else { + list($prefix, $name) = explode('.', $name); + $this->column_name = $name; + } + + if(!$this->argument_name) $this->argument_name = $tag->attrs->name; + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); + $this->argument_validator = new QueryArgumentValidator($tag); + + } + + function getArgumentName(){ + return $this->argument_name; + } + + function getColumnName(){ + return $this->column_name; + } + + function getValidatorString(){ + return $this->argument_validator->toString(); + } + + function toString(){ + $arg = sprintf("\n$%s_argument = new Argument('%s', %s);\n" + , $this->argument_name + , $this->argument_name + , '$args->'.$this->argument_name); + $arg .= $this->argument_validator->toString(); + $arg .= sprintf("if(!$%s_argument->isValid()) return $%s_argument->getErrorMessage();\n" + , $this->argument_name + , $this->argument_name + ); + return $arg; + } + + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php new file mode 100644 index 000000000..4a74b809c --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php @@ -0,0 +1,20 @@ +argument_name) return ''; + if(!isset($this->validator_string)){ + $validator = parent::toString(); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php'); + $v = new EscapeCheck($this->argument_name); + $validator .= $v->toString(); + $this->validator_string = $validator; + } + return $this->validator_string; + } + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php b/classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php new file mode 100644 index 000000000..e6048fc28 --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php @@ -0,0 +1,25 @@ +argument_name = $argument_name; + $this->value = $value; + } + + function toString(){ + if(!isset($this->argument_name)) return ''; + + $value = $this->value->toString(); + + if($this->value->isString()) { + $value = "'".$value."'"; + } + + return 'if(!isset($args->'.$this->argument_name.')) $args->'.$this->argument_name.' = '.$value.';'."\n"; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php b/classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php new file mode 100644 index 000000000..1d37cb953 --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php @@ -0,0 +1,21 @@ +argument_name = $argument_name; + } + + function toString(){ + return sprintf("if(is_string(\$args->%s) && !is_numeric(\$args->%s)) \$args->%s = \$dbParser->escapeString(\$args->%s);\n" + , $this->argument_name + , $this->argument_name + , $this->argument_name + , $this->argument_name); + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php b/classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php new file mode 100644 index 000000000..29a8e9cbf --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php @@ -0,0 +1,16 @@ +argument_name = $argument_name; + $this->filter = $filter; + } + + function toString(){ + return sprintf('if(isset($args->%s)) { unset($_output); $_output = $this->checkFilter("%s",$args->%s,"%s"); if(!$_output->toBool()) return $_output; } %s',$this->argument_name, $this->argument_name,$this->argument_name,$this->filter,"\n"); + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php b/classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php new file mode 100644 index 000000000..3d94cd12e --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php @@ -0,0 +1,22 @@ +argument_name = $argument_name; + $this->value = $value; + } + + function toString(){ + return 'if($args->' + .$this->argument_name + .'&&strlen($args->'.$this->argument_name.')>'.$this->value + .') return new Object(-1, sprintf($lang->filter->outofrange, $lang->' + .$this->argument_name.'?$lang->' + .$this->argument_name.':\''.$this->argument_name.'\'));'."\n"; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php b/classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php new file mode 100644 index 000000000..2717f4487 --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php @@ -0,0 +1,22 @@ +argument_name = $argument_name; + $this->value = $value; + } + + function toString(){ + return 'if($args->' + .$this->argument_name + .'&&strlen($args->'.$this->argument_name.')<'.$this->value + .') return new Object(-1, sprintf($lang->filter->outofrange, $lang->' + .$this->argument_name.'?$lang->' + .$this->argument_name.':\''.$this->argument_name.'\'));'."\n"; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php b/classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php new file mode 100644 index 000000000..4f87b0462 --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php @@ -0,0 +1,18 @@ +argument_name = $argument_name; + $this->value = $value; + } + + function toString(){ + return 'if(!isset($args->'.$this->argument_name.')) return new Object(-1, sprintf($lang->filter->isnull, $lang->' + .$this->argument_name.'?$lang->'.$this->argument_name.':\''.$this->argument_name.'\'));'."\n"; + } + + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php new file mode 100644 index 000000000..cfaeab5de --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php @@ -0,0 +1,62 @@ +argument_name = $tag->attrs->var; + if(!$this->argument_name) $this->argument_name = $tag->attrs->name; + $this->default_value = $tag->attrs->default; + $this->notnull = $tag->attrs->notnull; + $this->filter = $tag->attrs->filter; + $this->min_length = $tag->attrs->min_length; + $this->max_length = $tag->attrs->max_length; + } + + function toString(){ + $validator = ''; + if(isset($this->default_value)){ + $this->default_value = new DefaultValue($this->argument_name, $this->default_value); + //$v = new DefaultCheck($this->argument_name, $this->default_value); + //$validator .= $v->toString(); + $validator .= sprintf("$%s_argument->ensureDefaultValue(%s);\n" + , $this->argument_name + , $this->default_value->toString() + ); + } + if($this->notnull){ + $validator .= sprintf("$%s_argument->checkNotNull();\n" + , $this->argument_name + ); + } + if($this->filter){ + $validator .= sprintf("$%s_argument->checkFilter(%s);\n" + , $this->argument_name + , $this->filter + ); + } + if($this->min_length){ + $validator .= sprintf("$%s_argument->checkMinLength(%s);\n" + , $this->argument_name + , $this->min_length + ); + } + if($this->max_length){ + $validator .= sprintf("$%s_argument->checkMaxLength(%s);\n" + , $this->argument_name + , $this->max_length + ); + } + return $validator; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/Validator.class.php b/classes/xml/xmlquery/queryargument/validator/Validator.class.php new file mode 100644 index 000000000..6fb7426bc --- /dev/null +++ b/classes/xml/xmlquery/queryargument/validator/Validator.class.php @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php new file mode 100644 index 000000000..93de1dde9 --- /dev/null +++ b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php @@ -0,0 +1,52 @@ +dbParser = $dbParser; + $this->pipe = $pipe; + + if(!is_array($conditions)) $conditions = array($conditions); + if(count($conditions))require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); + + foreach($conditions as $condition){ + $this->conditions[] = new ConditionTag($condition, $dbParser); + } + } + + function getConditions(){ + return $this->conditions; + } + + function getConditionGroupString(){ + $conditions_string = 'array('.PHP_EOL; + foreach($this->conditions as $condition) + $conditions_string .= $condition->getConditionString() . PHP_EOL . ','; + $conditions_string = substr($conditions_string, 0, -2);//remove ',' + $conditions_string .= ')'; + + return sprintf("new ConditionGroup(%s%s)", $conditions_string, $this->pipe ? ','.$this->pipe : ''); + } + + function getArguments(){ + $arguments = array(); + foreach($this->conditions as $condition){ + $arguments[] = $condition->getArgument(); + } + return $arguments; + } + + function getValidatorString(){ + $validator = ''; + foreach($this->conditions as $condition){ + $validator .= $condition->getValidatorString(); + } + return $validator; + } + + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php new file mode 100644 index 000000000..a96a9a98d --- /dev/null +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -0,0 +1,49 @@ + tag inside an XML Query file. Base class. + * + */ + + class ConditionTag { + var $dbParser; + var $operation; + var $column_name; + + var $pipe; + var $argument_name; + var $argument; + var $default_column; + + function ConditionTag($condition, $dbParser){ + $this->dbParser = $dbParser; + $this->operation = $condition->attrs->operation; + $this->pipe = $condition->attrs->pipe; + $this->column_name = $this->dbParser->parseColumnName($condition->attrs->column); + // TODO fix this hack - should use default value for query argument + $this->argument_name = $condition->attrs->var; + $this->default_column = $this->dbParser->parseColumnName($condition->attrs->default); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + $this->argument = new QueryArgument($condition); + } + + function getArgument(){ + return $this->argument; + } + + function getConditionString(){ + return sprintf("new Condition('%s',%s,%s%s)" + , $this->column_name + , $this->argument_name ? '$' . $this->argument_name . '_argument->getValue()' : "'" . $this->default_column . "'" + , '"'.$this->operation.'"' + , $this->pipe ? ", '" . $this->pipe . "'" : '' + ); + } + + function getValidatorString(){ + return $this->argument->getValidatorString(); + } + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php new file mode 100644 index 000000000..864634131 --- /dev/null +++ b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php @@ -0,0 +1,51 @@ +dbParser = $dbParser; + $this->condition_groups = array(); + + $xml_condition_list = $xml_conditions->condition; + if($xml_condition_list){ + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php'); + $this->condition_groups[] = new ConditionGroupTag($xml_condition_list, $this->dbParser); + } + + $xml_groups = $xml_conditions->group; + if($xml_groups){ + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php'); + foreach($xml_groups as $group){ + $this->condition_groups[] = new ConditionGroupTag($group->condition, $this->dbParser, $group->pipe); + } + } + } + + function toString(){ + $output_conditions = 'array(' . PHP_EOL; + foreach($this->condition_groups as $condition){ + $output_conditions .= $condition->getConditionGroupString() . PHP_EOL . ','; + } + $output_conditions = substr($output_conditions, 0, -1); + $output_conditions .= ')'; + return $output_conditions; + } + + function getArguments(){ + $arguments = array(); + foreach($this->condition_groups as $condition){ + $arguments = array_merge($arguments, $condition->getArguments()); + } + return $arguments; + } + + function getValidatorString(){ + $validator = ''; + foreach($this->condition_groups as $condition){ + $validator .= $condition->getValidatorString(); + } + return $validator; + } + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/group/GroupsTag.class.php b/classes/xml/xmlquery/tags/group/GroupsTag.class.php new file mode 100644 index 000000000..266e9accb --- /dev/null +++ b/classes/xml/xmlquery/tags/group/GroupsTag.class.php @@ -0,0 +1,36 @@ +dbParser = $dbParser; + + $this->groups = array(); + + if($xml_groups) { + if(!is_array($xml_groups)) $xml_groups = array($xml_groups); + + for($i=0;$iattrs->column); + if(!$column) continue; + $column = $this->dbParser->parseExpression($column); + $this->groups[] = $column; + } + } + } + + function toString(){ + $output = 'array(' . PHP_EOL; + foreach($this->groups as $group){ + $output .= "'" . $group . "' ,"; + } + $output = substr($output, 0, -1); + $output .= ')'; + return $output; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php new file mode 100644 index 000000000..afdfaa17c --- /dev/null +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -0,0 +1,49 @@ +dbParser = $dbParser; + $this->argument_name = $index->attrs->var; + $index->attrs->default = $this->dbParser->parseExpression($index->attrs->default); + $this->default = $index->attrs->default; + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + $this->argument = new QueryArgument($index); + $this->sort_order = $index->attrs->order; + if(!in_array($this->sort_order, array("asc", "desc"))){ + $arg->var = $this->sort_order; + $arg->default = '"asc"'; + $this->sort_order_argument = new QueryArgument($arg); + $this->sort_order = "\$args->".$this->sort_order; + } + //else $this->sort_order = '"'.$this->sort_order.'"'; + } + + function toString(){ + return sprintf("new OrderByColumn(\$%s_argument->getValue(), %s)", $this->argument_name, $this->sort_order); + } + + function getArguments(){ + $arguments = array(); + $arguments[] = $this->argument; + if($this->sort_order_argument) + $arguments[] = $this->sort_order_argument; + return $arguments; + } + + function getValidatorString(){ + $validator = $this->argument->getValidatorString(); + if($this->sort_order_argument) + $validator .= $this->sort_order_argument->getValidatorString(); + return $validator; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php new file mode 100644 index 000000000..98824592b --- /dev/null +++ b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php @@ -0,0 +1,60 @@ +order = array(); + if($xml_navigation) { + $order = $xml_navigation->index; + if($order) { + if(!is_array($order)) $order = array($order); + foreach($order as $order_info) { + $this->order[] = new IndexTag($order_info, $dbParser); + } + } + + $list_count = $xml_navigation->list_count->attrs; + $this->list_count = $list_count; + + $page_count = $xml_navigation->page_count->attrs; + $this->page_count = $page_count; + + $page = $xml_navigation->page->attrs; + $this->page = $page ; + } + } + + function getOrderByString(){ + $output = 'array(' . PHP_EOL; + foreach($this->order as $order){ + $output .= $order->toString() . PHP_EOL . ','; + } + $output = substr($output, 0, -1); + $output .= ')'; + return $output; + } + + function getArguments(){ + $arguments = array(); + foreach($this->order as $order){ + $arguments = array_merge($order->getArguments(), $arguments); + } + return $arguments; + } + + function getValidatorString(){ + $validator = ''; + foreach ($this->order as $order){ + $validator .= $order->getValidatorString(); + } + return $validator; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/table/TableTag.class.php b/classes/xml/xmlquery/tags/table/TableTag.class.php new file mode 100644 index 000000000..4797df04c --- /dev/null +++ b/classes/xml/xmlquery/tags/table/TableTag.class.php @@ -0,0 +1,60 @@ + tag inside an XML Query file + * + */ + + class TableTag { + var $unescaped_name; + var $name; + var $alias; + var $join_type; + var $conditions; + + var $dbParser; + + function TableTag($table, $dbParser){ + $this->dbParser = $dbParser; + + $this->unescaped_name = $table->attrs->name; + $this->name = $this->dbParser->parseTableName($table->attrs->name); + $this->alias = $table->attrs->alias; + //if(!$this->alias) $this->alias = $alias; + + $this->join_type = $table->attrs->type; + $this->conditions = $table->conditions; + } + + function isJoinTable(){ + if(in_array($this->join_type,array('left join','left outer join','right join','right outer join')) + && count($this->conditions)) return true; + return false; + } + + function getTableAlias(){ + return $this->alias; + } + + function getTableName(){ + return $this->unescaped_name; + } + + function getTableString(){ + if($this->isJoinTable()){ + $conditionsTag = new ConditionsTag($this->conditions, $this->dbParser); + return sprintf('new JoinTable(\'%s\', \'%s\', "%s", %s)' + , $this->dbParser->escape($this->name) + , $this->dbParser->escape($this->alias) + , $this->join_type, $conditionsTag->toString()); + } + return sprintf('new Table(\'%s\'%s)' + , $this->dbParser->escape($this->name) + , $this->alias ? ', \'' . $this->dbParser->escape($this->alias) .'\'' : ''); + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/table/TablesTag.class.php b/classes/xml/xmlquery/tags/table/TablesTag.class.php new file mode 100644 index 000000000..862cfd9ae --- /dev/null +++ b/classes/xml/xmlquery/tags/table/TablesTag.class.php @@ -0,0 +1,33 @@ +dbParser = $dbParser; + $this->tables = array(); + if(!is_array($xml_tables)) $xml_tables = array($xml_tables); + + if(count($xml_tables)) require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); + + foreach($xml_tables as $table){ + $this->tables[] = new TableTag($table, $this->dbParser); + } + } + + function getTables(){ + return $this->tables; + } + + function toString(){ + $output_tables = 'array(' . PHP_EOL; + foreach($this->tables as $table){ + $output_tables .= $table->getTableString() . PHP_EOL . ','; + } + $output_tables = substr($output_tables, 0, -1); + $output_tables .= ')'; + return $output_tables; + } + } +?> \ No newline at end of file From 2a35558b4e429210fc366ff78938bc5249b1aeee Mon Sep 17 00:00:00 2001 From: mosmartin Date: Thu, 19 May 2011 13:17:46 +0000 Subject: [PATCH 03/82] Update new xml query classes with xe 1.5 with improved query argument support and update and delete queries git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8379 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../xmlquery/tags/column/ColumnTag.class.php | 21 +++++++ .../tags/column/DeleteColumnTag.class.php | 43 +++++++++++++ .../tags/column/DeleteColumnsTag.class.php | 58 ++++++++++++++++++ .../tags/column/InsertColumnTag.class.php | 45 ++++++++++++++ .../tags/column/InsertColumnsTag.class.php | 58 ++++++++++++++++++ .../tags/column/SelectColumnTag.class.php | 31 ++++++++++ .../tags/column/SelectColumnsTag.class.php | 45 ++++++++++++++ .../tags/column/UpdateColumnTag.class.php | 46 ++++++++++++++ .../tags/column/UpdateColumnsTag.class.php | 61 +++++++++++++++++++ 9 files changed, 408 insertions(+) create mode 100644 classes/xml/xmlquery/tags/column/ColumnTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/InsertColumnTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/SelectColumnTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php create mode 100644 classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php diff --git a/classes/xml/xmlquery/tags/column/ColumnTag.class.php b/classes/xml/xmlquery/tags/column/ColumnTag.class.php new file mode 100644 index 000000000..7cf066013 --- /dev/null +++ b/classes/xml/xmlquery/tags/column/ColumnTag.class.php @@ -0,0 +1,21 @@ + tag inside an XML Query file + * + * Since the tag supports different attributes depending on + * the type of query (select, update, insert, delete) this is only + * the base class for the classes that will model each type tag. + * + **/ + + class ColumnTag { + var $name; + var $dbParser; + + function ColumnTag($name, $dbParser){ + $this->dbParser = $dbParser; + $this->name = $name; + } + } \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php b/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php new file mode 100644 index 000000000..0c2b1b6db --- /dev/null +++ b/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php @@ -0,0 +1,43 @@ + tag inside an XML Query file whose action is 'delete' + * + **/ + + + class DeleteColumnTag extends ColumnTag { + var $argument; + + function DeleteColumnTag($column, $dbParser) { + parent::ColumnTag($column->attrs->name, $dbParser); + $this->name = $this->dbParser->parseColumnName($this->name); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + $this->argument = new QueryArgument($column); + } + function toString(){ + $output_columns = 'array(' . PHP_EOL; + foreach($this->argument as $argument){ + $output_columns .= $argument->getExpressionString() . PHP_EOL . ','; + } + $output_columns = substr($output_columns, 0, -1); + $output_columns .= ')'; + return $output_columns; + } + function getExpressionString(){ + return sprintf('new DeleteExpression(\'%s\', $args->%s)' + , $this->name + , $this->argument->argument_name); + } + + function getArgument(){ + return $this->argument; + } + + function getValidatorString(){ + return $this->argument->getValidatorString(); + } + + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php b/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php new file mode 100644 index 000000000..b242d7ca0 --- /dev/null +++ b/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php @@ -0,0 +1,58 @@ + tag inside an XML Query file whose action is 'delete' + * + **/ + + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/ColumnTag.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php'); + + class DeleteColumnsTag{ + var $dbParser; + var $columns; + + function DeleteColumnsTag($xml_columns, $dbParser) { + $this->dbParser = $dbParser; + + $this->columns = array(); + + if(!$xml_columns) + return; + + if(!is_array($xml_columns)) $xml_columns = array($xml_columns); + + foreach($xml_columns as $column){ + $this->columns[] = new DeleteColumnTag($column, $this->dbParser); + } + } + function toString(){ + $output_columns = 'array(' . PHP_EOL; + foreach($this->columns as $column){ + $output_columns .= $column->getExpressionString() . PHP_EOL . ','; + } + $output_columns = substr($output_columns, 0, -1); + $output_columns .= ')'; + return $output_columns; + } + + function getArguments(){ + $arguments = array(); + foreach($this->columns as $column){ + $arguments[] = $column->getArgument(); + } + return $arguments; + } + + function getValidatorString(){ + $validator = ''; + foreach($this->columns as $column){ + $validator .= $column->getValidatorString(); + } + return $validator; + } + + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php new file mode 100644 index 000000000..9dfba9247 --- /dev/null +++ b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php @@ -0,0 +1,45 @@ + tag inside an XML Query file whose action is 'insert' + * + **/ + + + class InsertColumnTag extends ColumnTag { + var $argument; + + function InsertColumnTag($column, $dbParser) { + parent::ColumnTag($column->attrs->name, $dbParser); + $this->name = $this->dbParser->parseColumnName($this->name); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + $this->argument = new QueryArgument($column); + } + + function toString(){ + $output_columns = 'array(' . PHP_EOL; + foreach($this->argument as $argument){ + $output_columns .= $argument->getExpressionString() . PHP_EOL . ','; + } + $output_columns = substr($output_columns, 0, -1); + $output_columns .= ')'; + return $output_columns; + } + + function getExpressionString(){ + return sprintf('new InsertExpression(\'%s\', $%s_argument->getValue())' + , $this->name + , $this->argument->argument_name); + } + + function getArgument(){ + return $this->argument; + } + + function getValidatorString(){ + return $this->argument->getValidatorString(); + } + + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php new file mode 100644 index 000000000..086cbba2d --- /dev/null +++ b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php @@ -0,0 +1,58 @@ + tag inside an XML Query file whose action is 'insert' + * + **/ + + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/ColumnTag.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnTag.class.php'); + + class InsertColumnsTag{ + var $dbParser; + var $columns; + + function InsertColumnsTag($xml_columns, $dbParser) { + $this->dbParser = $dbParser; + + $this->columns = array(); + + if(!$xml_columns) + return; + + if(!is_array($xml_columns)) $xml_columns = array($xml_columns); + + foreach($xml_columns as $column){ + $this->columns[] = new InsertColumnTag($column, $this->dbParser); + } + } + function toString(){ + $output_columns = 'array(' . PHP_EOL; + foreach($this->columns as $column){ + $output_columns .= $column->getExpressionString() . PHP_EOL . ','; + } + $output_columns = substr($output_columns, 0, -1); + $output_columns .= ')'; + return $output_columns; + } + + function getArguments(){ + $arguments = array(); + foreach($this->columns as $column){ + $arguments[] = $column->getArgument(); + } + return $arguments; + } + + function getValidatorString(){ + $validator = ''; + foreach($this->columns as $column){ + $validator .= $column->getValidatorString(); + } + return $validator; + } + + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/SelectColumnTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnTag.class.php new file mode 100644 index 000000000..ca7a40eff --- /dev/null +++ b/classes/xml/xmlquery/tags/column/SelectColumnTag.class.php @@ -0,0 +1,31 @@ + tag inside an XML Query file whose action is 'select' + * + **/ + + class SelectColumnTag extends ColumnTag{ + var $alias; + var $click_count; + + function SelectColumnTag($column, $dbParser){ + parent::ColumnTag($column->attrs->name, $dbParser); + if(!$this->name) $this->name = "*"; + if($this->name != "*") + $this->name = $this->dbParser->parseExpression($this->name); + + $this->alias = $column->attrs->alias; + $this->click_count = $column->attrs->click_count; + } + + function getExpressionString(){ + if($this->name == '*') return "new StarExpression()"; + if($this->click_count) + return sprintf('new ClickCountExpression(%s, %s, $args->%s)', $this->name, $this->alias,$this->click_count); + return sprintf('new SelectExpression(\'%s\'%s)', $this->name, $this->alias ? ', \''.$this->dbParser->escape($this->alias) .'\'': ''); + } + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php new file mode 100644 index 000000000..15102f130 --- /dev/null +++ b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php @@ -0,0 +1,45 @@ +dbParser = $dbParser; + + $this->columns = array(); + + if(!$xml_columns) { + $this->columns[] = new SelectColumnTag("*", $this->dbParser); + return; + } + + if(!is_array($xml_columns)) $xml_columns = array($xml_columns); + + foreach($xml_columns as $column){ + $this->columns[] = new SelectColumnTag($column, $this->dbParser); + } + } + + function toString(){ + $output_columns = 'array(' . PHP_EOL; + foreach($this->columns as $column){ + $output_columns .= $column->getExpressionString() . PHP_EOL . ','; + } + $output_columns = substr($output_columns, 0, -1); + $output_columns .= ')'; + return $output_columns; + } + + function getArguments(){ + return array(); + } + + function getValidatorString(){ + return ''; + } + } +?> diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php new file mode 100644 index 000000000..d41905e59 --- /dev/null +++ b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php @@ -0,0 +1,46 @@ + tag inside an XML Query file whose action is 'update' + * + **/ + + + + class UpdateColumnTag extends ColumnTag { + var $argument; + + function UpdateColumnTag($column, $dbParser) { + parent::ColumnTag($column->attrs->name, $dbParser); + $this->name = $this->dbParser->parseColumnName($this->name); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + $this->argument = new QueryArgument($column); + } + + function toString(){ + $output_columns = 'array(' . PHP_EOL; + foreach($this->argument as $argument){ + $output_columns .= $argument->getExpressionString() . PHP_EOL . ','; + } + $output_columns = substr($output_columns, 0, -1); + $output_columns .= ')'; + return $output_columns; + } + function getExpressionString(){ + return sprintf('new UpdateExpression(\'%s\', $%s_argument->getValue())' + , $this->name + , $this->argument->argument_name); + } + + function getArgument(){ + return $this->argument; + } + + function getValidatorString(){ + return $this->argument->getValidatorString(); + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php new file mode 100644 index 000000000..2f1feba0f --- /dev/null +++ b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php @@ -0,0 +1,61 @@ + tag inside an XML Query file whose action is 'update' + * + **/ + + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/ColumnTag.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php'); + + class UpdateColumnsTag{ + var $dbParser; + var $columns; + + function UpdateColumnsTag($xml_columns, $dbParser) { + $this->dbParser = $dbParser; + + $this->columns = array(); + + if(!$xml_columns) { + $this->columns[] = new UpdateColumnTag("*", $this->dbParser); + return; + } + + if(!is_array($xml_columns)) $xml_columns = array($xml_columns); + + foreach($xml_columns as $column){ + $this->columns[] = new UpdateColumnTag($column, $this->dbParser); + } + } + + function toString(){ + $output_columns = 'array(' . PHP_EOL; + foreach($this->columns as $column){ + $output_columns .= $column->getExpressionString() . PHP_EOL . ','; + } + $output_columns = substr($output_columns, 0, -1); + $output_columns .= ')'; + return $output_columns; + } + + function getArguments(){ + $arguments = array(); + foreach($this->columns as $column){ + $arguments[] = $column->getArgument(); + } + return $arguments; + } + + function getValidatorString(){ + $validator = ''; + foreach($this->columns as $column){ + $validator .= $column->getValidatorString(); + } + return $validator; + } + } + +?> \ No newline at end of file From 7fe8000d0f8b3826a65936315272fe63ee0524cb Mon Sep 17 00:00:00 2001 From: mosmartin Date: Thu, 19 May 2011 13:39:38 +0000 Subject: [PATCH 04/82] Fix for XmlQueryParser. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8380 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/XmlQueryParser.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 6c7192bf1..fde5ade4d 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -12,7 +12,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/QueryParser.class.php'); - class NewXmlQueryParser extends XmlParser { + class XmlQueryParser extends XmlParser { var $dbParser; function parse($query_id, $xml_file, $cache_file) { @@ -25,7 +25,7 @@ //$oDB = &DB::getParser(); //$dbParser = $oDB->getParser(); - $dbParser = getDBParser(); + $dbParser = $this->getDBParser(); $parser = new QueryParser($xml_obj->query, $dbParser); FileHandler::writeFile($cache_file, $parser->toString()); From 6e11747960035fd7b7b3f1824452d0fe4ff4de64 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Thu, 19 May 2011 14:31:05 +0000 Subject: [PATCH 05/82] add support for insert select update and delete queries in CUBRID class git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8381 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 229 ++++++++++++---------------------- 1 file changed, 82 insertions(+), 147 deletions(-) diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 171bf6a47..10b96ca97 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -654,156 +654,106 @@ **/ function _executeInsertAct ($output) { - // tables - foreach ($output->tables as $val) { - $table_list[] = '"'.$this->prefix.$val.'"'; - } - - // columns - foreach ($output->columns as $key => $val) { - $name = $val['name']; - $value = $val['value']; - //if ($this->getColumnType ($output->column_type, $name) != 'number') - if ($output->column_type[$name] != 'number') { - if (!is_null($value)) { - $value = "'" . $this->addQuotes($value) ."'"; - } - else { - if ($val['notnull']=='notnull') { - $value = "''"; - } - else { - //$value = 'null'; - $value = "''"; - } - } + $query = ''; + + $tableName = $output->tables[0]->getName(); + + $columnsList = ''; + $valuesList = ''; + foreach($output->columns as $column){ + if($column->show()){ + $columnsList .= $column->getColumnName() . ', '; + $valuesList .= $column->getValue() . ', '; } - else $this->_filterNumber(&$value); - - $column_list[] = '"'.$name.'"'; - $value_list[] = $value; } - - $query = sprintf ("insert into %s (%s) values (%s);", implode(',', $table_list), implode(',', $column_list), implode(',', $value_list)); - - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $columnsList = substr($columnsList, 0, -2); + $valuesList = substr($valuesList, 0, -2); + + // TODO Make sure column values are escaped. Preferably directly from the cache file and not in here + $query = "INSERT INTO $tableName ($columnsList) VALUES ($valuesList)"; + + return $query; + /*$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result = $this->_query ($query); if ($result && !$this->transaction_started) { @cubrid_commit ($this->fd); } return $result; - } + */ + } - /** - * @brief handles updateAct - **/ function _executeUpdateAct ($output) { - // tables - foreach ($output->tables as $key => $val) { - $table_list[] = '"'.$this->prefix.$val.'" as "'.$key.'"'; - } - - $check_click_count = true; - - // columns - foreach ($output->columns as $key => $val) { - if (!isset ($val['value'])) continue; - $name = $val['name']; - $value = $val['value']; - - if (substr ($value, -2) != '+1' || $output->column_type[$name] != 'number') { - $check_click_count = false; - } - - for ($i = 0; $i < $key; $i++) { - // not allows to define the same property repeatedly in a single query in CUBRID - if ($output->columns[$i]['name'] == $name) break; - } - if ($i < $key) continue; // ignore the rest of properties if duplicated property found - - if (strpos ($name, '.') !== false && strpos ($value, '.') !== false) { - $column_list[] = $name.' = '.$value; - } - else { - if ($output->column_type[$name] != 'number') { - $check_column = false; - $value = "'".$this->addQuotes ($value)."'"; - } - else $this->_filterNumber(&$value); - - $column_list[] = sprintf ("\"%s\" = %s", $name, $value); + $query = ''; + + $tableName = $output->tables[0]->getName(); + + $columnsList = ''; + $valuesList = ''; + foreach($output->columns as $column){ + if($column->show()){ + $columnsList .= $column->getColumnName() . ', '; + $valuesList .= $column->getValue() . ', '; } } - - // conditional clause - $condition = $this->getCondition ($output); - - $check_click_count_condition = false; - if ($check_click_count) { - foreach ($output->conditions as $val) { - if ($val['pipe'] == 'or') { - $check_click_count_condition = false; - break; - } - - foreach ($val['condition'] as $v) { - if ($v['operation'] == 'equal') { - $check_click_count_condition = true; - } - else { - if ($v['operation'] == 'in' && !strpos ($v['value'], ',')) { - $check_click_count_condition = true; - } - else { - $check_click_count_condition = false; - } - } - - if ($v['pipe'] == 'or') { - $check_click_count_condition = false; - break; - } - } - } - } - - if ($check_click_count&& $check_click_count_condition && count ($output->tables) == 1 && count ($output->conditions) > 0 && count ($output->groups) == 0 && count ($output->order) == 0) { - foreach ($output->columns as $v) { - $incr_columns[] = 'incr("'.$v['name'].'")'; - } - - $query = sprintf ('select %s from %s %s', join (',', $incr_columns), implode(',', $table_list), $condition); - } - else { - $query = sprintf ("update %s set %s %s", implode (',', $table_list), implode (',', $column_list), $condition); - } - + $columnsList = substr($columnsList, 0, -2); + $valuesList = substr($valuesList, 0, -2); + + // TODO Make sure column values are escaped. Preferably directly from the cache file and not in here + $query = "UPDATE INTO $tableName ($columnsList) VALUES ($valuesList)"; + + return $query; + /*$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result = $this->_query ($query); - if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); + if ($result && !$this->transaction_started) { + @cubrid_commit ($this->fd); + } return $result; - } + */ + } /** * @brief handles deleteAct **/ - function _executeDeleteAct ($output) - { - // tables - foreach ($output->tables as $val) { - $table_list[] = '"'.$this->prefix.$val.'"'; + function _executeDeleteAct($output){ + $query = ''; + + $select = 'DELETE '; + + $from = 'FROM '; + $simple_table_count = 0; + foreach($output->tables as $table){ + if($simple_table_count > 0) $from .= ', '; + $from .= $table->toString() . ' '; + if(!$table->isJoinTable()) $simple_table_count++; } - - // Conditional clauses - $condition = $this->getCondition ($output); - - $query = sprintf ("delete from %s %s", implode (',',$table_list), $condition); - $result = $this->_query ($query); - if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); - - return $result; + + $where = ''; + if(count($output->conditions) > 0){ + $where = 'WHERE '; + foreach($output->conditions as $conditionGroup){ + $where .= $conditionGroup->toString(); + } + } + /* + $groupBy = ''; + if($output->groups) if($output->groups[0] !== "") + $groupBy = 'GROUP BY ' . implode(', ', $output->groups); + + $orderBy = ''; + if(count($output->orderby) > 0){ + $orderBy = 'ORDER BY '; + foreach($output->orderby as $order){ + $orderBy .= $order->toString() .', '; + } + $orderBy = substr($orderBy, 0, -2); + } + */ + + $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; + return $query; } /** @@ -825,14 +775,9 @@ $from = 'FROM '; $simple_table_count = 0; foreach($output->tables as $table){ - /*if($simple_table_count > 0) $from .= ', '; - + if($simple_table_count > 0) $from .= ', '; $from .= $table->toString() . ' '; if(!$table->isJoinTable()) $simple_table_count++; - */ - if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; - else $from .= ', '.$table->toString() . ' '; - $simple_table_count++; } $where = ''; @@ -858,18 +803,8 @@ $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; - - //$query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, //$groupby_query.$orderby_query); - //$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); - if ($this->isError ()) return; - $data = $this->_fetch ($result); - - $buff = new Object (); - $buff->data = $data; - - return $buff; - } + return $query; + } /*function _executeSelectAct ($output) { // tables From 9a2c0a8ff9398ab424923b23511aa252fd92ed2d Mon Sep 17 00:00:00 2001 From: mosmartin Date: Thu, 19 May 2011 14:46:11 +0000 Subject: [PATCH 06/82] fixed an issue when Argument class is required git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8382 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 1 + 1 file changed, 1 insertion(+) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 2d1f9dd27..f49e8710b 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -315,6 +315,7 @@ if($source_args) $args = @clone($source_args); require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/SelectExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/InsertExpression.class.php'); From 0f61e5d499deb6191f0a5a56be4c0192d9da07d7 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Thu, 19 May 2011 15:31:47 +0000 Subject: [PATCH 07/82] Included some missing classes. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8383 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 5 +- classes/db/DBCubrid.class.php | 85 ++++++++++--------- classes/xml/XmlQueryParser.class.php | 2 +- .../queryargument/DefaultValue.class.php | 1 + .../QueryArgumentValidator.class.php | 2 - .../tags/navigation/IndexTag.class.php | 4 +- config/config.inc.php | 2 +- modules/member/queries/getAutologin.xml | 2 +- 8 files changed, 55 insertions(+), 48 deletions(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index f49e8710b..71dc76e34 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -319,13 +319,16 @@ require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/SelectExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/InsertExpression.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/expression/UpdateExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/table/Table.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/table/JoinTable.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/condition/ConditionGroup.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/condition/Condition.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/StarExpression.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/order/OrderByColumn.class.php'); - $output = @include($cache_file); + + $output = include($cache_file); if( (is_a($output, 'Object') || is_subclass_of($output, 'Object')) && !$output->toBool()) return $output; $output->_tables = ($output->_tables && is_array($output->_tables)) ? $output->_tables : array(); diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 10b96ca97..1df9d207e 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -669,20 +669,20 @@ $columnsList = substr($columnsList, 0, -2); $valuesList = substr($valuesList, 0, -2); - // TODO Make sure column values are escaped. Preferably directly from the cache file and not in here - $query = "INSERT INTO $tableName ($columnsList) VALUES ($valuesList)"; - - return $query; - /*$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $query = "INSERT INTO $tableName \n ($columnsList) \n VALUES ($valuesList)"; + + $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result = $this->_query ($query); if ($result && !$this->transaction_started) { @cubrid_commit ($this->fd); } return $result; - */ - } + } + /** + * @brief handles updateAct + **/ function _executeUpdateAct ($output) { $query = ''; @@ -690,34 +690,35 @@ $tableName = $output->tables[0]->getName(); $columnsList = ''; - $valuesList = ''; foreach($output->columns as $column){ if($column->show()){ - $columnsList .= $column->getColumnName() . ', '; - $valuesList .= $column->getValue() . ', '; + $columnsList .= $column->getExpression() . ', '; } } $columnsList = substr($columnsList, 0, -2); - $valuesList = substr($valuesList, 0, -2); + + $where = ''; + if(count($output->conditions) > 0){ + $where = 'WHERE '; + foreach($output->conditions as $conditionGroup){ + $where .= $conditionGroup->toString(); + } + } - // TODO Make sure column values are escaped. Preferably directly from the cache file and not in here - $query = "UPDATE INTO $tableName ($columnsList) VALUES ($valuesList)"; - - return $query; - /*$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $query = "UPDATE $tableName SET $columnsList ".$where; + + $result = $this->_query ($query); - if ($result && !$this->transaction_started) { - @cubrid_commit ($this->fd); - } + if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); return $result; - */ - } + } /** * @brief handles deleteAct **/ - function _executeDeleteAct($output){ + function _executeDeleteAct ($output) + { $query = ''; $select = 'DELETE '; @@ -737,23 +738,12 @@ $where .= $conditionGroup->toString(); } } - /* - $groupBy = ''; - if($output->groups) if($output->groups[0] !== "") - $groupBy = 'GROUP BY ' . implode(', ', $output->groups); - - $orderBy = ''; - if(count($output->orderby) > 0){ - $orderBy = 'ORDER BY '; - foreach($output->orderby as $order){ - $orderBy .= $order->toString() .', '; - } - $orderBy = substr($orderBy, 0, -2); - } - */ $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; - return $query; + $result = $this->_query ($query); + if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); + + return $result; } /** @@ -775,9 +765,14 @@ $from = 'FROM '; $simple_table_count = 0; foreach($output->tables as $table){ - if($simple_table_count > 0) $from .= ', '; + /*if($simple_table_count > 0) $from .= ', '; + $from .= $table->toString() . ' '; if(!$table->isJoinTable()) $simple_table_count++; + */ + if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; + else $from .= ', '.$table->toString() . ' '; + $simple_table_count++; } $where = ''; @@ -803,8 +798,18 @@ $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; - return $query; - } + + //$query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, //$groupby_query.$orderby_query); + //$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result = $this->_query ($query); + if ($this->isError ()) return; + $data = $this->_fetch ($result); + + $buff = new Object (); + $buff->data = $data; + + return $buff; + } /*function _executeSelectAct ($output) { // tables diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index fde5ade4d..8e1595056 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -36,7 +36,7 @@ if(!$this->dbParser){ //$oDB = &DB::getParser(); //$dbParser = $oDB->getParser(); - $this->dbParser = new DBParser('`'); + $this->dbParser = new DBParser('"'); } return $this->dbParser; } diff --git a/classes/xml/xmlquery/queryargument/DefaultValue.class.php b/classes/xml/xmlquery/queryargument/DefaultValue.class.php index 33f5776d3..060261b65 100644 --- a/classes/xml/xmlquery/queryargument/DefaultValue.class.php +++ b/classes/xml/xmlquery/queryargument/DefaultValue.class.php @@ -19,6 +19,7 @@ if(!isset($this->value)) return; $str_pos = strpos($this->value, '('); + // TODO Replace this with parseExpression if($str_pos===false) return '"'.$this->value.'"'; $func_name = substr($this->value, 0, $str_pos); diff --git a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php index cfaeab5de..371dd33c3 100644 --- a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php +++ b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php @@ -25,8 +25,6 @@ $validator = ''; if(isset($this->default_value)){ $this->default_value = new DefaultValue($this->argument_name, $this->default_value); - //$v = new DefaultCheck($this->argument_name, $this->default_value); - //$validator .= $v->toString(); $validator .= sprintf("$%s_argument->ensureDefaultValue(%s);\n" , $this->argument_name , $this->default_value->toString() diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index afdfaa17c..cbe726b99 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -12,7 +12,7 @@ function IndexTag($index, $dbParser){ $this->dbParser = $dbParser; $this->argument_name = $index->attrs->var; - $index->attrs->default = $this->dbParser->parseExpression($index->attrs->default); + //$index->attrs->default = $this->dbParser->parseExpression($index->attrs->default); $this->default = $index->attrs->default; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($index); @@ -23,7 +23,7 @@ $this->sort_order_argument = new QueryArgument($arg); $this->sort_order = "\$args->".$this->sort_order; } - //else $this->sort_order = '"'.$this->sort_order.'"'; + else $this->sort_order = '"'.$this->sort_order.'"'; } function toString(){ diff --git a/config/config.inc.php b/config/config.inc.php index 91ebb2fa1..24636abac 100644 --- a/config/config.inc.php +++ b/config/config.inc.php @@ -97,7 +97,7 @@ * 1: Enabled * Only particular servers may have a problem in IE browser when sending a compression **/ - if(!defined('__OB_GZHANDLER_ENABLE__')) define('__OB_GZHANDLER_ENABLE__', 1); + if(!defined('__OB_GZHANDLER_ENABLE__')) define('__OB_GZHANDLER_ENABLE__', 0); /** * @brief decide to use/not use the php unit test (Path/tests/index.php) diff --git a/modules/member/queries/getAutologin.xml b/modules/member/queries/getAutologin.xml index eef12f490..73065636b 100644 --- a/modules/member/queries/getAutologin.xml +++ b/modules/member/queries/getAutologin.xml @@ -10,6 +10,6 @@ - + From 520300fad11f48dea7ece6120ccd8a65ab9cc163 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Fri, 20 May 2011 09:25:59 +0000 Subject: [PATCH 08/82] Updated WHERE clause to ignore expressions when the argument value is not set. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8386 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBMysql.class.php | 2 +- .../queryparts/condition/Condition.class.php | 21 +++++++++++-------- .../condition/ConditionGroup.class.php | 3 ++- classes/xml/xmlquery/QueryParser.class.php | 1 - .../xml/xmlquery/argument/Argument.class.php | 2 ++ .../tags/condition/ConditionsTag.class.php | 1 + 6 files changed, 18 insertions(+), 12 deletions(-) diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index 59501f161..6ee269ba5 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -666,7 +666,7 @@ /** * @brief Paging is handled if navigation information exists in the query xml * - * It is quite convenient although its structure is not good at all .. -_-; + * It is quite convenient although its structure is not good at all .. -_-; **/ function _getNavigationData($table_list, $columns, $left_join, $index_hint, $condition, $output) { require_once(_XE_PATH_.'classes/page/PageHandler.class.php'); diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index ea8657b71..4db069e72 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -17,8 +17,8 @@ return $this->pipe . ' ' . $this->getConditionPart($this->column_name, $this->value, $this->operation); } - function getConditionPart($name, $value, $operation) { - switch($operation) { + function show(){ + switch($this->operation) { case 'equal' : case 'more' : case 'excess' : @@ -31,16 +31,19 @@ case 'notin' : case 'notequal' : // if variable is not set or is not string or number, return - if(!isset($value)) return; - if($value === '') return; - if(!in_array(gettype($value), array('string', 'integer'))) return; + if(!isset($this->value)) return false; + if($this->value === '') return false; + if(!in_array(gettype($this->value), array('string', 'integer'))) return false; break; case 'between' : - if(!is_array($value)) return; - if(count($value)!=2) return; - - } + if(!is_array($this->value)) return false; + if(count($this->value)!=2) return false; + } + return true; + } + + function getConditionPart($name, $value, $operation) { switch($operation) { case 'equal' : return $name.' = '.$value; diff --git a/classes/db/queryparts/condition/ConditionGroup.class.php b/classes/db/queryparts/condition/ConditionGroup.class.php index ecf5870f1..bc3a1b888 100644 --- a/classes/db/queryparts/condition/ConditionGroup.class.php +++ b/classes/db/queryparts/condition/ConditionGroup.class.php @@ -15,7 +15,8 @@ else $group = ''; foreach($this->conditions as $condition){ - $group .= $condition->toString() . ' '; + if($condition->show()) + $group .= $condition->toString() . ' '; } if($this->pipe !== "") diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 00f95d5b8..852aeced1 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -95,7 +95,6 @@ class QueryParser { } function toString(){ - // TODO Add tags for update, insert .. if($this->action == 'select'){ $columns = new SelectColumnsTag($this->query->columns->column, $this->dbParser); }else if($this->action == 'insert'){ diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 9b88296bb..f24dd4a20 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -31,6 +31,8 @@ } function escapeValue($column_type){ + if(!isset($this->value)) return; + if($column_type === '') $column_type = 'varchar'; if(in_array($column_type, array('date', 'varchar', 'char'))) $this->value = '\''.$this->value.'\''; } diff --git a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php index 864634131..ef174bc2e 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php @@ -15,6 +15,7 @@ $xml_groups = $xml_conditions->group; if($xml_groups){ + if(!is_array($xml_groups)) $xml_groups = array($xml_groups); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php'); foreach($xml_groups as $group){ $this->condition_groups[] = new ConditionGroupTag($group->condition, $this->dbParser, $group->pipe); From d3067703a434970b44af1199a92026ee6793ec28 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Fri, 20 May 2011 12:24:50 +0000 Subject: [PATCH 09/82] Fixed join condidition bug: if the user specifies the "pipe" attribute of a condition in a join cause, it should be ignored (otherwise the sql string is like INNER JOIN ... ON AND a = b). Fixed order by bug. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8387 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 2 +- classes/xml/xmlquery/QueryParser.class.php | 1 + classes/xml/xmlquery/argument/Argument.class.php | 3 ++- .../xml/xmlquery/queryargument/DefaultValue.class.php | 8 +++++--- .../xmlquery/tags/condition/ConditionTag.class.php | 4 ++++ .../tags/condition/JoinConditionsTag.class.php | 11 +++++++++++ .../xml/xmlquery/tags/navigation/IndexTag.class.php | 2 +- classes/xml/xmlquery/tags/table/TableTag.class.php | 2 +- modules/module/queries/getDefaultModules.xml | 6 +++--- modules/module/queries/getSiteModules.xml | 4 ++-- 10 files changed, 31 insertions(+), 12 deletions(-) create mode 100644 classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 1df9d207e..4193f8270 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -199,7 +199,7 @@ if (cubrid_error_code ()) { $code = cubrid_error_code (); $msg = cubrid_error_msg (); - + $this->setError ($code, $msg); } diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 852aeced1..c7a50717a 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -7,6 +7,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/UpdateColumnsTag.class. require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TablesTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionsTag.class.php'); +require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/group/GroupsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/navigation/NavigationTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/navigation/IndexTag.class.php'); diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index f24dd4a20..23cb46539 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -32,7 +32,8 @@ function escapeValue($column_type){ if(!isset($this->value)) return; - if($column_type === '') $column_type = 'varchar'; + if($column_type === '') return; + //if($column_type === '') $column_type = 'varchar'; if(in_array($column_type, array('date', 'varchar', 'char'))) $this->value = '\''.$this->value.'\''; } diff --git a/classes/xml/xmlquery/queryargument/DefaultValue.class.php b/classes/xml/xmlquery/queryargument/DefaultValue.class.php index 060261b65..4cac606fe 100644 --- a/classes/xml/xmlquery/queryargument/DefaultValue.class.php +++ b/classes/xml/xmlquery/queryargument/DefaultValue.class.php @@ -19,8 +19,9 @@ if(!isset($this->value)) return; $str_pos = strpos($this->value, '('); - // TODO Replace this with parseExpression - if($str_pos===false) return '"'.$this->value.'"'; + // // TODO Replace this with parseExpression + if($str_pos===false) return '\''.$this->value.'\''; + //if($str_pos===false) return $this->value; $func_name = substr($this->value, 0, $str_pos); $args = substr($this->value, $str_pos+1, strlen($value)-1); @@ -52,7 +53,8 @@ $val = sprintf('"%s*%d"', $this->column_name, $args); break; default : - $val = '"' . $this->value . '"'; + $val = '\'' . $this->value . '\''; + //$val = $this->value; } return $val; diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index a96a9a98d..626a4a0b0 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -29,6 +29,10 @@ $this->argument = new QueryArgument($condition); } + function setPipe($pipe){ + $this->pipe = $pipe; + } + function getArgument(){ return $this->argument; } diff --git a/classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php new file mode 100644 index 000000000..1568ecbb7 --- /dev/null +++ b/classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php @@ -0,0 +1,11 @@ +condition_groups[0]->conditions[0]->setPipe(""); + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index cbe726b99..febb8628f 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -12,7 +12,7 @@ function IndexTag($index, $dbParser){ $this->dbParser = $dbParser; $this->argument_name = $index->attrs->var; - //$index->attrs->default = $this->dbParser->parseExpression($index->attrs->default); + $index->attrs->default = $this->dbParser->parseExpression($index->attrs->default); $this->default = $index->attrs->default; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($index); diff --git a/classes/xml/xmlquery/tags/table/TableTag.class.php b/classes/xml/xmlquery/tags/table/TableTag.class.php index 4797df04c..dea2729b7 100644 --- a/classes/xml/xmlquery/tags/table/TableTag.class.php +++ b/classes/xml/xmlquery/tags/table/TableTag.class.php @@ -45,7 +45,7 @@ function getTableString(){ if($this->isJoinTable()){ - $conditionsTag = new ConditionsTag($this->conditions, $this->dbParser); + $conditionsTag = new JoinConditionsTag($this->conditions, $this->dbParser); return sprintf('new JoinTable(\'%s\', \'%s\', "%s", %s)' , $this->dbParser->escape($this->name) , $this->dbParser->escape($this->alias) diff --git a/modules/module/queries/getDefaultModules.xml b/modules/module/queries/getDefaultModules.xml index dd847508e..c6ffd842f 100644 --- a/modules/module/queries/getDefaultModules.xml +++ b/modules/module/queries/getDefaultModules.xml @@ -19,8 +19,8 @@ - - - + + + diff --git a/modules/module/queries/getSiteModules.xml b/modules/module/queries/getSiteModules.xml index 2c80abe39..6d9988eea 100644 --- a/modules/module/queries/getSiteModules.xml +++ b/modules/module/queries/getSiteModules.xml @@ -17,7 +17,7 @@ - - + + From a8bed44a83b26277a51e9cb10de580af13233d27 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Mon, 23 May 2011 08:18:19 +0000 Subject: [PATCH 10/82] Cleaned up some classes that weren't needed. Removed calls to getValidatorString from tags, since the argument escaping is now done directly in the QueryParser class. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8390 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/QueryParser.class.php | 7 ----- .../ConditionQueryArgument.class.php | 26 ------------------- .../ConditionQueryArgumentValidator.class.php | 20 -------------- .../validator/DefaultCheck.class.php | 25 ------------------ .../validator/EscapeCheck.class.php | 21 --------------- .../validator/FilterValidator.class.php | 16 ------------ .../validator/MaxLengthValidator.class.php | 22 ---------------- .../validator/MinLengthValidator.class.php | 22 ---------------- .../validator/NotNullValidator.class.php | 18 ------------- .../tags/column/DeleteColumnTag.class.php | 16 ++---------- .../tags/column/DeleteColumnsTag.class.php | 11 ++------ .../tags/column/InsertColumnTag.class.php | 18 ++----------- .../tags/column/InsertColumnsTag.class.php | 11 ++------ .../tags/column/SelectColumnsTag.class.php | 6 +---- .../tags/column/UpdateColumnTag.class.php | 15 +---------- .../tags/column/UpdateColumnsTag.class.php | 9 +------ .../condition/ConditionGroupTag.class.php | 8 ------ .../tags/condition/ConditionTag.class.php | 6 +---- .../tags/condition/ConditionsTag.class.php | 10 +------ .../tags/navigation/IndexTag.class.php | 9 +------ .../tags/navigation/NavigationTag.class.php | 8 ------ 21 files changed, 14 insertions(+), 290 deletions(-) delete mode 100644 classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php delete mode 100644 classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php delete mode 100644 classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php delete mode 100644 classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php delete mode 100644 classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php delete mode 100644 classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php delete mode 100644 classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php delete mode 100644 classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index c7a50717a..a446c38f9 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -118,15 +118,8 @@ class QueryParser { $arguments = array_merge($arguments, $columns->getArguments()); $arguments = array_merge($arguments, $conditions->getArguments()); $arguments = array_merge($arguments, $navigation->getArguments()); - //foreach($arguments as $argument){ - // var_dump($argument); - // var_dump($this->column_type[$this->getQueryId()][$argument->getColumnName()]); - //} $prebuff = ''; - //$prebuff .= $columns->getValidatorString(); - //$prebuff .= $conditions->getValidatorString(); - //$prebuff .= $navigation->getValidatorString(); foreach($arguments as $argument){ if($argument->getArgumentName()){ $prebuff .= $argument->toString(); diff --git a/classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php b/classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php deleted file mode 100644 index 8c5743dc0..000000000 --- a/classes/xml/xmlquery/queryargument/ConditionQueryArgument.class.php +++ /dev/null @@ -1,26 +0,0 @@ -argument_name = $tag->attrs->var; - - $name = $tag->attrs->column; - if(strpos($name, '.') === false) $this->column_name = $name; - else { - list($prefix, $name) = explode('.', $name); - $this->column_name = $name; - } - - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php'); - $this->argument_validator = new ConditionQueryArgumentValidator($tag); - } - - function getColumnName(){ - return $this->column_name; - } - } -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php deleted file mode 100644 index 4a74b809c..000000000 --- a/classes/xml/xmlquery/queryargument/validator/ConditionQueryArgumentValidator.class.php +++ /dev/null @@ -1,20 +0,0 @@ -argument_name) return ''; - if(!isset($this->validator_string)){ - $validator = parent::toString(); - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php'); - $v = new EscapeCheck($this->argument_name); - $validator .= $v->toString(); - $this->validator_string = $validator; - } - return $this->validator_string; - } - } -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php b/classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php deleted file mode 100644 index e6048fc28..000000000 --- a/classes/xml/xmlquery/queryargument/validator/DefaultCheck.class.php +++ /dev/null @@ -1,25 +0,0 @@ -argument_name = $argument_name; - $this->value = $value; - } - - function toString(){ - if(!isset($this->argument_name)) return ''; - - $value = $this->value->toString(); - - if($this->value->isString()) { - $value = "'".$value."'"; - } - - return 'if(!isset($args->'.$this->argument_name.')) $args->'.$this->argument_name.' = '.$value.';'."\n"; - } - } - -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php b/classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php deleted file mode 100644 index 1d37cb953..000000000 --- a/classes/xml/xmlquery/queryargument/validator/EscapeCheck.class.php +++ /dev/null @@ -1,21 +0,0 @@ -argument_name = $argument_name; - } - - function toString(){ - return sprintf("if(is_string(\$args->%s) && !is_numeric(\$args->%s)) \$args->%s = \$dbParser->escapeString(\$args->%s);\n" - , $this->argument_name - , $this->argument_name - , $this->argument_name - , $this->argument_name); - } - } - -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php b/classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php deleted file mode 100644 index 29a8e9cbf..000000000 --- a/classes/xml/xmlquery/queryargument/validator/FilterValidator.class.php +++ /dev/null @@ -1,16 +0,0 @@ -argument_name = $argument_name; - $this->filter = $filter; - } - - function toString(){ - return sprintf('if(isset($args->%s)) { unset($_output); $_output = $this->checkFilter("%s",$args->%s,"%s"); if(!$_output->toBool()) return $_output; } %s',$this->argument_name, $this->argument_name,$this->argument_name,$this->filter,"\n"); - } - } - -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php b/classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php deleted file mode 100644 index 3d94cd12e..000000000 --- a/classes/xml/xmlquery/queryargument/validator/MaxLengthValidator.class.php +++ /dev/null @@ -1,22 +0,0 @@ -argument_name = $argument_name; - $this->value = $value; - } - - function toString(){ - return 'if($args->' - .$this->argument_name - .'&&strlen($args->'.$this->argument_name.')>'.$this->value - .') return new Object(-1, sprintf($lang->filter->outofrange, $lang->' - .$this->argument_name.'?$lang->' - .$this->argument_name.':\''.$this->argument_name.'\'));'."\n"; - } - } - -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php b/classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php deleted file mode 100644 index 2717f4487..000000000 --- a/classes/xml/xmlquery/queryargument/validator/MinLengthValidator.class.php +++ /dev/null @@ -1,22 +0,0 @@ -argument_name = $argument_name; - $this->value = $value; - } - - function toString(){ - return 'if($args->' - .$this->argument_name - .'&&strlen($args->'.$this->argument_name.')<'.$this->value - .') return new Object(-1, sprintf($lang->filter->outofrange, $lang->' - .$this->argument_name.'?$lang->' - .$this->argument_name.':\''.$this->argument_name.'\'));'."\n"; - } - } - -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php b/classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php deleted file mode 100644 index 4f87b0462..000000000 --- a/classes/xml/xmlquery/queryargument/validator/NotNullValidator.class.php +++ /dev/null @@ -1,18 +0,0 @@ -argument_name = $argument_name; - $this->value = $value; - } - - function toString(){ - return 'if(!isset($args->'.$this->argument_name.')) return new Object(-1, sprintf($lang->filter->isnull, $lang->' - .$this->argument_name.'?$lang->'.$this->argument_name.':\''.$this->argument_name.'\'));'."\n"; - } - - } -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php b/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php index 0c2b1b6db..24c5d094c 100644 --- a/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php @@ -16,15 +16,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($column); } - function toString(){ - $output_columns = 'array(' . PHP_EOL; - foreach($this->argument as $argument){ - $output_columns .= $argument->getExpressionString() . PHP_EOL . ','; - } - $output_columns = substr($output_columns, 0, -1); - $output_columns .= ')'; - return $output_columns; - } + function getExpressionString(){ return sprintf('new DeleteExpression(\'%s\', $args->%s)' , $this->name @@ -33,11 +25,7 @@ function getArgument(){ return $this->argument; - } - - function getValidatorString(){ - return $this->argument->getValidatorString(); - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php b/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php index b242d7ca0..662328479 100644 --- a/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php @@ -27,6 +27,7 @@ $this->columns[] = new DeleteColumnTag($column, $this->dbParser); } } + function toString(){ $output_columns = 'array(' . PHP_EOL; foreach($this->columns as $column){ @@ -43,15 +44,7 @@ $arguments[] = $column->getArgument(); } return $arguments; - } - - function getValidatorString(){ - $validator = ''; - foreach($this->columns as $column){ - $validator .= $column->getValidatorString(); - } - return $validator; - } + } } diff --git a/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php index 9dfba9247..d18f95685 100644 --- a/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php @@ -15,17 +15,7 @@ $this->name = $this->dbParser->parseColumnName($this->name); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($column); - } - - function toString(){ - $output_columns = 'array(' . PHP_EOL; - foreach($this->argument as $argument){ - $output_columns .= $argument->getExpressionString() . PHP_EOL . ','; - } - $output_columns = substr($output_columns, 0, -1); - $output_columns .= ')'; - return $output_columns; - } + } function getExpressionString(){ return sprintf('new InsertExpression(\'%s\', $%s_argument->getValue())' @@ -35,11 +25,7 @@ function getArgument(){ return $this->argument; - } - - function getValidatorString(){ - return $this->argument->getValidatorString(); - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php index 086cbba2d..d5aafd30a 100644 --- a/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php @@ -27,6 +27,7 @@ $this->columns[] = new InsertColumnTag($column, $this->dbParser); } } + function toString(){ $output_columns = 'array(' . PHP_EOL; foreach($this->columns as $column){ @@ -43,15 +44,7 @@ $arguments[] = $column->getArgument(); } return $arguments; - } - - function getValidatorString(){ - $validator = ''; - foreach($this->columns as $column){ - $validator .= $column->getValidatorString(); - } - return $validator; - } + } } diff --git a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php index 15102f130..ef0d952a2 100644 --- a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php @@ -36,10 +36,6 @@ function getArguments(){ return array(); - } - - function getValidatorString(){ - return ''; - } + } } ?> diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php index d41905e59..90b44b0e9 100644 --- a/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php @@ -19,15 +19,6 @@ $this->argument = new QueryArgument($column); } - function toString(){ - $output_columns = 'array(' . PHP_EOL; - foreach($this->argument as $argument){ - $output_columns .= $argument->getExpressionString() . PHP_EOL . ','; - } - $output_columns = substr($output_columns, 0, -1); - $output_columns .= ')'; - return $output_columns; - } function getExpressionString(){ return sprintf('new UpdateExpression(\'%s\', $%s_argument->getValue())' , $this->name @@ -36,11 +27,7 @@ function getArgument(){ return $this->argument; - } - - function getValidatorString(){ - return $this->argument->getValidatorString(); - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php index 2f1feba0f..9ead8811a 100644 --- a/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php @@ -48,14 +48,7 @@ } return $arguments; } - - function getValidatorString(){ - $validator = ''; - foreach($this->columns as $column){ - $validator .= $column->getValidatorString(); - } - return $validator; - } + } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php index 93de1dde9..58546f761 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php @@ -39,14 +39,6 @@ } return $arguments; } - - function getValidatorString(){ - $validator = ''; - foreach($this->conditions as $condition){ - $validator .= $condition->getValidatorString(); - } - return $validator; - } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index 626a4a0b0..ae5eb08d2 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -44,10 +44,6 @@ , '"'.$this->operation.'"' , $this->pipe ? ", '" . $this->pipe . "'" : '' ); - } - - function getValidatorString(){ - return $this->argument->getValidatorString(); - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php index ef174bc2e..fec1063cd 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php @@ -39,14 +39,6 @@ $arguments = array_merge($arguments, $condition->getArguments()); } return $arguments; - } - - function getValidatorString(){ - $validator = ''; - foreach($this->condition_groups as $condition){ - $validator .= $condition->getValidatorString(); - } - return $validator; - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index febb8628f..ed2d79e54 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -36,14 +36,7 @@ if($this->sort_order_argument) $arguments[] = $this->sort_order_argument; return $arguments; - } - - function getValidatorString(){ - $validator = $this->argument->getValidatorString(); - if($this->sort_order_argument) - $validator .= $this->sort_order_argument->getValidatorString(); - return $validator; - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php index 98824592b..c8dba8b94 100644 --- a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php @@ -46,14 +46,6 @@ $arguments = array_merge($order->getArguments(), $arguments); } return $arguments; - } - - function getValidatorString(){ - $validator = ''; - foreach ($this->order as $order){ - $validator .= $order->getValidatorString(); - } - return $validator; } } From abba8761cccdef26c8f454e0bb917b660ac86ae9 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Mon, 23 May 2011 08:42:16 +0000 Subject: [PATCH 11/82] fixed an issue when default argument name is column name git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8391 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/argument/Argument.class.php | 2 +- classes/xml/xmlquery/queryargument/QueryArgument.class.php | 2 ++ .../queryargument/validator/QueryArgumentValidator.class.php | 1 + classes/xml/xmlquery/tags/condition/ConditionTag.class.php | 3 ++- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 23cb46539..8e8e3fb88 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -34,7 +34,7 @@ if(!isset($this->value)) return; if($column_type === '') return; //if($column_type === '') $column_type = 'varchar'; - if(in_array($column_type, array('date', 'varchar', 'char'))) + if(in_array($column_type, array('date', 'varchar', 'char', 'bigtext'))) $this->value = '\''.$this->value.'\''; } diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index b18e6d784..a8df696f7 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -17,6 +17,8 @@ } if(!$this->argument_name) $this->argument_name = $tag->attrs->name; + if(!$this->argument_name) $this->argument_name = $tag->attrs->column; + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); $this->argument_validator = new QueryArgumentValidator($tag); diff --git a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php index 371dd33c3..9c4d478df 100644 --- a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php +++ b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php @@ -14,6 +14,7 @@ function QueryArgumentValidator($tag){ $this->argument_name = $tag->attrs->var; if(!$this->argument_name) $this->argument_name = $tag->attrs->name; + if(!$this->argument_name) $this->argument_name = $tag->attrs->column; $this->default_value = $tag->attrs->default; $this->notnull = $tag->attrs->notnull; $this->filter = $tag->attrs->filter; diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index ae5eb08d2..563f2c4e0 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -22,8 +22,9 @@ $this->operation = $condition->attrs->operation; $this->pipe = $condition->attrs->pipe; $this->column_name = $this->dbParser->parseColumnName($condition->attrs->column); - // TODO fix this hack - should use default value for query argument + // TODO fix this hack - argument_name is initialized in three places :) [ here, queryArgument and queryArgumentValidator] $this->argument_name = $condition->attrs->var; + if(!$this->argument_name) $this->argument_name = $condition->attrs->column; $this->default_column = $this->dbParser->parseColumnName($condition->attrs->default); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($condition); From 52c3d503bc220fb77efbc144ba1f4e20055f8428 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Mon, 23 May 2011 09:01:00 +0000 Subject: [PATCH 12/82] Changed code to use dbParser as singleton - instead of passing it in the constructor every time. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8392 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/XmlQueryParser.class.php | 16 ++++++------- classes/xml/xmlquery/QueryParser.class.php | 23 ++++++++----------- .../xmlquery/tags/column/ColumnTag.class.php | 4 +--- .../tags/column/DeleteColumnTag.class.php | 7 +++--- .../tags/column/DeleteColumnsTag.class.php | 7 ++---- .../tags/column/InsertColumnTag.class.php | 7 +++--- .../tags/column/InsertColumnsTag.class.php | 7 ++---- .../tags/column/SelectColumnTag.class.php | 13 +++++++---- .../tags/column/SelectColumnsTag.class.php | 9 +++----- .../tags/column/UpdateColumnTag.class.php | 7 +++--- .../tags/column/UpdateColumnsTag.class.php | 14 +++-------- .../condition/ConditionGroupTag.class.php | 9 +++----- .../tags/condition/ConditionTag.class.php | 9 ++++---- .../tags/condition/ConditionsTag.class.php | 8 +++---- .../condition/JoinConditionsTag.class.php | 4 ++-- .../xmlquery/tags/group/GroupsTag.class.php | 9 ++++---- .../tags/navigation/IndexTag.class.php | 11 ++++----- .../tags/navigation/NavigationTag.class.php | 5 ++-- .../xmlquery/tags/table/TableTag.class.php | 20 ++++++++-------- .../xmlquery/tags/table/TablesTag.class.php | 6 ++--- 20 files changed, 82 insertions(+), 113 deletions(-) diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 8e1595056..1b4b4514d 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -23,22 +23,20 @@ $action = strtolower($xml_obj->query->attrs->action); if(!$action) return; - //$oDB = &DB::getParser(); - //$dbParser = $oDB->getParser(); - $dbParser = $this->getDBParser(); - $parser = new QueryParser($xml_obj->query, $dbParser); + $parser = new QueryParser($xml_obj->query); FileHandler::writeFile($cache_file, $parser->toString()); } // singleton - function getDBParser(){ - if(!$this->dbParser){ + function &getDBParser(){ + static $dbParser; + if(!$dbParser){ //$oDB = &DB::getParser(); - //$dbParser = $oDB->getParser(); - $this->dbParser = new DBParser('"'); + //self::$dbParser = $oDB->getParser(); + $dbParser = new DBParser('"'); } - return $this->dbParser; + return $dbParser; } function getXmlFileContent($xml_file){ diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index a446c38f9..96898c5f2 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -17,16 +17,12 @@ class QueryParser { var $action; var $query_id; - var $dbParser; - var $column_type; - function QueryParser($query, $dbParser){ + function QueryParser($query){ $this->query = $query; $this->action = $this->query->attrs->action; $this->query_id = $this->query->attrs->id; - - $this->dbParser = $dbParser; } function getQueryId(){ @@ -97,20 +93,20 @@ class QueryParser { function toString(){ if($this->action == 'select'){ - $columns = new SelectColumnsTag($this->query->columns->column, $this->dbParser); + $columns = new SelectColumnsTag($this->query->columns->column); }else if($this->action == 'insert'){ - $columns = new InsertColumnsTag($this->query->columns->column, $this->dbParser); + $columns = new InsertColumnsTag($this->query->columns->column); }else if($this->action == 'update') { - $columns = new UpdateColumnsTag($this->query->columns->column, $this->dbParser); + $columns = new UpdateColumnsTag($this->query->columns->column); }else if($this->action == 'delete') { - $columns = new DeleteColumnsTag($this->query->columns->column, $this->dbParser); + $columns = new DeleteColumnsTag($this->query->columns->column); } - $tables = new TablesTag($this->query->tables->table, $this->dbParser); - $conditions = new ConditionsTag($this->query->conditions, $this->dbParser); - $groups = new GroupsTag($this->query->groups->group, $this->dbParser); - $navigation = new NavigationTag($this->query->navigation, $this->dbParser); + $tables = new TablesTag($this->query->tables->table); + $conditions = new ConditionsTag($this->query->conditions); + $groups = new GroupsTag($this->query->groups->group); + $navigation = new NavigationTag($this->query->navigation); $this->setTableColumnTypes($tables); @@ -139,7 +135,6 @@ class QueryParser { $buff .= '$output->orderby = ' . $navigation->getOrderByString() .';'; return "dbParser->getEscapeChar()."');\n" . sprintf('$output->query_id = "%s";%s', $this->query_id, "\n") . sprintf('$output->action = "%s";%s', $this->action, "\n") . $prebuff diff --git a/classes/xml/xmlquery/tags/column/ColumnTag.class.php b/classes/xml/xmlquery/tags/column/ColumnTag.class.php index 7cf066013..8ffe77373 100644 --- a/classes/xml/xmlquery/tags/column/ColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/ColumnTag.class.php @@ -12,10 +12,8 @@ class ColumnTag { var $name; - var $dbParser; - function ColumnTag($name, $dbParser){ - $this->dbParser = $dbParser; + function ColumnTag($name){ $this->name = $name; } } \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php b/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php index 24c5d094c..3ac64a2c4 100644 --- a/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php @@ -10,9 +10,10 @@ class DeleteColumnTag extends ColumnTag { var $argument; - function DeleteColumnTag($column, $dbParser) { - parent::ColumnTag($column->attrs->name, $dbParser); - $this->name = $this->dbParser->parseColumnName($this->name); + function DeleteColumnTag($column) { + parent::ColumnTag($column->attrs->name); + $dbParser = XmlQueryParser::getDBParser(); + $this->name = $dbParser->parseColumnName($this->name); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($column); } diff --git a/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php b/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php index 662328479..753d79cf0 100644 --- a/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php @@ -10,12 +10,9 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php'); class DeleteColumnsTag{ - var $dbParser; var $columns; - function DeleteColumnsTag($xml_columns, $dbParser) { - $this->dbParser = $dbParser; - + function DeleteColumnsTag($xml_columns) { $this->columns = array(); if(!$xml_columns) @@ -24,7 +21,7 @@ if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - $this->columns[] = new DeleteColumnTag($column, $this->dbParser); + $this->columns[] = new DeleteColumnTag($column); } } diff --git a/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php index d18f95685..1d42ffb3a 100644 --- a/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php @@ -10,9 +10,10 @@ class InsertColumnTag extends ColumnTag { var $argument; - function InsertColumnTag($column, $dbParser) { - parent::ColumnTag($column->attrs->name, $dbParser); - $this->name = $this->dbParser->parseColumnName($this->name); + function InsertColumnTag($column) { + parent::ColumnTag($column->attrs->name); + $dbParser = XmlQueryParser::getDBParser(); + $this->name = $dbParser->parseColumnName($this->name); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($column); } diff --git a/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php index d5aafd30a..5f0893b1f 100644 --- a/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php @@ -10,12 +10,9 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnTag.class.php'); class InsertColumnsTag{ - var $dbParser; var $columns; - function InsertColumnsTag($xml_columns, $dbParser) { - $this->dbParser = $dbParser; - + function InsertColumnsTag($xml_columns) { $this->columns = array(); if(!$xml_columns) @@ -24,7 +21,7 @@ if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - $this->columns[] = new InsertColumnTag($column, $this->dbParser); + $this->columns[] = new InsertColumnTag($column); } } diff --git a/classes/xml/xmlquery/tags/column/SelectColumnTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnTag.class.php index ca7a40eff..61031dfcc 100644 --- a/classes/xml/xmlquery/tags/column/SelectColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/SelectColumnTag.class.php @@ -11,11 +11,13 @@ var $alias; var $click_count; - function SelectColumnTag($column, $dbParser){ - parent::ColumnTag($column->attrs->name, $dbParser); + function SelectColumnTag($column){ + parent::ColumnTag($column->attrs->name); if(!$this->name) $this->name = "*"; - if($this->name != "*") - $this->name = $this->dbParser->parseExpression($this->name); + if($this->name != "*") { + $dbParser = XmlQueryParser::getDBParser(); + $this->name = $dbParser->parseExpression($this->name); + } $this->alias = $column->attrs->alias; $this->click_count = $column->attrs->click_count; @@ -25,7 +27,8 @@ if($this->name == '*') return "new StarExpression()"; if($this->click_count) return sprintf('new ClickCountExpression(%s, %s, $args->%s)', $this->name, $this->alias,$this->click_count); - return sprintf('new SelectExpression(\'%s\'%s)', $this->name, $this->alias ? ', \''.$this->dbParser->escape($this->alias) .'\'': ''); + $dbParser = XmlQueryParser::getDBParser(); + return sprintf('new SelectExpression(\'%s\'%s)', $this->name, $this->alias ? ', \''.$dbParser->escape($this->alias) .'\'': ''); } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php index ef0d952a2..e5e741042 100644 --- a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php @@ -4,23 +4,20 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/SelectColumnTag.class.php'); class SelectColumnsTag { - var $dbParser; var $columns; - function SelectColumnsTag($xml_columns, $dbParser){ - $this->dbParser = $dbParser; - + function SelectColumnsTag($xml_columns){ $this->columns = array(); if(!$xml_columns) { - $this->columns[] = new SelectColumnTag("*", $this->dbParser); + $this->columns[] = new SelectColumnTag("*"); return; } if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - $this->columns[] = new SelectColumnTag($column, $this->dbParser); + $this->columns[] = new SelectColumnTag($column); } } diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php index 90b44b0e9..93d4c2b5b 100644 --- a/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php @@ -12,9 +12,10 @@ class UpdateColumnTag extends ColumnTag { var $argument; - function UpdateColumnTag($column, $dbParser) { - parent::ColumnTag($column->attrs->name, $dbParser); - $this->name = $this->dbParser->parseColumnName($this->name); + function UpdateColumnTag($column) { + parent::ColumnTag($column->attrs->name); + $dbParser = XmlQueryParser::getDBParser(); + $this->name = $dbParser->parseColumnName($this->name); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($column); } diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php index 9ead8811a..a0a856af1 100644 --- a/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php @@ -11,23 +11,15 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php'); class UpdateColumnsTag{ - var $dbParser; var $columns; - function UpdateColumnsTag($xml_columns, $dbParser) { - $this->dbParser = $dbParser; - + function UpdateColumnsTag($xml_columns) { $this->columns = array(); - - if(!$xml_columns) { - $this->columns[] = new UpdateColumnTag("*", $this->dbParser); - return; - } - + if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - $this->columns[] = new UpdateColumnTag($column, $this->dbParser); + $this->columns[] = new UpdateColumnTag($column); } } diff --git a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php index 58546f761..bd62f0137 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php @@ -1,20 +1,17 @@ dbParser = $dbParser; + function ConditionGroupTag($conditions, $pipe = ""){ $this->pipe = $pipe; if(!is_array($conditions)) $conditions = array($conditions); if(count($conditions))require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); foreach($conditions as $condition){ - $this->conditions[] = new ConditionTag($condition, $dbParser); + $this->conditions[] = new ConditionTag($condition); } } diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index 563f2c4e0..a422cd7c3 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -8,7 +8,6 @@ */ class ConditionTag { - var $dbParser; var $operation; var $column_name; @@ -17,15 +16,15 @@ var $argument; var $default_column; - function ConditionTag($condition, $dbParser){ - $this->dbParser = $dbParser; + function ConditionTag($condition){ $this->operation = $condition->attrs->operation; $this->pipe = $condition->attrs->pipe; - $this->column_name = $this->dbParser->parseColumnName($condition->attrs->column); + $dbParser = XmlQueryParser::getDBParser(); + $this->column_name = $dbParser->parseColumnName($condition->attrs->column); // TODO fix this hack - argument_name is initialized in three places :) [ here, queryArgument and queryArgumentValidator] $this->argument_name = $condition->attrs->var; if(!$this->argument_name) $this->argument_name = $condition->attrs->column; - $this->default_column = $this->dbParser->parseColumnName($condition->attrs->default); + $this->default_column = $dbParser->parseColumnName($condition->attrs->default); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($condition); } diff --git a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php index fec1063cd..1d17ea1e3 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php @@ -1,16 +1,14 @@ dbParser = $dbParser; + function ConditionsTag($xml_conditions){ $this->condition_groups = array(); $xml_condition_list = $xml_conditions->condition; if($xml_condition_list){ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php'); - $this->condition_groups[] = new ConditionGroupTag($xml_condition_list, $this->dbParser); + $this->condition_groups[] = new ConditionGroupTag($xml_condition_list); } $xml_groups = $xml_conditions->group; @@ -18,7 +16,7 @@ if(!is_array($xml_groups)) $xml_groups = array($xml_groups); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php'); foreach($xml_groups as $group){ - $this->condition_groups[] = new ConditionGroupTag($group->condition, $this->dbParser, $group->pipe); + $this->condition_groups[] = new ConditionGroupTag($group->condition, $group->pipe); } } } diff --git a/classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php index 1568ecbb7..3b59989f6 100644 --- a/classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php +++ b/classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php @@ -2,8 +2,8 @@ class JoinConditionsTag extends ConditionsTag { - function JoinConditionsTag($xml_conditions, $dbParser){ - parent::ConditionsTag($xml_conditions, $dbParser); + function JoinConditionsTag($xml_conditions){ + parent::ConditionsTag($xml_conditions); $this->condition_groups[0]->conditions[0]->setPipe(""); } } diff --git a/classes/xml/xmlquery/tags/group/GroupsTag.class.php b/classes/xml/xmlquery/tags/group/GroupsTag.class.php index 266e9accb..19f74fe43 100644 --- a/classes/xml/xmlquery/tags/group/GroupsTag.class.php +++ b/classes/xml/xmlquery/tags/group/GroupsTag.class.php @@ -2,21 +2,20 @@ class GroupsTag { var $groups; - var $dbParser; - function GroupsTag($xml_groups, $dbParser){ - $this->dbParser = $dbParser; - + function GroupsTag($xml_groups){ $this->groups = array(); if($xml_groups) { if(!is_array($xml_groups)) $xml_groups = array($xml_groups); + $dbParser = XmlQueryParser::getDBParser(); for($i=0;$iattrs->column); if(!$column) continue; - $column = $this->dbParser->parseExpression($column); + + $column = $dbParser->parseExpression($column); $this->groups[] = $column; } } diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index ed2d79e54..aae32d16b 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -1,18 +1,17 @@ dbParser = $dbParser; + function IndexTag($index){ $this->argument_name = $index->attrs->var; - $index->attrs->default = $this->dbParser->parseExpression($index->attrs->default); + + $dbParser = XmlQueryParser::getDBParser(); + $index->attrs->default = $dbParser->parseExpression($index->attrs->default); $this->default = $index->attrs->default; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($index); diff --git a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php index c8dba8b94..87fa9d064 100644 --- a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php @@ -2,20 +2,19 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/navigation/IndexTag.class.php'); class NavigationTag { - var $dbParser; var $order; var $list_count; var $page_count; var $page; - function NavigationTag($xml_navigation, $dbParser){ + function NavigationTag($xml_navigation){ $this->order = array(); if($xml_navigation) { $order = $xml_navigation->index; if($order) { if(!is_array($order)) $order = array($order); foreach($order as $order_info) { - $this->order[] = new IndexTag($order_info, $dbParser); + $this->order[] = new IndexTag($order_info); } } diff --git a/classes/xml/xmlquery/tags/table/TableTag.class.php b/classes/xml/xmlquery/tags/table/TableTag.class.php index dea2729b7..3f432770d 100644 --- a/classes/xml/xmlquery/tags/table/TableTag.class.php +++ b/classes/xml/xmlquery/tags/table/TableTag.class.php @@ -15,13 +15,12 @@ var $join_type; var $conditions; - var $dbParser; - - function TableTag($table, $dbParser){ - $this->dbParser = $dbParser; + function TableTag($table){ $this->unescaped_name = $table->attrs->name; - $this->name = $this->dbParser->parseTableName($table->attrs->name); + + $dbParser = XmlQueryParser::getDBParser(); + $this->name = $dbParser->parseTableName($table->attrs->name); $this->alias = $table->attrs->alias; //if(!$this->alias) $this->alias = $alias; @@ -44,16 +43,17 @@ } function getTableString(){ + $dbParser = XmlQueryParser::getDBParser(); if($this->isJoinTable()){ - $conditionsTag = new JoinConditionsTag($this->conditions, $this->dbParser); + $conditionsTag = new JoinConditionsTag($this->conditions); return sprintf('new JoinTable(\'%s\', \'%s\', "%s", %s)' - , $this->dbParser->escape($this->name) - , $this->dbParser->escape($this->alias) + , $dbParser->escape($this->name) + , $dbParser->escape($this->alias) , $this->join_type, $conditionsTag->toString()); } return sprintf('new Table(\'%s\'%s)' - , $this->dbParser->escape($this->name) - , $this->alias ? ', \'' . $this->dbParser->escape($this->alias) .'\'' : ''); + , $dbParser->escape($this->name) + , $this->alias ? ', \'' . $dbParser->escape($this->alias) .'\'' : ''); } } diff --git a/classes/xml/xmlquery/tags/table/TablesTag.class.php b/classes/xml/xmlquery/tags/table/TablesTag.class.php index 862cfd9ae..d4560594b 100644 --- a/classes/xml/xmlquery/tags/table/TablesTag.class.php +++ b/classes/xml/xmlquery/tags/table/TablesTag.class.php @@ -1,18 +1,16 @@ dbParser = $dbParser; + function TablesTag($xml_tables){ $this->tables = array(); if(!is_array($xml_tables)) $xml_tables = array($xml_tables); if(count($xml_tables)) require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); foreach($xml_tables as $table){ - $this->tables[] = new TableTag($table, $this->dbParser); + $this->tables[] = new TableTag($table); } } From c40ccf777f7486eadfe5d1e104f529fc15a20fab Mon Sep 17 00:00:00 2001 From: mosmartin Date: Mon, 23 May 2011 09:28:18 +0000 Subject: [PATCH 13/82] Fixed condition tag bug. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8393 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/QueryParser.class.php | 2 +- .../queryargument/QueryArgument.class.php | 2 +- .../tags/condition/ConditionTag.class.php | 17 ++++++++++------- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 96898c5f2..805140fe5 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -117,7 +117,7 @@ class QueryParser { $prebuff = ''; foreach($arguments as $argument){ - if($argument->getArgumentName()){ + if(isset($argument) && $argument->getArgumentName()){ $prebuff .= $argument->toString(); $prebuff .= sprintf("$%s_argument->escapeValue('%s');\n" , $argument->getArgumentName() diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index a8df696f7..63dc9fb98 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -17,7 +17,7 @@ } if(!$this->argument_name) $this->argument_name = $tag->attrs->name; - if(!$this->argument_name) $this->argument_name = $tag->attrs->column; + if(!$this->argument_name) $this->argument_name = str_replace('.', '_', $condition->attrs->column); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); $this->argument_validator = new QueryArgumentValidator($tag); diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index a422cd7c3..4f6017478 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -21,12 +21,15 @@ $this->pipe = $condition->attrs->pipe; $dbParser = XmlQueryParser::getDBParser(); $this->column_name = $dbParser->parseColumnName($condition->attrs->column); - // TODO fix this hack - argument_name is initialized in three places :) [ here, queryArgument and queryArgumentValidator] - $this->argument_name = $condition->attrs->var; - if(!$this->argument_name) $this->argument_name = $condition->attrs->column; - $this->default_column = $dbParser->parseColumnName($condition->attrs->default); - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - $this->argument = new QueryArgument($condition); + + if($condition->attrs->var){ + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + $this->argument_name = $condition->attrs->var; + $this->argument = new QueryArgument($condition); + } + else { + $this->default_column = $dbParser->parseColumnName($condition->attrs->default); + } } function setPipe($pipe){ @@ -40,7 +43,7 @@ function getConditionString(){ return sprintf("new Condition('%s',%s,%s%s)" , $this->column_name - , $this->argument_name ? '$' . $this->argument_name . '_argument->getValue()' : "'" . $this->default_column . "'" + , $this->default_column ? "'" . $this->default_column . "'" : '$' . $this->argument_name . '_argument->getValue()' , '"'.$this->operation.'"' , $this->pipe ? ", '" . $this->pipe . "'" : '' ); From 4d2d18b53b9bfe10ed6573e729fe42add5806620 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Mon, 23 May 2011 14:45:00 +0000 Subject: [PATCH 14/82] Fixed condition group bug. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8394 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../queryparts/condition/Condition.class.php | 15 ++- .../condition/ConditionGroup.class.php | 9 +- .../argument/ConditionArgument.class.php | 111 ++++++++++++++++++ .../queryargument/QueryArgument.class.php | 38 ++++-- .../condition/ConditionGroupTag.class.php | 2 +- .../tags/condition/ConditionTag.class.php | 12 +- .../tags/condition/ConditionsTag.class.php | 4 +- .../tags/navigation/NavigationTag.class.php | 4 + modules/opage/queries/getOpageList.xml | 2 +- 9 files changed, 178 insertions(+), 19 deletions(-) create mode 100644 classes/xml/xmlquery/argument/ConditionArgument.class.php diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index 4db069e72..b77ed1173 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -14,7 +14,11 @@ } function toString(){ - return $this->pipe . ' ' . $this->getConditionPart($this->column_name, $this->value, $this->operation); + return $this->pipe . ' ' . $this->getConditionPart(); + } + + function setPipe($pipe){ + $this->pipe = $pipe; } function show(){ @@ -42,8 +46,13 @@ } return true; } - - function getConditionPart($name, $value, $operation) { + + function getConditionPart() { + + $name = $this->column_name; + $value = $this->value; + $operation = $this->operation; + switch($operation) { case 'equal' : return $name.' = '.$value; diff --git a/classes/db/queryparts/condition/ConditionGroup.class.php b/classes/db/queryparts/condition/ConditionGroup.class.php index bc3a1b888..5e9a943b9 100644 --- a/classes/db/queryparts/condition/ConditionGroup.class.php +++ b/classes/db/queryparts/condition/ConditionGroup.class.php @@ -11,12 +11,17 @@ function toString(){ if($this->pipe !== "") - $group = $this->pipe .'('; + $group = $this->pipe .' ('; else $group = ''; + $cond_indx = 0; + foreach($this->conditions as $condition){ - if($condition->show()) + if($condition->show()){ + if($cond_indx === 0) $condition->setPipe(""); $group .= $condition->toString() . ' '; + $cond_indx++; + } } if($this->pipe !== "") diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php new file mode 100644 index 000000000..7e6040990 --- /dev/null +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -0,0 +1,111 @@ +operation = $operation; + } + + function createConditionValue(){ + if(!isset($this->value)) return; + + $name = $this->column_name; + $operation = $this->operation; + $value = $this->value; + + switch($operation) { + case 'like_prefix' : + $this->value = $value.'%'; + break; + case 'like_tail' : + $this-> value = '%'.$value; + break; + case 'like' : + $this->value = '%'.$value.'%'; + break; + } + /* + //if(!in_array($operation,array('in','notin','between')) && is_array($value)){ + // $value = join(',', $value); + //} + // Daca operatia nu este in, notin, between si coloana e de tip numeric + // daca valoarea e array -> concatenare + // daca valoarea nu e array si nici nu contine paranteze (nu e functie) -> return (int) + // altfel return valoare + +// if(!in_array($operation,array('in','notin','between')) && $type == 'number') { +// if(is_array($value)){ +// $value = join(',',$value); +// } +// if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; +// return $value; +// } +// +// if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { +// list($table_name, $column_name) = explode('.', $value); +// if($column_type[$column_name]) return $value; +// } + + switch($operation) { + case 'like_prefix' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = $value.'%'; + break; + case 'like_tail' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = '%'.$value; + break; + case 'like' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = '%'.$value.'%'; + break; +// case 'notin' : +// if(is_array($value)) +// { +// $value = $this->addQuotesArray($value); +// if($type=='number') return join(',',$value); +// else return "'". join("','",$value)."'"; +// } +// else +// { +// return $value; +// } +// break; +// case 'in' : +// if(is_array($value)) +// { +// $value = $this->addQuotesArray($value); +// if($type=='number') return join(',',$value); +// else return "'". join("','",$value)."'"; +// } +// else +// { +// return $value; +// } +// break; +// case 'between' : +// if(!is_array($value)) $value = array($value); +// $value = $this->addQuotesArray($value); +// if($type!='number') +// { +// foreach($value as $k=>$v) +// { +// $value[$k] = "'".$v."'"; +// } +// } + + //return $value; + break; + default: + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + } + $this->value = $value; + //return "'".$this->addQuotes($value)."'"; + */ + + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index 63dc9fb98..e4dfbe7ab 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -4,9 +4,16 @@ var $argument_name; var $argument_validator; var $column_name; + var $operation; + var $ignoreValue; function QueryArgument($tag){ $this->argument_name = $tag->attrs->var; + if(!$this->argument_name) $this->ignoreValue = true; + else $this->ignoreValue = false; + + if(!$this->argument_name) $this->argument_name = $tag->attrs->name; + if(!$this->argument_name) $this->argument_name = $tag->attrs->column; $name = $tag->attrs->name; if(!$name) $name = $tag->attrs->column; @@ -14,10 +21,9 @@ else { list($prefix, $name) = explode('.', $name); $this->column_name = $name; - } + } - if(!$this->argument_name) $this->argument_name = $tag->attrs->name; - if(!$this->argument_name) $this->argument_name = str_replace('.', '_', $condition->attrs->column); + if($tag->attrs->operation) $this->operation = $tag->attrs->operation; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); $this->argument_validator = new QueryArgumentValidator($tag); @@ -37,11 +43,29 @@ } function toString(){ - $arg = sprintf("\n$%s_argument = new Argument('%s', %s);\n" - , $this->argument_name - , $this->argument_name - , '$args->'.$this->argument_name); + if($this->operation) + $arg = sprintf("\n$%s_argument = new ConditionArgument('%s', %s, '%s');\n" + , $this->argument_name + , $this->argument_name + , $this->ignoreValue ? 'null' : '$args->'.$this->argument_name + , $this->operation + ); + + else + $arg = sprintf("\n$%s_argument = new Argument('%s', %s);\n" + , $this->argument_name + , $this->argument_name + , $this->ignoreValue ? 'null' : '$args->'.$this->argument_name); + + $arg .= $this->argument_validator->toString(); + + if($this->operation){ + $arg .= sprintf("$%s_argument->createConditionValue();\n" + , $this->argument_name + ); + } + $arg .= sprintf("if(!$%s_argument->isValid()) return $%s_argument->getErrorMessage();\n" , $this->argument_name , $this->argument_name diff --git a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php index bd62f0137..728be23b1 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php @@ -26,7 +26,7 @@ $conditions_string = substr($conditions_string, 0, -2);//remove ',' $conditions_string .= ')'; - return sprintf("new ConditionGroup(%s%s)", $conditions_string, $this->pipe ? ','.$this->pipe : ''); + return sprintf("new ConditionGroup(%s%s)", $conditions_string, $this->pipe ? ',\''.$this->pipe . '\'': ''); } function getArguments(){ diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index 4f6017478..aed904eff 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -22,11 +22,17 @@ $dbParser = XmlQueryParser::getDBParser(); $this->column_name = $dbParser->parseColumnName($condition->attrs->column); - if($condition->attrs->var){ + $isColumnName = strpos($condition->attrs->default, '.'); + + if($condition->attrs->var || $isColumnName === false){ require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - $this->argument_name = $condition->attrs->var; - $this->argument = new QueryArgument($condition); + //$this->argument_name = $condition->attrs->var; + $this->argument = new QueryArgument($condition); + $this->argument_name = $this->argument->getArgumentName(); } + //else if($isColumnName === false){ + // $this->default_column = $condition->attrs->default; + //} else { $this->default_column = $dbParser->parseColumnName($condition->attrs->default); } diff --git a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php index 1d17ea1e3..983f0e1fd 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php @@ -16,9 +16,9 @@ if(!is_array($xml_groups)) $xml_groups = array($xml_groups); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php'); foreach($xml_groups as $group){ - $this->condition_groups[] = new ConditionGroupTag($group->condition, $group->pipe); + $this->condition_groups[] = new ConditionGroupTag($group->condition, $group->attrs->pipe); } - } + } } function toString(){ diff --git a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php index 87fa9d064..c37f94652 100644 --- a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php @@ -38,6 +38,10 @@ $output .= ')'; return $output; } + + function getLimitString(){ + + } function getArguments(){ $arguments = array(); diff --git a/modules/opage/queries/getOpageList.xml b/modules/opage/queries/getOpageList.xml index 1703e5d4d..ceef2a03e 100644 --- a/modules/opage/queries/getOpageList.xml +++ b/modules/opage/queries/getOpageList.xml @@ -9,7 +9,7 @@ - + From 750733936bb866ebc4a8068c005ffcb8d059672b Mon Sep 17 00:00:00 2001 From: mosmartin Date: Wed, 25 May 2011 11:32:54 +0000 Subject: [PATCH 15/82] add "limit" navigation control to xml query and db classes git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8395 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 2 ++ classes/db/DBCubrid.class.php | 10 ++++--- classes/db/queryparts/limit/Limit.class.php | 16 +++++++++++ classes/xml/xmlquery/QueryParser.class.php | 7 ++--- .../tags/navigation/LimitTag.class.php | 27 +++++++++++++++++++ .../tags/navigation/NavigationTag.class.php | 11 ++++++-- 6 files changed, 65 insertions(+), 8 deletions(-) create mode 100644 classes/db/queryparts/limit/Limit.class.php create mode 100644 classes/xml/xmlquery/tags/navigation/LimitTag.class.php diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 71dc76e34..1e4785941 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -316,6 +316,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/argument/ConditionArgument.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/SelectExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/InsertExpression.class.php'); @@ -326,6 +327,7 @@ require_once(_XE_PATH_.'classes/db/queryparts/condition/Condition.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/StarExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/order/OrderByColumn.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php'); $output = include($cache_file); diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 4193f8270..54aca4125 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -795,9 +795,13 @@ } $orderBy = substr($orderBy, 0, -2); } - - - $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; + $limit = ''; + if(count($output->limit) > 0){ + $limit = 'limit '; + $limit .= $output->limit->toString(); + } + + $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; //$query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, //$groupby_query.$orderby_query); //$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; diff --git a/classes/db/queryparts/limit/Limit.class.php b/classes/db/queryparts/limit/Limit.class.php new file mode 100644 index 000000000..fc20d3fbe --- /dev/null +++ b/classes/db/queryparts/limit/Limit.class.php @@ -0,0 +1,16 @@ +start = ($page-1)*$list_count; + $this->end = $list_count; + } + + function toString(){ + return $this->start . ' , ' . $this->end; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 805140fe5..20dd541d3 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -131,9 +131,10 @@ class QueryParser { $buff .= '$output->columns = ' . $columns->toString() . ';'.PHP_EOL; $buff .= '$output->tables = ' . $tables->toString() .';'.PHP_EOL; $buff .= '$output->conditions = '.$conditions->toString() .';'.PHP_EOL; - $buff .= '$output->groups = ' . $groups->toString() . ';'; - $buff .= '$output->orderby = ' . $navigation->getOrderByString() .';'; - + $buff .= '$output->groups = ' . $groups->toString() . ';'; + $buff .= '$output->orderby = ' . $navigation->getOrderByString() .';'; + $buff .= $navigation->getLimitString()?'$output->limit = ' . $navigation->getLimitString() .';':""; + return "query_id = "%s";%s', $this->query_id, "\n") . sprintf('$output->action = "%s";%s', $this->action, "\n") diff --git a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php new file mode 100644 index 000000000..52b81b8d0 --- /dev/null +++ b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php @@ -0,0 +1,27 @@ +page = $index->page->attrs; + $this->page_count = $index->page_count->attrs; + $this->list_count = $index->list_count->attrs; + + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + $this->arguments[] = new QueryArgument($index->page); + $this->arguments[] = new QueryArgument($index->list_count); + } + + function toString(){ + return sprintf("new Limit(\$%s_argument->getValue(), \$%s_argument->getValue())", $this->page->var, $this->list_count->var); + } + + function getArguments(){ + return $this->arguments; + } + } +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php index c37f94652..7edf8d519 100644 --- a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php @@ -1,11 +1,13 @@ order = array(); @@ -17,7 +19,10 @@ $this->order[] = new IndexTag($order_info); } } - + + if($xml_navigation->page->attrs && $xml_navigation->list_count->attrs) + $this->limit = new LimitTag($xml_navigation); + $list_count = $xml_navigation->list_count->attrs; $this->list_count = $list_count; @@ -40,7 +45,8 @@ } function getLimitString(){ - + if ($this->limit) return $this->limit->toString(); + else return ""; } function getArguments(){ @@ -48,6 +54,7 @@ foreach($this->order as $order){ $arguments = array_merge($order->getArguments(), $arguments); } + if($this->limit) $arguments = array_merge($this->limit->getArguments(), $arguments); return $arguments; } } From 0b78e26357f39d3e64eaaf173d073b932d7400c5 Mon Sep 17 00:00:00 2001 From: mosmartin Date: Fri, 27 May 2011 11:39:45 +0000 Subject: [PATCH 16/82] Fix condition/ConditionGroup.class.php when all conditions have no value. Add page navigation mechanism. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8399 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 54 +++++++++++++++++-- .../condition/ConditionGroup.class.php | 2 + classes/db/queryparts/limit/Limit.class.php | 18 +++++-- .../tags/navigation/LimitTag.class.php | 3 +- 4 files changed, 66 insertions(+), 11 deletions(-) diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 54aca4125..04a86c357 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -802,15 +802,59 @@ } $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; - + //$query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, //$groupby_query.$orderby_query); //$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result = $this->_query ($query); - if ($this->isError ()) return; - $data = $this->_fetch ($result); + if ($this->isError ()) { + if ($limit && $output->limit->isPageHandler()){ + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + }else return; + } - $buff = new Object (); - $buff->data = $data; + if ($limit && $output->limit->isPageHandler()) { + $count_query = sprintf('select count(*) as "count" %s %s', $from, $where); + if (count($output->groups)) { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } + + //$count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result_count = $this->_query($count_query); + $count_output = $this->_fetch($result_count); + $total_count = (int)$count_output->count; + + // total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $output->limit->list_count) + 1; + } else $total_page = 1; + + $virtual_no = $total_count - ($output->limit->page - 1) * $output->limit->list_count; + while ($tmp = cubrid_fetch ($result, CUBRID_OBJECT)) { + if ($tmp) { + foreach ($tmp as $k => $v) { + $tmp->{$k} = rtrim($v); + } + } + $data[$virtual_no--] = $tmp; + } + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $output->limit->page; + $buff->data = $data; + $buff->page_navigation = new PageHandler ($total_count, $total_page, $output->limit->page, $output->limit->page_count); + }else{ + $data = $this->_fetch ($result); + $buff = new Object (); + $buff->data = $data; + } return $buff; } diff --git a/classes/db/queryparts/condition/ConditionGroup.class.php b/classes/db/queryparts/condition/ConditionGroup.class.php index 5e9a943b9..cab975d7d 100644 --- a/classes/db/queryparts/condition/ConditionGroup.class.php +++ b/classes/db/queryparts/condition/ConditionGroup.class.php @@ -23,6 +23,8 @@ $cond_indx++; } } + // If the group has no conditions in it, return '' + if($cond_indx === 0) return ''; if($this->pipe !== "") $group .= ')'; diff --git a/classes/db/queryparts/limit/Limit.class.php b/classes/db/queryparts/limit/Limit.class.php index fc20d3fbe..46090ddff 100644 --- a/classes/db/queryparts/limit/Limit.class.php +++ b/classes/db/queryparts/limit/Limit.class.php @@ -1,15 +1,23 @@ start = ($page-1)*$list_count; - $this->end = $list_count; + $this->list_count = $list_count; + $this->page_count = $page_count; + $this->page = $page; + } + + function isPageHandler(){//in case you choose to use query limit in other cases than page select + return true; } function toString(){ - return $this->start . ' , ' . $this->end; + return $this->start . ' , ' . $this->list_count; } } diff --git a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php index 52b81b8d0..a6d2734ae 100644 --- a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php @@ -14,10 +14,11 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->arguments[] = new QueryArgument($index->page); $this->arguments[] = new QueryArgument($index->list_count); + $this->arguments[] = new QueryArgument($index->page_count); } function toString(){ - return sprintf("new Limit(\$%s_argument->getValue(), \$%s_argument->getValue())", $this->page->var, $this->list_count->var); + return sprintf("new Limit(\$%s_argument->getValue(), \$%s_argument->getValue(), \$%s_argument->getValue())", $this->page->var, $this->list_count->var, $this->page_count->var); } function getArguments(){ From 64d268ab6b510f5e2531917eb8593d8eab7a1e9a Mon Sep 17 00:00:00 2001 From: mosmartin Date: Fri, 27 May 2011 12:25:43 +0000 Subject: [PATCH 17/82] Added a wrapper for queries - select can now be called like: $query->select(..)->from(..)->where(..) git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8400 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/Query.class.php | 124 ++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 classes/db/queryparts/Query.class.php diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php new file mode 100644 index 000000000..a0fb13e09 --- /dev/null +++ b/classes/db/queryparts/Query.class.php @@ -0,0 +1,124 @@ +action = 'select'; + if(!isset($columns) || count($columns) === 0){ + $this->columns = array(new StarExpression()); + return $this; + } + + if(!is_array($columns)) $columns = array($columns); + + $this->columns = $columns; + return $this; + } + + function from($tables){ + if(!isset($tables) || count($tables) === 0){ + $this->setError(true); + $this->setMessage("You must provide at least one table for the query."); + return $this; + } + + if(!is_array($tables)) $tables = array($tables); + + $this->tables = $tables; + return $this; + } + + function where($conditions){ + if(!isset($conditions) || count($conditions) === 0) return $this; + if(!is_array($conditions)) $conditions = array($conditions); + + $this->conditions = $conditions; + return $this; + } + + function groupBy($groups){ + if(!isset($groups) || count($groups) === 0) return $this; + if(!is_array($groups)) $groups = array($groups); + + $this->groups = $groups; + return $this; + } + + function orderBy($order){ + if(!isset($order) || count($order) === 0) return $this; + if(!is_array($order)) $order = array($order); + + $this->orderby = $order; + return $this; + } + + function limit($limit){ + if(!isset($limit)) return $this; + $this->limit = $limit; + return $this; + } + + function getSql(){ + if($this->action == 'select') return $this->getSelectSql(); + } + + function getSelectSql(){ + $query = ''; + + $select = 'SELECT '; + foreach($this->columns as $column){ + if($column->show()) + $select .= $column->getExpression() . ', '; + } + $select = substr($select, 0, -2); + + $from = 'FROM '; + $simple_table_count = 0; + foreach($this->tables as $table){ + if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; + else $from .= ', '.$table->toString() . ' '; + $simple_table_count++; + } + + $where = ''; + if(count($this->conditions) > 0){ + $where = 'WHERE '; + foreach($this->conditions as $conditionGroup){ + $where .= $conditionGroup->toString(); + } + } + + $groupBy = ''; + if($this->groups) if($this->groups[0] !== "") + $groupBy = 'GROUP BY ' . implode(', ', $this->groups); + + $orderBy = ''; + if(count($this->orderby) > 0){ + $orderBy = 'ORDER BY '; + foreach($this->orderby as $order){ + $orderBy .= $order->toString() .', '; + } + $orderBy = substr($orderBy, 0, -2); + } + $limit = ''; + if(count($this->limit) > 0){ + $limit = 'limit '; + $limit .= $this->limit->toString(); + } + + $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; + return $query; + + } + } + + + +?> \ No newline at end of file From 68f068cf886f4d83ffc2afc4d526a0bee4f606ed Mon Sep 17 00:00:00 2001 From: mosmartin Date: Mon, 30 May 2011 13:20:28 +0000 Subject: [PATCH 18/82] fix query "limit" tag in other cases than page select git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8409 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/limit/Limit.class.php | 17 ++++++++++------- .../tags/navigation/LimitTag.class.php | 18 +++++++++++------- .../tags/navigation/NavigationTag.class.php | 2 +- 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/classes/db/queryparts/limit/Limit.class.php b/classes/db/queryparts/limit/Limit.class.php index 46090ddff..fd8147e47 100644 --- a/classes/db/queryparts/limit/Limit.class.php +++ b/classes/db/queryparts/limit/Limit.class.php @@ -5,20 +5,23 @@ var $page_count; var $page; - function Limit($page, $list_count, $page_count){ - $this->start = ($page-1)*$list_count; + function Limit($list_count, $page= NULL, $page_count= NULL){ $this->list_count = $list_count; - $this->page_count = $page_count; - $this->page = $page; + if ($page){ + $this->start = ($page-1)*$list_count; + $this->page_count = $page_count; + $this->page = $page; + } } function isPageHandler(){//in case you choose to use query limit in other cases than page select - return true; + if ($this->page)return true; + else return false; } function toString(){ - return $this->start . ' , ' . $this->list_count; + if ($this->page) return $this->start . ' , ' . $this->list_count; + else return $this->list_count; } } - ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php index a6d2734ae..68a006946 100644 --- a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php @@ -7,18 +7,22 @@ var $list_count; function LimitTag($index){ - $this->page = $index->page->attrs; - $this->page_count = $index->page_count->attrs; - $this->list_count = $index->list_count->attrs; - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - $this->arguments[] = new QueryArgument($index->page); + + if($index->page->attrs && $index->page_count->attrs){ + $this->page = $index->page->attrs; + $this->page_count = $index->page_count->attrs; + $this->arguments[] = new QueryArgument($index->page); + $this->arguments[] = new QueryArgument($index->page_count); + } + + $this->list_count = $index->list_count->attrs; $this->arguments[] = new QueryArgument($index->list_count); - $this->arguments[] = new QueryArgument($index->page_count); } function toString(){ - return sprintf("new Limit(\$%s_argument->getValue(), \$%s_argument->getValue(), \$%s_argument->getValue())", $this->page->var, $this->list_count->var, $this->page_count->var); + if ($this->page)return sprintf("new Limit(\$%s_argument->getValue(), \$%s_argument->getValue(), \$%s_argument->getValue())",$this->list_count->var, $this->page->var, $this->page_count->var); + else return sprintf("new Limit(\$%s_argument->getValue())", $this->list_count->var); } function getArguments(){ diff --git a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php index 7edf8d519..1c364643e 100644 --- a/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/NavigationTag.class.php @@ -20,7 +20,7 @@ } } - if($xml_navigation->page->attrs && $xml_navigation->list_count->attrs) + if($xml_navigation->page->attrs || $xml_navigation->list_count->attrs) $this->limit = new LimitTag($xml_navigation); $list_count = $xml_navigation->list_count->attrs; From b4ca6896bcdb8e8b2e98787ab5741abba49eaecc Mon Sep 17 00:00:00 2001 From: ucorina Date: Wed, 1 Jun 2011 10:19:58 +0000 Subject: [PATCH 19/82] Removed code for creating final SELECT statement - this will be moved to db classes. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8425 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/Query.class.php | 49 --------------------------- 1 file changed, 49 deletions(-) diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index a0fb13e09..dd0fa3089 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -68,55 +68,6 @@ function getSql(){ if($this->action == 'select') return $this->getSelectSql(); } - - function getSelectSql(){ - $query = ''; - - $select = 'SELECT '; - foreach($this->columns as $column){ - if($column->show()) - $select .= $column->getExpression() . ', '; - } - $select = substr($select, 0, -2); - - $from = 'FROM '; - $simple_table_count = 0; - foreach($this->tables as $table){ - if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; - else $from .= ', '.$table->toString() . ' '; - $simple_table_count++; - } - - $where = ''; - if(count($this->conditions) > 0){ - $where = 'WHERE '; - foreach($this->conditions as $conditionGroup){ - $where .= $conditionGroup->toString(); - } - } - - $groupBy = ''; - if($this->groups) if($this->groups[0] !== "") - $groupBy = 'GROUP BY ' . implode(', ', $this->groups); - - $orderBy = ''; - if(count($this->orderby) > 0){ - $orderBy = 'ORDER BY '; - foreach($this->orderby as $order){ - $orderBy .= $order->toString() .', '; - } - $orderBy = substr($orderBy, 0, -2); - } - $limit = ''; - if(count($this->limit) > 0){ - $limit = 'limit '; - $limit .= $this->limit->toString(); - } - - $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; - return $query; - - } } From 23e991bec0f2dd70ae934ad28562ec4aa864fc58 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Wed, 1 Jun 2011 12:51:13 +0000 Subject: [PATCH 20/82] Bug fixes: DBCubrid.class.php - remove "WHERE" clause when all conditions are empty queryargument/QueryArgument.class.php and queryargument/validator/QueryArgumentValidator.class.php - this is for backwords compatibility - there are many xml files that have variable names (var) given with "." table/TableTag.class.php - autocomplete default table name alias with table name. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8426 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 2 +- .../xml/xmlquery/queryargument/QueryArgument.class.php | 8 +++++--- .../validator/QueryArgumentValidator.class.php | 10 ++++++---- .../xml/xmlquery/tags/condition/ConditionTag.class.php | 1 + classes/xml/xmlquery/tags/table/TableTag.class.php | 1 + 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 04a86c357..804870a43 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -777,10 +777,10 @@ $where = ''; if(count($output->conditions) > 0){ - $where = 'WHERE '; foreach($output->conditions as $conditionGroup){ $where .= $conditionGroup->toString(); } + if(trim($where) != '') $where = 'WHERE ' . $where; } $groupBy = ''; diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index e4dfbe7ab..cd4b23b41 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -8,12 +8,14 @@ var $ignoreValue; function QueryArgument($tag){ - $this->argument_name = $tag->attrs->var; + // HACK (this is for backwords compatibility - there are many xml files that have variable names (var) given with .) + // eg. var = point.memeber_srl (getMemberList query from point module) + $this->argument_name = str_replace('.', '_',$tag->attrs->var); if(!$this->argument_name) $this->ignoreValue = true; else $this->ignoreValue = false; if(!$this->argument_name) $this->argument_name = $tag->attrs->name; - if(!$this->argument_name) $this->argument_name = $tag->attrs->column; + if(!$this->argument_name) $this->argument_name = str_replace('.', '_',$tag->attrs->column); $name = $tag->attrs->name; if(!$name) $name = $tag->attrs->column; @@ -26,7 +28,7 @@ if($tag->attrs->operation) $this->operation = $tag->attrs->operation; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); - $this->argument_validator = new QueryArgumentValidator($tag); + $this->argument_validator = new QueryArgumentValidator($tag, $this); } diff --git a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php index 9c4d478df..c51578d0e 100644 --- a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php +++ b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php @@ -11,10 +11,12 @@ var $validator_string; - function QueryArgumentValidator($tag){ - $this->argument_name = $tag->attrs->var; - if(!$this->argument_name) $this->argument_name = $tag->attrs->name; - if(!$this->argument_name) $this->argument_name = $tag->attrs->column; + var $argument; + + function QueryArgumentValidator($tag, $argument){ + $this->argument = $argument; + $this->argument_name = $this->argument->getArgumentName(); + $this->default_value = $tag->attrs->default; $this->notnull = $tag->attrs->notnull; $this->filter = $tag->attrs->filter; diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index aed904eff..3f25da9fa 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -27,6 +27,7 @@ if($condition->attrs->var || $isColumnName === false){ require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); //$this->argument_name = $condition->attrs->var; + $this->argument = new QueryArgument($condition); $this->argument_name = $this->argument->getArgumentName(); } diff --git a/classes/xml/xmlquery/tags/table/TableTag.class.php b/classes/xml/xmlquery/tags/table/TableTag.class.php index 3f432770d..3d5407f18 100644 --- a/classes/xml/xmlquery/tags/table/TableTag.class.php +++ b/classes/xml/xmlquery/tags/table/TableTag.class.php @@ -22,6 +22,7 @@ $dbParser = XmlQueryParser::getDBParser(); $this->name = $dbParser->parseTableName($table->attrs->name); $this->alias = $table->attrs->alias; + if(!$this->alias) $this->alias = $table->attrs->name; //if(!$this->alias) $this->alias = $alias; $this->join_type = $table->attrs->type; From c384f6c753f191972762fbc3c7ffda676f4494a6 Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 2 Jun 2011 13:04:22 +0000 Subject: [PATCH 21/82] Fix for XE Core: added code to create document module "is_secret" column if it didn't exist. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8437 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- modules/document/document.class.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/modules/document/document.class.php b/modules/document/document.class.php index f4cb79912..c2595226e 100644 --- a/modules/document/document.class.php +++ b/modules/document/document.class.php @@ -102,6 +102,8 @@ //2011. 04. 07 adding description column to document categories if(!$oDB->isColumnExists("document_categories","description")) return true; + // 2011.06.01 Bug fix: is_secret column had no update coede + if(!$oDB->isColumnExists("documents","is_secret")) return true; return false; } @@ -237,6 +239,9 @@ //2011. 04. 07 adding description column to document categories if(!$oDB->isColumnExists("document_categories","description")) $oDB->addColumn('document_categories',"description","varchar",200,0); + // 2011.06.01 Bug fix: Add is_secret column if it does not exist + if(!$oDB->isColumnExists("documents","is_secret")) $oDB->addColumn('documents',"is_secret","char",1,0); + return new Object(0,'success_updated'); } From 0cd318fcf5b16c5444c9819bd700b6066511bbfc Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 2 Jun 2011 13:06:08 +0000 Subject: [PATCH 22/82] Removed legacy methods from DB and DBCubrid classes. Added Query object to hold together query parts. Updated structure of query cache file to return Query object. Added support for array query arguments - used in the IN clause. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8438 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 267 +------- classes/db/DBCubrid.class.php | 616 +----------------- classes/db/queryparts/Query.class.php | 158 ++++- classes/xml/xmlquery/QueryParser.class.php | 20 +- .../xml/xmlquery/argument/Argument.class.php | 14 +- .../argument/ConditionArgument.class.php | 13 + .../queryargument/DefaultValue.class.php | 6 + .../queryargument/QueryArgument.class.php | 5 + .../QueryArgumentValidator.class.php | 2 +- 9 files changed, 210 insertions(+), 891 deletions(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 1e4785941..4ba22ddbc 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -17,17 +17,6 @@ var $count_cache_path = 'files/cache/db'; - var $cond_operation = array( ///< operations for condition - 'equal' => '=', - 'more' => '>=', - 'excess' => '>', - 'less' => '<=', - 'below' => '<', - 'notequal' => '<>', - 'notnull' => 'is not null', - 'null' => 'is null', - ); - var $fd = NULL; ///< connector resource or file description var $result = NULL; ///< result @@ -328,15 +317,15 @@ require_once(_XE_PATH_.'classes/db/queryparts/expression/StarExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/order/OrderByColumn.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/Query.class.php'); $output = include($cache_file); if( (is_a($output, 'Object') || is_subclass_of($output, 'Object')) && !$output->toBool()) return $output; - $output->_tables = ($output->_tables && is_array($output->_tables)) ? $output->_tables : array(); // execute appropriate query - switch($output->action) { + switch($output->getAction()) { case 'insert' : $this->resetCountCache($output->tables); $output = $this->_executeInsertAct($output); @@ -350,6 +339,7 @@ $output = $this->_executeDeleteAct($output); break; case 'select' : + // TODO Add property for Query object for Arg_columns $output->arg_columns = is_array($arg_columns)?$arg_columns:array(); $output = $this->_executeSelectAct($output); break; @@ -363,232 +353,6 @@ return $output; } - /** - * @brief check $val with $filter_type - * @param[in] $key key value - * @param[in] $val value of $key - * @param[in] $filter_type type of filter to check $val - * @return object - * @remarks this function is to be used from XmlQueryParser - **/ - function checkFilter($key, $val, $filter_type) { - global $lang; - - switch($filter_type) { - case 'email' : - case 'email_address' : - if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) return new Object(-1, sprintf($lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key)); - break; - case 'homepage' : - if(!preg_match('/^(http|https)+(:\/\/)+[0-9a-z_-]+\.[^ ]+$/is', $val)) return new Object(-1, sprintf($lang->filter->invalid_homepage, $lang->{$key} ? $lang->{$key} : $key)); - break; - case 'userid' : - case 'user_id' : - if(!preg_match('/^[a-zA-Z]+([_0-9a-zA-Z]+)*$/is', $val)) return new Object(-1, sprintf($lang->filter->invalid_userid, $lang->{$key} ? $lang->{$key} : $key)); - break; - case 'number' : - case 'numbers' : - if(is_array($val)) $val = join(',', $val); - if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)) return new Object(-1, sprintf($lang->filter->invalid_number, $lang->{$key} ? $lang->{$key} : $key)); - break; - case 'alpha' : - if(!preg_match('/^[a-z]+$/is', $val)) return new Object(-1, sprintf($lang->filter->invalid_alpha, $lang->{$key} ? $lang->{$key} : $key)); - break; - case 'alpha_number' : - if(!preg_match('/^[0-9a-z]+$/is', $val)) return new Object(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key)); - break; - } - - return new Object(); - } - - /** - * @brief returns type of column - * @param[in] $column_type_list list of column type - * @param[in] $name name of column type - * @return column type of $name - * @remarks columns are usually like a.b, so it needs another function - **/ - function getColumnType($column_type_list, $name) { - if(strpos($name, '.') === false) return $column_type_list[$name]; - list($prefix, $name) = explode('.', $name); - return $column_type_list[$name]; - } - - /** - * @brief returns the value of condition - * @param[in] $name name of condition - * @param[in] $value value of condition - * @param[in] $operation operation this is used in condition - * @param[in] $type type of condition - * @param[in] $column_type type of column - * @return well modified $value - * @remarks if $operation is like or like_prefix, $value itself will be modified - * @remarks if $type is not 'number', call addQuotes() and wrap with ' ' - **/ - function getConditionValue($name, $value, $operation, $type, $column_type) { - if(!in_array($operation,array('in','notin','between')) && $type == 'number') { - if(is_array($value)){ - $value = join(',',$value); - } - if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; - return $value; - } - - if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { - list($table_name, $column_name) = explode('.', $value); - if($column_type[$column_name]) return $value; - } - - switch($operation) { - case 'like_prefix' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = $value.'%'; - break; - case 'like_tail' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value; - break; - case 'like' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value.'%'; - break; - case 'notin' : - if(is_array($value)) - { - $value = $this->addQuotesArray($value); - if($type=='number') return join(',',$value); - else return "'". join("','",$value)."'"; - } - else - { - return $value; - } - break; - case 'in' : - if(is_array($value)) - { - $value = $this->addQuotesArray($value); - if($type=='number') return join(',',$value); - else return "'". join("','",$value)."'"; - } - else - { - return $value; - } - break; - case 'between' : - if(!is_array($value)) $value = array($value); - $value = $this->addQuotesArray($value); - if($type!='number') - { - foreach($value as $k=>$v) - { - $value[$k] = "'".$v."'"; - } - } - - return $value; - break; - default: - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - } - - return "'".$this->addQuotes($value)."'"; - } - - /** - * @brief returns part of condition - * @param[in] $name name of condition - * @param[in] $value value of condition - * @param[in] $operation operation that is used in condition - * @return detail condition - **/ - function getConditionPart($name, $value, $operation) { - switch($operation) { - case 'equal' : - case 'more' : - case 'excess' : - case 'less' : - case 'below' : - case 'like_tail' : - case 'like_prefix' : - case 'like' : - case 'in' : - case 'notin' : - case 'notequal' : - // if variable is not set or is not string or number, return - if(!isset($value)) return; - if($value === '') return; - if(!in_array(gettype($value), array('string', 'integer'))) return; - break; - case 'between' : - if(!is_array($value)) return; - if(count($value)!=2) return; - - } - - switch($operation) { - case 'equal' : - return $name.' = '.$value; - break; - case 'more' : - return $name.' >= '.$value; - break; - case 'excess' : - return $name.' > '.$value; - break; - case 'less' : - return $name.' <= '.$value; - break; - case 'below' : - return $name.' < '.$value; - break; - case 'like_tail' : - case 'like_prefix' : - case 'like' : - return $name.' like '.$value; - break; - case 'in' : - return $name.' in ('.$value.')'; - break; - case 'notin' : - return $name.' not in ('.$value.')'; - break; - case 'notequal' : - return $name.' <> '.$value; - break; - case 'notnull' : - return $name.' is not null'; - break; - case 'null' : - return $name.' is null'; - break; - case 'between' : - return $name.' between ' . $value[0] . ' and ' . $value[1]; - break; - } - } - - /** - * @brief returns condition key - * @param[in] $output result of query - * @return array of conditions of $output - **/ - function getConditionList($output) { - $conditions = array(); - if(count($output->conditions)) { - foreach($output->conditions as $key => $val) { - if($val['condition']) { - foreach($val['condition'] as $k => $v) { - $conditions[] = $v['column']; - } - } - } - } - - return $conditions; - } /** * @brief returns counter cache data @@ -693,30 +457,5 @@ $this->_query($query); } - function addQuotesArray($arr) - { - if(is_array($arr)) - { - foreach($arr as $k => $v) - { - $arr[$k] = $this->addQuotes($v); - } - } - else - { - $arr = $this->addQuotes($arr); - } - - return $arr; - } - - /** - * @brief Just like numbers, and operations needed to remove the rest - **/ - function _filterNumber(&$value) - { - $value = preg_replace('/[^\d\w\+\-\*\/\.\(\)]/', '', $value); - if(!$value) $value = 0; - } } ?> diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 804870a43..7b5541b91 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -121,6 +121,7 @@ /** * @brief handles quatation of the string variables from the query **/ + // TODO Make sure this is handled in DBParser class function addQuotes($string) { if (!$this->fd) return $string; @@ -561,97 +562,11 @@ } } - /** - * @brief return the condition - **/ - function getCondition ($output) - { - if (!$output->conditions) return; - $condition = $this->_getCondition ($output->conditions, $output->column_type, $output); - if ($condition) $condition = ' where '.$condition; - - return $condition; - } - - function _getCondition ($conditions, $column_type, &$output) - { - $condition = ''; - - foreach ($conditions as $val) { - $sub_condition = ''; - - foreach ($val['condition'] as $v) { - if (!isset ($v['value'])) continue; - if ($v['value'] === '') continue; - if(!in_array(gettype($v['value']), array('string', 'integer', 'double', 'array'))) continue; - - $name = $v['column']; - $operation = $v['operation']; - $value = $v['value']; - $type = $this->getColumnType ($column_type, $name); - $pipe = $v['pipe']; - $value = $this->getConditionValue ($name, $value, $operation, $type, $column_type); - - if (!$value) { - $value = $v['value']; - if (strpos ($value, '(')) { - $valuetmp = $value; - } - elseif (strpos ($value, ".") === false) { - $valuetmp = $value; - } - else { - $valuetmp = '"'.str_replace('.', '"."', $value).'"'; - } - } - else { - $tmp = explode('.',$value); - - if (count($tmp)==2) { - $table = $tmp[0]; - $column = $tmp[1]; - - if ($column_type[$column] && (in_array ($table, $output->tables) || - array_key_exists($table, $output->tables))) { - $valuetmp = sprintf('"%s"."%s"', $table, $column); - } - else { - $valuetmp = $value; - } - } - else { - $valuetmp = $value; - } - } - - if (strpos ($name, '(') > 0) { - $nametmp = $name; - } - elseif (strpos ($name, ".") === false) { - $nametmp = '"'.$name.'"'; - } - else { - $nametmp = '"'.str_replace('.', '"."', $name).'"'; - } - $str = $this->getConditionPart ($nametmp, $valuetmp, $operation); - if ($sub_condition) $sub_condition .= ' '.$pipe.' '; - $sub_condition .= $str; - } - - if ($sub_condition) { - if ($condition && $val['pipe']) { - $condition .= ' '.$val['pipe'].' '; - } - $condition .= '('.$sub_condition.')'; - } - } - - return $condition; - } /** * @brief handles insertAct **/ + // TODO Rewrite with Query object as input function _executeInsertAct ($output) { $query = ''; @@ -683,6 +598,7 @@ /** * @brief handles updateAct **/ + // TODO Rewrite with Query object as input function _executeUpdateAct ($output) { $query = ''; @@ -717,6 +633,7 @@ /** * @brief handles deleteAct **/ + // TODO Rewrite with Query object as input function _executeDeleteAct ($output) { $query = ''; @@ -746,62 +663,40 @@ return $result; } + + function getSelectSql($query){ + $select = $query->getSelect(); + if($select == '') return new Object(-1, "Invalid query"); + $select = 'SELECT ' .$select; + + $from = $query->getFrom(); + if($from == '') return new Object(-1, "Invalid query"); + $from = ' FROM '.$from; + + $where = $query->getWhere(); + if($where != '') $where = ' WHERE ' . $where; + + $groupBy = $query->getGroupBy(); + if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; + + $orderBy = $query->getOrderBy(); + if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; + + $limit = $query->getLimit(); + if($limit != '') $limit = ' LIMIT ' . $limit; + + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; + } + /** * @brief Handle selectAct * * to get a specific page list easily in select statement,\n * a method, navigation, is used **/ - function _executeSelectAct($output){ - $query = ''; - - $select = 'SELECT '; - foreach($output->columns as $column){ - if($column->show()) - $select .= $column->getExpression() . ', '; - } - $select = substr($select, 0, -2); - - $from = 'FROM '; - $simple_table_count = 0; - foreach($output->tables as $table){ - /*if($simple_table_count > 0) $from .= ', '; - - $from .= $table->toString() . ' '; - if(!$table->isJoinTable()) $simple_table_count++; - */ - if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; - else $from .= ', '.$table->toString() . ' '; - $simple_table_count++; - } - - $where = ''; - if(count($output->conditions) > 0){ - foreach($output->conditions as $conditionGroup){ - $where .= $conditionGroup->toString(); - } - if(trim($where) != '') $where = 'WHERE ' . $where; - } - - $groupBy = ''; - if($output->groups) if($output->groups[0] !== "") - $groupBy = 'GROUP BY ' . implode(', ', $output->groups); - - $orderBy = ''; - if(count($output->orderby) > 0){ - $orderBy = 'ORDER BY '; - foreach($output->orderby as $order){ - $orderBy .= $order->toString() .', '; - } - $orderBy = substr($orderBy, 0, -2); - } - $limit = ''; - if(count($output->limit) > 0){ - $limit = 'limit '; - $limit .= $output->limit->toString(); - } - - $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; + // TODO Rewrite with Query object as input + function _executeSelectAct($queryObject){ + $query = $this->getSelectSql($queryObject); //$query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, //$groupby_query.$orderby_query); //$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; @@ -856,453 +751,6 @@ $buff->data = $data; } - return $buff; - } - /*function _executeSelectAct ($output) - { - // tables - $table_list = array (); - foreach ($output->tables as $key => $val) { - $table_list[] = '"'.$this->prefix.$val.'" as "'.$key.'"'; - } - $left_join = array (); - // why??? - $left_tables = (array) $output->left_tables; - - foreach ($left_tables as $key => $val) { - $condition = $this->_getCondition ($output->left_conditions[$key], $output->column_type, $output); - if ($condition) { - $left_join[] = $val.' "'.$this->prefix.$output->_tables[$key]. '" "'.$key.'" on ('.$condition.')'; - } - } - - $click_count = array(); - if(!$output->columns){ - $output->columns = array(array('name'=>'*')); - } - - $column_list = array (); - foreach ($output->columns as $key => $val) { - $name = $val['name']; - - $click_count = '%s'; - if ($val['click_count'] && count ($output->conditions) > 0) { - $click_count = 'incr(%s)'; - } - - $alias = $val['alias'] ? sprintf ('"%s"', $val['alias']) : null; - $_alias = $val['alias']; - - if ($name == '*') { - $column_list[] = $name; - } - elseif (strpos ($name, '.') === false && strpos ($name, '(') === false) { - $name = sprintf ($click_count,$name); - if ($alias) { - $column_list[$alias] = sprintf('"%s" as %s', $name, $alias); - } - else { - $column_list[] = sprintf ('"%s"', $name); - } - } - else { - if (strpos ($name, '.') != false) { - list ($prefix, $name) = explode('.', $name); - if (($now_matchs = preg_match_all ("/\(/", $prefix, $xtmp)) > 0) { - if ($now_matchs == 1) { - $tmpval = explode ("(", $prefix); - $tmpval[1] = sprintf ('"%s"', $tmpval[1]); - $prefix = implode ("(", $tmpval); - $tmpval = explode (")", $name); - $tmpval[0] = sprintf ('"%s"', $tmpval[0]); - $name = implode (")", $tmpval); - } - } - else { - $prefix = sprintf ('"%s"', $prefix); - $name = ($name == '*') ? $name : sprintf('"%s"',$name); - } - $xtmp = null; - $now_matchs = null; - if($alias) $column_list[$_alias] = sprintf ($click_count, sprintf ('%s.%s', $prefix, $name)) . ($alias ? sprintf (' as %s',$alias) : ''); - else $column_list[] = sprintf ($click_count, sprintf ('%s.%s', $prefix, $name)); - } - elseif (($now_matchs = preg_match_all ("/\(/", $name, $xtmp)) > 0) { - if ($now_matchs == 1 && preg_match ("/[a-zA-Z0-9]*\(\*\)/", $name) < 1) { - $open_pos = strpos ($name, "("); - $close_pos = strpos ($name, ")"); - - if (preg_match ("/,/", $name)) { - $tmp_func_name = sprintf ('%s', substr ($name, 0, $open_pos)); - $tmp_params = sprintf ('%s', substr ($name, $open_pos + 1, $close_pos - $open_pos - 1)); - $tmpval = null; - $tmpval = explode (',', $tmp_params); - - foreach ($tmpval as $tmp_param) { - $tmp_param_list[] = (!is_numeric ($tmp_param)) ? sprintf ('"%s"', $tmp_param) : $tmp_param; - } - - $tmpval = implode (',', $tmp_param_list); - $name = sprintf ('%s(%s)', $tmp_func_name, $tmpval); - } - else { - $name = sprintf ('%s("%s")', substr ($name, 0, $open_pos), substr ($name, $open_pos + 1, $close_pos - $open_pos - 1)); - } - } - - if($alias) $column_list[$_alias] = sprintf ($click_count, $name). ($alias ? sprintf (' as %s', $alias) : ''); - else $column_list[] = sprintf ($click_count, $name); - } - else { - if($alias) $column_list[$_alias] = sprintf($click_count, $name). ($alias ? sprintf(' as %s',$alias) : ''); - else $column_list[] = sprintf($click_count, $name); - } - } - $columns = implode (',', $column_list); - } - - $condition = $this->getCondition ($output); - - $output->column_list = $column_list; - if ($output->list_count && $output->page) { - return ($this->_getNavigationData($table_list, $columns, $left_join, $condition, $output)); - } - - if ($output->order) { - $conditions = $this->getConditionList($output); - //if(in_array('list_order', $conditions) || in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if ($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' where %s < 2100000000 ', $col); - } - //} - } - - - if (count ($output->groups)) { - foreach ($output->groups as $key => $value) { - if (strpos ($value, '.')) { - $tmp = explode ('.', $value); - $tmp[0] = sprintf ('"%s"', $tmp[0]); - $tmp[1] = sprintf ('"%s"', $tmp[1]); - $value = implode ('.', $tmp); - } - elseif (strpos ($value, '(')) { - $value = $value; - } - else { - $value = sprintf ('"%s"', $value); - } - $output->groups[$key] = $value; - - - if(count($output->arg_columns)) - { - if($column_list[$value]) $output->arg_columns[] = $column_list[$value]; - } - } - $groupby_query = sprintf ('group by %s', implode(',', $output->groups)); - } - - - // apply when using list_count - if ($output->list_count['value']) { - $start_count = 0; - $list_count = $output->list_count['value']; - - if ($output->order) { - foreach ($output->order as $val) { - if (strpos ($val[0], '.')) { - $tmpval = explode ('.', $val[0]); - $tmpval[0] = sprintf ('"%s"', $tmpval[0]); - $tmpval[1] = sprintf ('"%s"', $tmpval[1]); - $val[0] = implode ('.', $tmpval); - } - elseif (strpos ($val[0], '(')) $val[0] = $val[0]; - elseif ($val[0] == 'count') $val[0] = 'count (*)'; - else $val[0] = sprintf ('"%s"', $val[0]); - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - } - if (count($index_list)) - $orderby_query = ' order by '.implode(',', $index_list); - $orderby_query = sprintf ('%s for orderby_num() between %d and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - else { - if (count ($output->groups)) { - $orderby_query = sprintf ('%s having groupby_num() between %d'. ' and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - else { - if ($condition) { - $orderby_query = sprintf ('%s and inst_num() between %d'. ' and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - else { - $orderby_query = sprintf ('%s where inst_num() between %d'. ' and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - } - } - } - else { - if ($output->order) { - foreach ($output->order as $val) { - if (strpos ($val[0], '.')) { - $tmpval = explode ('.', $val[0]); - $tmpval[0] = sprintf ('"%s"', $tmpval[0]); - $tmpval[1] = sprintf ('"%s"', $tmpval[1]); - $val[0] = implode ('.', $tmpval); - } - elseif (strpos ($val[0], '(')) $val[0] = $val[0]; - elseif ($val[0] == 'count') $val[0] = 'count (*)'; - else $val[0] = sprintf ('"%s"', $val[0]); - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - - if(count($output->arg_columns) && $column_list[$val]) $output->arg_columns[] = $column_list[$key]; - } - - if (count ($index_list)) { - $orderby_query = ' order by '.implode(',', $index_list); - } - } - } - - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - unset($tmpCol); - $tmpCol = explode('.', $col); - if(isset($tmpCol[1])) $col = $tmpCol[1]; - - if(strpos($col,'"')===false && strpos($col,' ')==false) $col = '"'.$col.'"'; - if(isset($tmpCol[1])) $col = $tmpCol[0].'.'.$col; - - $columns[] = $col; - } - - $columns = join(',',$columns); - } - - $query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, $groupby_query.$orderby_query); - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); - if ($this->isError ()) return; - $data = $this->_fetch ($result); - - $buff = new Object (); - $buff->data = $data; - - return $buff; - } - */ - - /** - * @brief displays the current stack trace. Fetch the result - **/ - function backtrace () - { - $output = "
\n"; - $output .= "Backtrace:
\n"; - $backtrace = debug_backtrace (); - - foreach ($backtrace as $bt) { - $args = ''; - foreach ($bt['args'] as $a) { - if (!empty ($args)) { - $args .= ', '; - } - switch (gettype ($a)) { - case 'integer': - case 'double': - $args .= $a; - break; - case 'string': - $a = htmlspecialchars (substr ($a, 0, 64)). - ((strlen ($a) > 64) ? '...' : ''); - $args .= "\"$a\""; - break; - case 'array': - $args .= 'Array ('. count ($a).')'; - break; - case 'object': - $args .= 'Object ('.get_class ($a).')'; - break; - case 'resource': - $args .= 'Resource ('.strstr ($a, '#').')'; - break; - case 'boolean': - $args .= $a ? 'True' : 'False'; - break; - case 'NULL': - $args .= 'Null'; - break; - default: - $args .= 'Unknown'; - } - } - $output .= "
\n"; - $output .= "file: ".$bt['line']." - ". $bt['file']."
\n"; - $output .= "call: ".$bt['class']. $bt['type'].$bt['function'].$args."
\n"; - } - $output .= "
\n"; - return $output; - } - - /** - * @brief paginates when navigation info exists in the query xml - * - * it is convenient although its structure is not good .. -_-; - **/ - function _getNavigationData ($table_list, $columns, $left_join, $condition, $output) { - require_once (_XE_PATH_.'classes/page/PageHandler.class.php'); - - $column_list = $output->column_list; - - $count_condition = count($output->groups) ? sprintf('%s group by %s', $condition, implode(', ', $output->groups)) : $condition; - $count_query = sprintf('select count(*) as "count" from %s %s %s', implode(', ', $table_list), implode(' ', $left_join), $count_condition); - if (count($output->groups)) { - $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); - } - - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query($count_query); - $count_output = $this->_fetch($result); - $total_count = (int)$count_output->count; - - $list_count = $output->list_count['value']; - if (!$list_count) $list_count = 20; - $page_count = $output->page_count['value']; - if (!$page_count) $page_count = 10; - $page = $output->page['value']; - if (!$page) $page = 1; - - // total pages - if ($total_count) { - $total_page = (int) (($total_count - 1) / $list_count) + 1; - } - else { - $total_page = 1; - } - - // check the page variables - if ($page > $total_page) $page = $total_page; - $start_count = ($page - 1) * $list_count; - - if ($output->order) { - $conditions = $this->getConditionList($output); - //if(in_array('list_order', $conditions) || in_array('update_order', $conditions)) { - foreach ($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' where %s < 2100000000 ', $col); - } - //} - } - - - if (count ($output->groups)) { - foreach ($output->groups as $key => $value) { - if (strpos ($value, '.')) { - $tmp = explode ('.', $value); - $tmp[0] = sprintf ('"%s"', $tmp[0]); - $tmp[1] = sprintf ('"%s"', $tmp[1]); - $value = implode ('.', $tmp); - } - elseif (strpos ($value, '(')) $value = $value; - else $value = sprintf ('"%s"', $value); - $output->groups[$key] = $value; - } - - $groupby_query = sprintf (' group by %s', implode (',', $output->groups)); - } - - if ($output->order) { - foreach ($output->order as $val) { - if (strpos ($val[0], '.')) { - $tmpval = explode ('.', $val[0]); - $tmpval[0] = sprintf ('"%s"', $tmpval[0]); - $tmpval[1] = sprintf ('"%s"', $tmpval[1]); - $val[0] = implode ('.', $tmpval); - } - elseif (strpos ($val[0], '(')) $val[0] = $val[0]; - elseif ($val[0] == 'count') $val[0] = 'count (*)'; - else $val[0] = sprintf ('"%s"', $val[0]); - $index_list[] = sprintf ('%s %s', $val[0], $val[1]); - } - - if (count ($index_list)) { - $orderby_query = ' order by '.implode(',', $index_list); - } - - $orderby_query = sprintf ('%s for orderby_num() between %d and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - else { - if (count($output->groups)) { - $orderby_query = sprintf ('%s having groupby_num() between %d and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - else { - if ($condition) { - $orderby_query = sprintf ('%s and inst_num() between %d and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - else { - $orderby_query = sprintf('%s where inst_num() between %d and %d', $orderby_query, $start_count + 1, $list_count + $start_count); - } - } - } - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - unset($tmpCol); - $tmpCol = explode('.', $col); - if(isset($tmpCol[1])) $col = $tmpCol[1]; - - if(strpos($col,'"')===false && strpos($col,' ')==false) $col = '"'.$col.'"'; - if(isset($tmpCol[1])) $col = $tmpCol[0].'.'.$col; - - $columns[] = $col; - } - - $columns = join(',',$columns); - } - - $query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, $groupby_query.$orderby_query); - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); - - if ($this->isError ()) { - $buff = new Object (); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array (); - - $buff->page_navigation = new PageHandler ($total_count, $total_page, $page, $page_count); - - return $buff; - } - - $virtual_no = $total_count - ($page - 1) * $list_count; - while ($tmp = cubrid_fetch ($result, CUBRID_OBJECT)) { - if ($tmp) { - foreach ($tmp as $k => $v) { - $tmp->{$k} = rtrim($v); - } - } - $data[$virtual_no--] = $tmp; - } - - $buff = new Object (); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = $data; - - $buff->page_navigation = new PageHandler ($total_count, $total_page, $page, $page_count); - return $buff; } } diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index dd0fa3089..722521195 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -1,72 +1,172 @@ action = 'select'; + + function setQueryId($queryID){ + $this->queryID = $queryID; + } + + function setAction($action){ + $this->action = $action; + } + + function setColumns($columns){ if(!isset($columns) || count($columns) === 0){ $this->columns = array(new StarExpression()); - return $this; + return; } if(!is_array($columns)) $columns = array($columns); - $this->columns = $columns; - return $this; + $this->columns = $columns; } - function from($tables){ + function setTables($tables){ if(!isset($tables) || count($tables) === 0){ $this->setError(true); $this->setMessage("You must provide at least one table for the query."); - return $this; + return; } if(!is_array($tables)) $tables = array($tables); - $this->tables = $tables; + $this->tables = $tables; + } + + function setConditions($conditions){ + if(!isset($conditions) || count($conditions) === 0) return; + if(!is_array($conditions)) $conditions = array($conditions); + + $this->conditions = $conditions; + } + + function setGroups($groups){ + if(!isset($groups) || count($groups) === 0) return; + if(!is_array($groups)) $groups = array($groups); + + $this->groups = $groups; + } + + function setOrder($order){ + if(!isset($order) || count($order) === 0) return; + if(!is_array($order)) $order = array($order); + + $this->orderby = $order; + } + + function setLimit($limit){ + if(!isset($limit)) return; + $this->limit = $limit; + } + + // START Fluent interface + function select($columns= null){ + $this->action = 'select'; + $this->setColumns($columns); + return $this; + } + + function from($tables){ + $this->setTables($tables); return $this; } function where($conditions){ - if(!isset($conditions) || count($conditions) === 0) return $this; - if(!is_array($conditions)) $conditions = array($conditions); - - $this->conditions = $conditions; - return $this; + $this->setConditions($conditions); + return $this; } function groupBy($groups){ - if(!isset($groups) || count($groups) === 0) return $this; - if(!is_array($groups)) $groups = array($groups); - - $this->groups = $groups; + $this->setGroups($groups); return $this; } function orderBy($order){ - if(!isset($order) || count($order) === 0) return $this; - if(!is_array($order)) $order = array($order); - - $this->orderby = $order; - return $this; + $this->setOrder($order); + return $this; } function limit($limit){ - if(!isset($limit)) return $this; - $this->limit = $limit; - return $this; + $this->setLimit($limit); + return $this; } - - function getSql(){ - if($this->action == 'select') return $this->getSelectSql(); + // END Fluent interface + + function getAction(){ + return $this->action; + } + + function getSelect(){ + $select = ''; + foreach($this->columns as $column){ + if($column->show()) + $select .= $column->getExpression() . ', '; + } + if(trim($select) == '') return ''; + $select = substr($select, 0, -2); + return $select; + } + + function getFrom(){ + $from = ''; + $simple_table_count = 0; + foreach($this->tables as $table){ + if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; + else $from .= ', '.$table->toString() . ' '; + $simple_table_count++; + } + if(trim($from) == '') return ''; + return $from; + + + + } + + function getWhere(){ + $where = ''; + if(count($this->conditions) > 0){ + foreach($this->conditions as $conditionGroup){ + $where .= $conditionGroup->toString(); + } + if(trim($where) == '') return ''; + + } + return $where; + } + + function getGroupBy(){ + $groupBy = ''; + if($this->groups) if($this->groups[0] !== "") + $groupBy = implode(', ', $this->groups); + return $groupBy; + } + + function getOrderBy(){ + if(count($this->orderby) === 0) return ''; + $orderBy = ''; + foreach($this->orderby as $order){ + $orderBy .= $order->toString() .', '; + } + $orderBy = substr($orderBy, 0, -2); + return $orderBy; + } + + function getLimit(){ + $limit = ''; + if(count($this->limit) > 0){ + $limit = ''; + $limit .= $this->limit->toString(); + } + return $limit; } } diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 20dd541d3..939699092 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -127,20 +127,20 @@ class QueryParser { $prebuff .= "\n"; $buff = ''; - - $buff .= '$output->columns = ' . $columns->toString() . ';'.PHP_EOL; - $buff .= '$output->tables = ' . $tables->toString() .';'.PHP_EOL; - $buff .= '$output->conditions = '.$conditions->toString() .';'.PHP_EOL; - $buff .= '$output->groups = ' . $groups->toString() . ';'; - $buff .= '$output->orderby = ' . $navigation->getOrderByString() .';'; - $buff .= $navigation->getLimitString()?'$output->limit = ' . $navigation->getLimitString() .';':""; + $buff .= '$query->setColumns(' . $columns->toString() . ');'.PHP_EOL; + $buff .= '$query->setTables(' . $tables->toString() .');'.PHP_EOL; + $buff .= '$query->setConditions('.$conditions->toString() .');'.PHP_EOL; + $buff .= '$query->setGroups(' . $groups->toString() . ');'.PHP_EOL; + $buff .= '$query->setOrder(' . $navigation->getOrderByString() .');'.PHP_EOL; + $buff .= $navigation->getLimitString()?'$query->setLimit(' . $navigation->getLimitString() .');'.PHP_EOL:""; return "query_id = "%s";%s', $this->query_id, "\n") - . sprintf('$output->action = "%s";%s', $this->action, "\n") + . '$query = new Query();'.PHP_EOL + . sprintf('$query->setQueryId("%s");%s', $this->query_id, "\n") + . sprintf('$query->setAction("%s");%s', $this->action, "\n") . $prebuff . $buff - . 'return $output; ?>'; + . 'return $query; ?>'; } diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 8e8e3fb88..da325fe0a 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -14,6 +14,7 @@ } function getValue(){ + if(is_array($this->value)) return implode(',', $this->value); return $this->value; } @@ -34,12 +35,19 @@ if(!isset($this->value)) return; if($column_type === '') return; //if($column_type === '') $column_type = 'varchar'; - if(in_array($column_type, array('date', 'varchar', 'char', 'bigtext'))) - $this->value = '\''.$this->value.'\''; + if(in_array($column_type, array('date', 'varchar', 'char','text', 'bigtext'))){ + if(!is_array($this->value)) + $this->value = '\''.$this->value.'\''; + else { + $total = count($this->value); + for($i = 0; $i < $total; $i++) + $this->value[$i] = '\''.$this->value[$i].'\''; + } + } } function checkFilter($filter_type){ - if(isset($this->value)){ + if(isset($this->value) && $this->value != ''){ $val = $this->value; $key = $this->name; switch($filter_type) { diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index 7e6040990..cad112b90 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -25,6 +25,19 @@ case 'like' : $this->value = '%'.$value.'%'; break; + case 'in' : + if(is_array($value)) + { + //$value = $this->addQuotesArray($value); + //if($type=='number') return join(',',$value); + //else + //$this->value = "['". join("','",$value)."']"; + } + else + { + $this->value = $value; + } + break; } /* //if(!in_array($operation,array('in','notin','between')) && is_array($value)){ diff --git a/classes/xml/xmlquery/queryargument/DefaultValue.class.php b/classes/xml/xmlquery/queryargument/DefaultValue.class.php index 4cac606fe..8ebed633a 100644 --- a/classes/xml/xmlquery/queryargument/DefaultValue.class.php +++ b/classes/xml/xmlquery/queryargument/DefaultValue.class.php @@ -18,6 +18,12 @@ function toString(){ if(!isset($this->value)) return; + // If value contains comma separated values and does not contain paranthesis + // -> default value is an array + if(strpos($this->value, ',') !== false && strpos($this->value, '(') === false) { + return sprintf('array(%s)', $this->value); + } + $str_pos = strpos($this->value, '('); // // TODO Replace this with parseExpression if($str_pos===false) return '\''.$this->value.'\''; diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index cd4b23b41..de5e8cfc9 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -14,6 +14,8 @@ if(!$this->argument_name) $this->ignoreValue = true; else $this->ignoreValue = false; + + if(!$this->argument_name) $this->argument_name = $tag->attrs->name; if(!$this->argument_name) $this->argument_name = str_replace('.', '_',$tag->attrs->column); @@ -26,6 +28,9 @@ } if($tag->attrs->operation) $this->operation = $tag->attrs->operation; + + // If we work with ConditionArgument, check if default value exists, and if yes, create argument + if($this->operation && $tag->attrs->default) $this->ignoreValue = false; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); $this->argument_validator = new QueryArgumentValidator($tag, $this); diff --git a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php index c51578d0e..7d930a6e4 100644 --- a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php +++ b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php @@ -39,7 +39,7 @@ ); } if($this->filter){ - $validator .= sprintf("$%s_argument->checkFilter(%s);\n" + $validator .= sprintf("$%s_argument->checkFilter('%s');\n" , $this->argument_name , $this->filter ); From d51e93152703ff1068f17adb11f370931407de09 Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 2 Jun 2011 13:19:36 +0000 Subject: [PATCH 23/82] Updated DBCubrid pagination to use new Query class. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8439 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 26 +++++++++++++------------- classes/db/queryparts/Query.class.php | 15 ++++++++++----- config/config.inc.php | 6 +++--- 3 files changed, 26 insertions(+), 21 deletions(-) diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 7b5541b91..2dee31e44 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -665,24 +665,24 @@ function getSelectSql($query){ - $select = $query->getSelect(); + $select = $query->getSelectString(); if($select == '') return new Object(-1, "Invalid query"); $select = 'SELECT ' .$select; - $from = $query->getFrom(); + $from = $query->getFromString(); if($from == '') return new Object(-1, "Invalid query"); $from = ' FROM '.$from; - $where = $query->getWhere(); + $where = $query->getWhereString(); if($where != '') $where = ' WHERE ' . $where; - $groupBy = $query->getGroupBy(); + $groupBy = $query->getGroupByString(); if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; - $orderBy = $query->getOrderBy(); + $orderBy = $query->getOrderByString(); if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; - $limit = $query->getLimit(); + $limit = $query->getLimitString(); if($limit != '') $limit = ' LIMIT ' . $limit; return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; @@ -713,9 +713,9 @@ }else return; } - if ($limit && $output->limit->isPageHandler()) { - $count_query = sprintf('select count(*) as "count" %s %s', $from, $where); - if (count($output->groups)) { + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); } @@ -726,10 +726,10 @@ // total pages if ($total_count) { - $total_page = (int) (($total_count - 1) / $output->limit->list_count) + 1; + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; } else $total_page = 1; - $virtual_no = $total_count - ($output->limit->page - 1) * $output->limit->list_count; + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; while ($tmp = cubrid_fetch ($result, CUBRID_OBJECT)) { if ($tmp) { foreach ($tmp as $k => $v) { @@ -742,9 +742,9 @@ $buff = new Object (); $buff->total_count = $total_count; $buff->total_page = $total_page; - $buff->page = $output->limit->page; + $buff->page = $queryObject->getLimit()->page; $buff->data = $data; - $buff->page_navigation = new PageHandler ($total_count, $total_page, $output->limit->page, $output->limit->page_count); + $buff->page_navigation = new PageHandler ($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); }else{ $data = $this->_fetch ($result); $buff = new Object (); diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 722521195..46dc4ac77 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -9,6 +9,7 @@ var $conditions; var $groups; var $orderby; + var $limit; function setQueryId($queryID){ @@ -105,7 +106,7 @@ return $this->action; } - function getSelect(){ + function getSelectString(){ $select = ''; foreach($this->columns as $column){ if($column->show()) @@ -116,7 +117,7 @@ return $select; } - function getFrom(){ + function getFromString(){ $from = ''; $simple_table_count = 0; foreach($this->tables as $table){ @@ -131,7 +132,7 @@ } - function getWhere(){ + function getWhereString(){ $where = ''; if(count($this->conditions) > 0){ foreach($this->conditions as $conditionGroup){ @@ -143,14 +144,14 @@ return $where; } - function getGroupBy(){ + function getGroupByString(){ $groupBy = ''; if($this->groups) if($this->groups[0] !== "") $groupBy = implode(', ', $this->groups); return $groupBy; } - function getOrderBy(){ + function getOrderByString(){ if(count($this->orderby) === 0) return ''; $orderBy = ''; foreach($this->orderby as $order){ @@ -161,6 +162,10 @@ } function getLimit(){ + return $this->limit; + } + + function getLimitString(){ $limit = ''; if(count($this->limit) > 0){ $limit = ''; diff --git a/config/config.inc.php b/config/config.inc.php index 24636abac..dd84b2b4f 100644 --- a/config/config.inc.php +++ b/config/config.inc.php @@ -51,7 +51,7 @@ * 2: output execute time, Request/Response info * 4: output DB query history **/ - if(!defined('__DEBUG__')) define('__DEBUG__', 0); + if(!defined('__DEBUG__')) define('__DEBUG__', 4); /** * @brief output location of debug message @@ -82,14 +82,14 @@ * = 0: leave a log when the slow query takes over specified seconds * Log file is saved as ./files/_db_slow_query.php file **/ - if(!defined('__LOG_SLOW_QUERY__')) define('__LOG_SLOW_QUERY__', 0); + if(!defined('__LOG_SLOW_QUERY__')) define('__LOG_SLOW_QUERY__', 1); /** * @brief Leave DB query information * 0: Do not add information to the query * 1: Comment the XML Query ID **/ - if(!defined('__DEBUG_QUERY__')) define('__DEBUG_QUERY__', 0); + if(!defined('__DEBUG_QUERY__')) define('__DEBUG_QUERY__', 1); /** * @brief option to enable/disable a compression feature using ob_gzhandler From 0e3043d678cdbca7bf6604f2e790453f1eb79dba Mon Sep 17 00:00:00 2001 From: lickawtl Date: Thu, 2 Jun 2011 15:26:38 +0000 Subject: [PATCH 24/82] unit tests for Sql Server, CUBRID, My Sql git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8440 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- test-phpUnit/ExpressionParserTest.php | 112 ++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 test-phpUnit/ExpressionParserTest.php diff --git a/test-phpUnit/ExpressionParserTest.php b/test-phpUnit/ExpressionParserTest.php new file mode 100644 index 000000000..e4e46b43a --- /dev/null +++ b/test-phpUnit/ExpressionParserTest.php @@ -0,0 +1,112 @@ +dbLeftEscapeChar,$this->dbRightEscapeChar); + $actual = $expressionParser->parseExpression($column_name); + if($alias) $actual .= " as $alias"; + $this->assertEquals($expected, $actual); + } + + function testStarExpressionIsNotEscaped(){ + $this->_test("*", NULL, '*'); + } + + function testSimpleColumnNameGetsEscaped(){ + $this->_test("member_srl", NULL + , $this->dbLeftEscapeChar.'member_srl'.$this->dbRightEscapeChar ); + } + + function testUnqualifiedAliasedColumnNameGetsEscaped(){ + $this->_test("member_srl", "id" + , $this->dbLeftEscapeChar.'member_srl'.$this->dbRightEscapeChar.' as id'); + } + + function testQualifiedColumnNameGetsEscaped(){ + $this->_test("xe_members.member_srl", NULL + , $this->dbLeftEscapeChar.'xe_members'.$this->dbRightEscapeChar.'.'.$this->dbLeftEscapeChar.'member_srl'.$this->dbRightEscapeChar); + } + + function testQualifiedAliasedColumnNameGetsEscaped(){ + $this->_test("xe_members.member_srl","id" + ,$this->dbLeftEscapeChar.'xe_members'.$this->dbRightEscapeChar.'.'.$this->dbLeftEscapeChar.'member_srl'.$this->dbRightEscapeChar.' as id'); + } + + function testCountDoesntGetEscaped(){ + $this->_test("count(*)", NULL, 'count(*)'); + } + + function testAliasedCountDoesntGetEscaped(){ + $this->_test("count(*)", "count", 'count(*) as count'); + } + + function testUnqualifiedColumnExpressionWithOneParameterLessFunction(){ + $this->_test("substring(regdate)", NULL + , 'substring('.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.')'); + } + + function testAliasedUnqualifiedColumnExpressionWithOneParameterLessFunction(){ + $this->_test("substring(regdate)", "regdate" + , 'substring('.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.') as regdate'); + } + + function testQualifiedColumnExpressionWithOneParameterLessFunction(){ + $this->_test("substring(xe_member.regdate)", NULL + , 'substring('.$this->dbLeftEscapeChar.'xe_member'.$this->dbRightEscapeChar.'.'.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.')'); + } + + function testAliasedQualifiedColumnExpressionWithOneParameterLessFunction(){ + $this->_test("substring(xe_member.regdate)", "regdate" + , 'substring('.$this->dbLeftEscapeChar.'xe_member'.$this->dbRightEscapeChar.'.'.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.') as regdate'); + } + + function testUnqualifiedColumnExpressionWithTwoParameterLessFunctions(){ + $this->_test("lpad(rpad(regdate))", NULL + , 'lpad(rpad('.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.'))'); + } + + function testAliasedUnqualifiedColumnExpressionWithTwoParameterLessFunctions(){ + $this->_test("lpad(rpad(regdate))", "regdate" + , 'lpad(rpad('.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.')) as regdate'); + } + + function testQualifiedColumnExpressionWithTwoParameterLessFunctions(){ + $this->_test("lpad(rpad(xe_member.regdate))", NULL + , 'lpad(rpad('.$this->dbLeftEscapeChar.'xe_member'.$this->dbRightEscapeChar.'.'.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.'))'); + } + + function testAliasedQualifiedColumnExpressionWithTwoParameterLessFunctions(){ + $this->_test("lpad(rpad(xe_member.regdate))", "regdate" + , 'lpad(rpad('.$this->dbLeftEscapeChar.'xe_member'.$this->dbRightEscapeChar.'.'.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.')) as regdate'); + } + + function testColumnAddition(){ + $this->_test("score1 + score2", "total" + , $this->dbLeftEscapeChar.'score1'.$this->dbRightEscapeChar.' + '.$this->dbLeftEscapeChar.'score2'.$this->dbRightEscapeChar.' as total'); + } + + function testMultipleParameterFunction(){ + $this->_test("substring(regdate, 1, 8)", NULL + , 'substring('.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.', 1, 8)'); + $this->_test("substring(regdate, 1, 8)", "regdate" + , 'substring('.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.', 1, 8) as regdate'); + $this->_test("substring(xe_member.regdate, 1, 8)", NULL + , 'substring('.$this->dbLeftEscapeChar.'xe_member'.$this->dbRightEscapeChar.'.'.$this->dbLeftEscapeChar.'regdate'.$this->dbRightEscapeChar.', 1, 8)'); + } + + function testFunctionAddition(){ + $this->_test("abs(score) + abs(totalscore)", NULL + , 'abs('.$this->dbLeftEscapeChar.'score'.$this->dbRightEscapeChar.') + abs('.$this->dbLeftEscapeChar.'totalscore'.$this->dbRightEscapeChar.')'); + } + } \ No newline at end of file From 251555245d7784728a59816867143b3a5b1f9dee Mon Sep 17 00:00:00 2001 From: lickawtl Date: Thu, 2 Jun 2011 15:34:11 +0000 Subject: [PATCH 25/82] Change DBParser.class.php to support left and right escape char. This change is required for unit tests. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8441 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/DBParser.class.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/classes/xml/xmlquery/DBParser.class.php b/classes/xml/xmlquery/DBParser.class.php index 00b65ee93..59cabb9fd 100644 --- a/classes/xml/xmlquery/DBParser.class.php +++ b/classes/xml/xmlquery/DBParser.class.php @@ -1,19 +1,23 @@ escape_char = $escape_char; + function DBParser($escape_char_left, $escape_char_right = "", $table_prefix = "xe_"){ + $this->escape_char_left = $escape_char_left; + if ($escape_char_right !== "")$this->escape_char_right = $escape_char_right; + else $this->escape_char_right = $escape_char_left; $this->table_prefix = $table_prefix; } - function getEscapeChar(){ - return $this->escape_char; + function getEscapeChar($leftOrRight){ + if ($leftOrRight === 'left')return $this->escape_char_left; + else return $this->escape_char_right; } function escape($name){ - return $this->escape_char . $name . $this->escape_char; + return $this->escape_char_left . $name . $this->escape_char_right; } function escapeString($name){ From 2e122219f17754acf57157219d23a623e065acf3 Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 2 Jun 2011 17:36:31 +0000 Subject: [PATCH 26/82] DBCubrid class: removed duplicate fetch code from pagination, updates to update, delete, insert queries. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8442 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 160 ++++++++---------- classes/db/queryparts/Query.class.php | 28 ++- classes/xml/xmlquery/QueryParser.class.php | 12 +- .../tags/column/DeleteColumnTag.class.php | 32 ---- .../tags/column/DeleteColumnsTag.class.php | 48 ------ 5 files changed, 99 insertions(+), 181 deletions(-) delete mode 100644 classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php delete mode 100644 classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 2dee31e44..e4db69607 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -214,34 +214,37 @@ /** * @brief Fetch the result **/ - function _fetch($result) + function _fetch($result, $arrayIndexEndValue = NULL) { if (!$this->isConnected() || $this->isError() || !$result) return; - + + // TODO Improve this piece of code + // This code trims values from char type columns $col_types = cubrid_column_types ($result); $col_names = cubrid_column_names ($result); $max = count ($col_types); - + for ($count = 0; $count < $max; $count++) { if (preg_match ("/^char/", $col_types[$count]) > 0) { $char_type_fields[] = $col_names[$count]; } } - + while ($tmp = cubrid_fetch ($result, CUBRID_OBJECT)) { if (is_array ($char_type_fields)) { foreach ($char_type_fields as $val) { $tmp->{$val} = rtrim ($tmp->{$val}); } } - - $output[] = $tmp; + + if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $tmp; + else $output[] = $tmp; } - + unset ($char_type_fields); - + if ($result) cubrid_close_request($result); - + if (count ($output) == 1) return $output[0]; return $output; } @@ -563,30 +566,22 @@ } + function getInsertSql($query){ + $tableName = $query->getFirstTableName(); + $values = $query->getInsertString(); + + return "INSERT INTO $tableName \n $values"; + } + /** * @brief handles insertAct **/ - // TODO Rewrite with Query object as input - function _executeInsertAct ($output) + function _executeInsertAct($queryObject) { - $query = ''; - - $tableName = $output->tables[0]->getName(); - - $columnsList = ''; - $valuesList = ''; - foreach($output->columns as $column){ - if($column->show()){ - $columnsList .= $column->getColumnName() . ', '; - $valuesList .= $column->getValue() . ', '; - } - } - $columnsList = substr($columnsList, 0, -2); - $valuesList = substr($valuesList, 0, -2); - - $query = "INSERT INTO $tableName \n ($columnsList) \n VALUES ($valuesList)"; + $query = $this->getInsertSql($queryObject); $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result = $this->_query ($query); if ($result && !$this->transaction_started) { @cubrid_commit ($this->fd); @@ -595,69 +590,53 @@ return $result; } + function getUpdateSql($query){ + $columnsList = $query->getSelectString(); + if($columnsList == '') return new Object(-1, "Invalid query"); + + $tableName = $query->getFirstTableName(); + if($tableName == '') return new Object(-1, "Invalid query"); + + $where = $query->getWhereString(); + if($where != '') $where = ' WHERE ' . $where; + + return "UPDATE $tableName SET $columnsList ".$where; + } + /** * @brief handles updateAct **/ - // TODO Rewrite with Query object as input - function _executeUpdateAct ($output) + function _executeUpdateAct($queryObject) { - $query = ''; + $query = $this->getUpdateSql($queryObject); + $result = $this->_query($query); - $tableName = $output->tables[0]->getName(); - - $columnsList = ''; - foreach($output->columns as $column){ - if($column->show()){ - $columnsList .= $column->getExpression() . ', '; - } - } - $columnsList = substr($columnsList, 0, -2); - - $where = ''; - if(count($output->conditions) > 0){ - $where = 'WHERE '; - foreach($output->conditions as $conditionGroup){ - $where .= $conditionGroup->toString(); - } - } - - $query = "UPDATE $tableName SET $columnsList ".$where; - - - $result = $this->_query ($query); if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); return $result; } + function getDeleteSql($query){ + $sql = 'DELETE '; + + $from = $query->getFromString(); + if($from == '') return new Object(-1, "Invalid query"); + $sql .= ' FROM '.$from; + + $where = $query->getWhereString(); + if($where != '') $sql .= ' WHERE ' . $where; + + return $sql; + } + /** * @brief handles deleteAct **/ - // TODO Rewrite with Query object as input - function _executeDeleteAct ($output) - { - $query = ''; - - $select = 'DELETE '; - - $from = 'FROM '; - $simple_table_count = 0; - foreach($output->tables as $table){ - if($simple_table_count > 0) $from .= ', '; - $from .= $table->toString() . ' '; - if(!$table->isJoinTable()) $simple_table_count++; - } - - $where = ''; - if(count($output->conditions) > 0){ - $where = 'WHERE '; - foreach($output->conditions as $conditionGroup){ - $where .= $conditionGroup->toString(); - } - } - - $query = $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; + function _executeDeleteAct($queryObject) + { + $query = $this->getDeleteSql($queryObject); $result = $this->_query ($query); + if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); return $result; @@ -685,7 +664,7 @@ $limit = $query->getLimitString(); if($limit != '') $limit = ' LIMIT ' . $limit; - return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy;// . ' ' . $limit; } /** @@ -698,8 +677,8 @@ function _executeSelectAct($queryObject){ $query = $this->getSelectSql($queryObject); - //$query = sprintf ("select %s from %s %s %s %s", $columns, implode (',',$table_list), implode (' ',$left_join), $condition, //$groupby_query.$orderby_query); - //$query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result = $this->_query ($query); if ($this->isError ()) { if ($limit && $output->limit->isPageHandler()){ @@ -710,43 +689,40 @@ $buff->data = array (); $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values return $buff; - }else return; + }else + return; } if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); if ($queryObject->getGroupByString() != '') { $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); } - //$count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result_count = $this->_query($count_query); $count_output = $this->_fetch($result_count); $total_count = (int)$count_output->count; - // total pages + // Total pages if ($total_count) { $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; } else $total_page = 1; + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; - while ($tmp = cubrid_fetch ($result, CUBRID_OBJECT)) { - if ($tmp) { - foreach ($tmp as $k => $v) { - $tmp->{$k} = rtrim($v); - } - } - $data[$virtual_no--] = $tmp; - } + $data = $this->_fetch($result); + //$data = $this->_fetch($result, $virtual_no); $buff = new Object (); $buff->total_count = $total_count; $buff->total_page = $total_page; $buff->page = $queryObject->getLimit()->page; $buff->data = $data; - $buff->page_navigation = new PageHandler ($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); }else{ - $data = $this->_fetch ($result); + $data = $this->_fetch($result); $buff = new Object (); $buff->data = $data; } diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 46dc4ac77..db3b9f1f3 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -64,7 +64,7 @@ $this->orderby = $order; } - function setLimit($limit){ + function setLimit($limit = NULL){ if(!isset($limit)) return; $this->limit = $limit; } @@ -117,6 +117,25 @@ return $select; } + function getUpdateString(){ + return $this->getSelectString(); + } + + function getInsertString(){ + $columnsList = ''; + $valuesList = ''; + foreach($this->columns as $column){ + if($column->show()){ + $columnsList .= $column->getColumnName() . ', '; + $valuesList .= $column->getValue() . ', '; + } + } + $columnsList = substr($columnsList, 0, -2); + $valuesList = substr($valuesList, 0, -2); + + return "($columnsList) \n VALUES ($valuesList)"; + } + function getFromString(){ $from = ''; $simple_table_count = 0; @@ -127,9 +146,6 @@ } if(trim($from) == '') return ''; return $from; - - - } function getWhereString(){ @@ -173,6 +189,10 @@ } return $limit; } + + function getFirstTableName(){ + return $this->tables[0]->getName(); + } } diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 939699092..6daca4389 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -4,7 +4,6 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/ColumnTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php'); -require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TablesTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/JoinConditionsTag.class.php'); @@ -99,7 +98,7 @@ class QueryParser { }else if($this->action == 'update') { $columns = new UpdateColumnsTag($this->query->columns->column); }else if($this->action == 'delete') { - $columns = new DeleteColumnsTag($this->query->columns->column); + $columns = null; } @@ -111,7 +110,8 @@ class QueryParser { $this->setTableColumnTypes($tables); $arguments = array(); - $arguments = array_merge($arguments, $columns->getArguments()); + if($columns) + $arguments = array_merge($arguments, $columns->getArguments()); $arguments = array_merge($arguments, $conditions->getArguments()); $arguments = array_merge($arguments, $navigation->getArguments()); @@ -127,12 +127,14 @@ class QueryParser { $prebuff .= "\n"; $buff = ''; - $buff .= '$query->setColumns(' . $columns->toString() . ');'.PHP_EOL; + if($columns) + $buff .= '$query->setColumns(' . $columns->toString() . ');'.PHP_EOL; + $buff .= '$query->setTables(' . $tables->toString() .');'.PHP_EOL; $buff .= '$query->setConditions('.$conditions->toString() .');'.PHP_EOL; $buff .= '$query->setGroups(' . $groups->toString() . ');'.PHP_EOL; $buff .= '$query->setOrder(' . $navigation->getOrderByString() .');'.PHP_EOL; - $buff .= $navigation->getLimitString()?'$query->setLimit(' . $navigation->getLimitString() .');'.PHP_EOL:""; + $buff .= '$query->setLimit(' . $navigation->getLimitString() .');'.PHP_EOL; return " tag inside an XML Query file whose action is 'delete' - * - **/ - - - class DeleteColumnTag extends ColumnTag { - var $argument; - - function DeleteColumnTag($column) { - parent::ColumnTag($column->attrs->name); - $dbParser = XmlQueryParser::getDBParser(); - $this->name = $dbParser->parseColumnName($this->name); - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - $this->argument = new QueryArgument($column); - } - - function getExpressionString(){ - return sprintf('new DeleteExpression(\'%s\', $args->%s)' - , $this->name - , $this->argument->argument_name); - } - - function getArgument(){ - return $this->argument; - } - - } -?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php b/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php deleted file mode 100644 index 753d79cf0..000000000 --- a/classes/xml/xmlquery/tags/column/DeleteColumnsTag.class.php +++ /dev/null @@ -1,48 +0,0 @@ - tag inside an XML Query file whose action is 'delete' - * - **/ - - require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/ColumnTag.class.php'); - require_once(_XE_PATH_.'classes/xml/xmlquery/tags/column/DeleteColumnTag.class.php'); - - class DeleteColumnsTag{ - var $columns; - - function DeleteColumnsTag($xml_columns) { - $this->columns = array(); - - if(!$xml_columns) - return; - - if(!is_array($xml_columns)) $xml_columns = array($xml_columns); - - foreach($xml_columns as $column){ - $this->columns[] = new DeleteColumnTag($column); - } - } - - function toString(){ - $output_columns = 'array(' . PHP_EOL; - foreach($this->columns as $column){ - $output_columns .= $column->getExpressionString() . PHP_EOL . ','; - } - $output_columns = substr($output_columns, 0, -1); - $output_columns .= ')'; - return $output_columns; - } - - function getArguments(){ - $arguments = array(); - foreach($this->columns as $column){ - $arguments[] = $column->getArgument(); - } - return $arguments; - } - - } - -?> \ No newline at end of file From 9ef9069ba2ab1e0d2902aaf53914daff8def3473 Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 2 Jun 2011 18:33:50 +0000 Subject: [PATCH 27/82] Started work on MySql class. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8443 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 57 +++++ classes/db/DBCubrid.class.php | 66 +----- classes/db/DBMysql.class.php | 387 +++------------------------------- 3 files changed, 90 insertions(+), 420 deletions(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 4ba22ddbc..560713944 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -456,6 +456,63 @@ $query = sprintf("drop table %s%s", $this->prefix, $table_name); $this->_query($query); } + + function getSelectSql($query){ + $select = $query->getSelectString(); + if($select == '') return new Object(-1, "Invalid query"); + $select = 'SELECT ' .$select; + + $from = $query->getFromString(); + if($from == '') return new Object(-1, "Invalid query"); + $from = ' FROM '.$from; + + $where = $query->getWhereString(); + if($where != '') $where = ' WHERE ' . $where; + + $groupBy = $query->getGroupByString(); + if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; + + $orderBy = $query->getOrderByString(); + if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; + + $limit = $query->getLimitString(); + if($limit != '') $limit = ' LIMIT ' . $limit; + + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; + } + + function getDeleteSql($query){ + $sql = 'DELETE '; + + $from = $query->getFromString(); + if($from == '') return new Object(-1, "Invalid query"); + $sql .= ' FROM '.$from; + + $where = $query->getWhereString(); + if($where != '') $sql .= ' WHERE ' . $where; + + return $sql; + } + + function getUpdateSql($query){ + $columnsList = $query->getSelectString(); + if($columnsList == '') return new Object(-1, "Invalid query"); + + $tableName = $query->getFirstTableName(); + if($tableName == '') return new Object(-1, "Invalid query"); + + $where = $query->getWhereString(); + if($where != '') $where = ' WHERE ' . $where; + + return "UPDATE $tableName SET $columnsList ".$where; + } + + function getInsertSql($query){ + $tableName = $query->getFirstTableName(); + $values = $query->getInsertString(); + + return "INSERT INTO $tableName \n $values"; + } } ?> diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index e4db69607..df7e79bd2 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -566,12 +566,7 @@ } - function getInsertSql($query){ - $tableName = $query->getFirstTableName(); - $values = $query->getInsertString(); - - return "INSERT INTO $tableName \n $values"; - } + /** * @brief handles insertAct @@ -589,19 +584,6 @@ return $result; } - - function getUpdateSql($query){ - $columnsList = $query->getSelectString(); - if($columnsList == '') return new Object(-1, "Invalid query"); - - $tableName = $query->getFirstTableName(); - if($tableName == '') return new Object(-1, "Invalid query"); - - $where = $query->getWhereString(); - if($where != '') $where = ' WHERE ' . $where; - - return "UPDATE $tableName SET $columnsList ".$where; - } /** * @brief handles updateAct @@ -616,18 +598,6 @@ return $result; } - function getDeleteSql($query){ - $sql = 'DELETE '; - - $from = $query->getFromString(); - if($from == '') return new Object(-1, "Invalid query"); - $sql .= ' FROM '.$from; - - $where = $query->getWhereString(); - if($where != '') $sql .= ' WHERE ' . $where; - - return $sql; - } /** * @brief handles deleteAct @@ -641,31 +611,6 @@ return $result; } - - - function getSelectSql($query){ - $select = $query->getSelectString(); - if($select == '') return new Object(-1, "Invalid query"); - $select = 'SELECT ' .$select; - - $from = $query->getFromString(); - if($from == '') return new Object(-1, "Invalid query"); - $from = ' FROM '.$from; - - $where = $query->getWhereString(); - if($where != '') $where = ' WHERE ' . $where; - - $groupBy = $query->getGroupByString(); - if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; - - $orderBy = $query->getOrderByString(); - if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; - - $limit = $query->getLimitString(); - if($limit != '') $limit = ' LIMIT ' . $limit; - - return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy;// . ' ' . $limit; - } /** * @brief Handle selectAct @@ -677,7 +622,7 @@ function _executeSelectAct($queryObject){ $query = $this->getSelectSql($queryObject); - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result = $this->_query ($query); if ($this->isError ()) { @@ -712,8 +657,7 @@ $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; - $data = $this->_fetch($result); - //$data = $this->_fetch($result, $virtual_no); + $data = $this->_fetch($result, $virtual_no); $buff = new Object (); $buff->total_count = $total_count; @@ -729,6 +673,10 @@ return $buff; } + + function getParser(){ + return new DBParser('"'); + } } return new DBCubrid; diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index 6ee269ba5..cc00681c7 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -374,141 +374,42 @@ if(!$output) return false; } - /** - * @brief Return conditional clause - **/ - function getCondition($output) { - if(!$output->conditions) return; - $condition = $this->_getCondition($output->conditions,$output->column_type); - if($condition) $condition = ' where '.$condition; - return $condition; - } - - function getLeftCondition($conditions,$column_type){ - return $this->_getCondition($conditions,$column_type); - } - - - function _getCondition($conditions,$column_type) { - $condition = ''; - foreach($conditions as $val) { - $sub_condition = ''; - foreach($val['condition'] as $v) { - if(!isset($v['value'])) continue; - if($v['value'] === '') continue; - if(!in_array(gettype($v['value']), array('string', 'integer', 'double', 'array'))) continue; - - $name = $v['column']; - $operation = $v['operation']; - $value = $v['value']; - $type = $this->getColumnType($column_type,$name); - $pipe = $v['pipe']; - $value = $this->getConditionValue($name, $value, $operation, $type, $column_type); - if(!$value) $value = $v['value']; - $str = $this->getConditionPart($name, $value, $operation); - if($sub_condition) $sub_condition .= ' '.$pipe.' '; - $sub_condition .= $str; - } - if($sub_condition) { - if($condition && $val['pipe']) $condition .= ' '.$val['pipe'].' '; - $condition .= '('.$sub_condition.')'; - } - } - return $condition; - } - /** * @brief Handle the insertAct **/ - function _executeInsertAct($output) { - // List tables - foreach($output->tables as $key => $val) { - $table_list[] = '`'.$this->prefix.$val.'`'; - } - // List columns - foreach($output->columns as $key => $val) { - $name = $val['name']; - $value = $val['value']; - - if($output->column_type[$name]!='number') { - - if(!is_null($value)){ - $value = "'" . $this->addQuotes($value) ."'"; - }else{ - if($val['notnull']=='notnull') { - $value = "''"; - } else { - //$value = 'null'; - $value = "''"; - } - } - - } - //elseif(!$value || is_numeric($value)) $value = (int)$value; - else $this->_filterNumber(&$value); - - $column_list[] = '`'.$name.'`'; - $value_list[] = $value; - } - + function _executeInsertAct($queryObject) { + // TODO See what priority does //priority setting - $priority = ''; - if($output->priority) $priority = $output->priority['type'].'_priority'; + //$priority = ''; + //if($output->priority) $priority = $output->priority['type'].'_priority'; - $query = sprintf("insert %s into %s (%s) values (%s);", $priority, implode(',',$table_list), implode(',',$column_list), implode(',', $value_list)); + $query = $this->getInsertSql($queryObject); return $this->_query($query); } /** * @brief Handle updateAct **/ - function _executeUpdateAct($output) { - // List tables - foreach($output->tables as $key => $val) { - $table_list[] = '`'.$this->prefix.$val.'` as '.$key; - } - // List columns - foreach($output->columns as $key => $val) { - if(!isset($val['value'])) continue; - $name = $val['name']; - $value = $val['value']; - if(strpos($name,'.')!==false&&strpos($value,'.')!==false) $column_list[] = $name.' = '.$value; - else { - if($output->column_type[$name]!='number') $value = "'".$this->addQuotes($value)."'"; - else $this->_filterNumber(&$value); - - $column_list[] = sprintf("`%s` = %s", $name, $value); - } - } - // List the conditional clause - $condition = $this->getCondition($output); - + function _executeUpdateAct($queryObject) { + // TODO See what proiority does //priority setting - $priority = ''; - if($output->priority) $priority = $output->priority['type'].'_priority'; - - $query = sprintf("update %s %s set %s %s", $priority, implode(',',$table_list), implode(',',$column_list), $condition); + //$priority = ''; + //if($output->priority) $priority = $output->priority['type'].'_priority'; + $query = $this->getUpdateSql($queryObject); return $this->_query($query); } /** * @brief Handle deleteAct **/ - function _executeDeleteAct($output) { - // List tables - foreach($output->tables as $key => $val) { - $table_list[] = '`'.$this->prefix.$val.'`'; - } - // List the conditional clause - $condition = $this->getCondition($output); - - //priority setting - $priority = ''; - if($output->priority) $priority = $output->priority['type'].'_priority'; - - $query = sprintf("delete %s from %s %s", $priority, implode(',',$table_list), $condition); + function _executeDeleteAct($queryObject) { + $query = $this->getDeleteSql($queryObject); + //priority setting + // TODO Check what priority does + //$priority = ''; + //if($output->priority) $priority = $output->priority['type'].'_priority'; return $this->_query($query); } @@ -518,143 +419,15 @@ * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($output) { - // List tables - $table_list = array(); - foreach($output->tables as $key => $val) { - $table_list[] = '`'.$this->prefix.$val.'` as '.$key; - } - - $left_join = array(); - // why??? - $left_tables= (array)$output->left_tables; - - foreach($left_tables as $key => $val) { - $condition = $this->_getCondition($output->left_conditions[$key],$output->column_type); - if($condition){ - $left_join[] = $val . ' `'.$this->prefix.$output->_tables[$key].'` as '.$key . ' on (' . $condition . ')'; - } - } - - $click_count = array(); - if(!$output->columns){ - $output->columns = array(array('name'=>'*')); - } - - $column_list = array(); - foreach($output->columns as $key => $val) - { - $name = $val['name']; - $alias = $val['alias']; - if($val['click_count']) $click_count[] = $val['name']; - - if(substr($name,-1) == '*') - { - $column_list[] = $name; - } - else if(strpos($name,'.')===false && strpos($name,'(')===false) - { - if($alias) - { - $col = sprintf('`%s` as `%s`', $name, $alias); - $column_list[$alias] = $col; - } - else - { - $column_list[] = sprintf('`%s`',$name); - } - } - else - { - if($alias) - { - $col = sprintf('%s as `%s`', $name, $alias); - $column_list[$alias] = $col; - } - else - { - $column_list[] = sprintf('%s',$name); - } - } - } - - $columns = implode(',',$column_list); - $output->column_list = $column_list; - $condition = $this->getCondition($output); - - if(count($output->index_hint)) - $index_hint = sprintf(' %s index (%s) ', $output->index_hint['type'], $output->index_hint['name']); - - if($output->list_count && $output->page) return $this->_getNavigationData($table_list, $columns, $left_join, $index_hint, $condition, $output); - - // Add a condition to use an index when sorting in order by list_order, update_order - if($output->order) { - $conditions = $this->getConditionList($output); - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' where %s < 2100000000 ', $col); - } - } - } - - - if(count($output->groups)) - { - $groupby_query = sprintf(' group by %s', implode(',',$output->groups)); - - if(count($output->arg_columns)) - { - foreach($output->groups as $group) - { - if($column_list[$group]) $output->arg_columns[] = $column_list[$group]; - } - } - } - - if($output->order) { - foreach($output->order as $key => $val) { - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $orderby_query .= ' order by '.implode(',',$index_list); - } - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - unset($tmpCol); - $tmpCol = explode('.', $col); - if(isset($tmpCol[1])) $col = $tmpCol[1]; - - if(strpos($col,'`')===false && strpos($col,' ')==false) $col = '`'.$col.'`'; - if(isset($tmpCol[1])) $col = $tmpCol[0].'.'.$col; - - $columns[] = $col; - } - - $columns = join(',',$columns); - } - - $query = sprintf("select %s from %s %s %s %s %s", $columns, implode(',',$table_list),implode(' ',$left_join), $index_hint, $condition, $groupby_query.$orderby_query); - - // Apply when using list_count - if($output->list_count['value']) $query = sprintf('%s limit %d', $query, $output->list_count['value']); - - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; + function _executeSelectAct($queryObject) { + $query = $this->getSelectSql($queryObject); + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; $result = $this->_query($query); if($this->isError()) return; - if(count($click_count) && count($output->conditions)){ - $_query = ''; - foreach($click_count as $k => $c) $_query .= sprintf(',%s=%s+1 ',$c,$c); - $_query = sprintf('update %s set %s %s',implode(',',$table_list), substr($_query,1), $condition); - $this->_query($_query); - } - + + // TODO Add support for click count + // TODO Add code for pagination $data = $this->_fetch($result); $buff = new Object(); @@ -663,118 +436,6 @@ return $buff; } - /** - * @brief Paging is handled if navigation information exists in the query xml - * - * It is quite convenient although its structure is not good at all .. -_-; - **/ - function _getNavigationData($table_list, $columns, $left_join, $index_hint, $condition, $output) { - require_once(_XE_PATH_.'classes/page/PageHandler.class.php'); - - $column_list = $output->column_list; - - // Get a total count - $count_condition = count($output->groups) ? sprintf('%s group by %s', $condition, implode(', ', $output->groups)) : $condition; - $count_query = sprintf("select count(*) as count from %s %s %s", implode(', ', $table_list), implode(' ', $left_join), $count_condition); - if (count($output->groups)) $count_query = sprintf('select count(*) as count from (%s) xet', $count_query); - - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id . ' count(*)'):''; - $result = $this->_query($count_query); - $count_output = $this->_fetch($result); - $total_count = (int)$count_output->count; - - $list_count = $output->list_count['value']; - if(!$list_count) $list_count = 20; - $page_count = $output->page_count['value']; - if(!$page_count) $page_count = 10; - $page = $output->page['value']; - if(!$page) $page = 1; - // Get a total page - if($total_count) $total_page = (int)( ($total_count-1) / $list_count) + 1; - else $total_page = 1; - // Check Page variables - if($page > $total_page) $page = $total_page; - $start_count = ($page-1)*$list_count; - // Add a condition to use an index when sorting in order by list_order, update_order - if($output->order) { - $conditions = $this->getConditionList($output); - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' where %s < 2100000000 ', $col); - } - } - } - - if(count($output->groups)){ - $groupby_query = sprintf(' group by %s', implode(',',$output->groups)); - - if(count($output->arg_columns)) - { - foreach($output->groups as $group) - { - if($column_list[$group]) $output->arg_columns[] = $column_list[$group]; - } - } - } - - if(count($output->order)) { - foreach($output->order as $key => $val) { - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $orderby_query = ' order by '.implode(',',$index_list); - } - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - unset($tmpCol); - $tmpCol = explode('.', $col); - if(isset($tmpCol[1])) $col = $tmpCol[1]; - - if(strpos($col,'`')===false && strpos($col,' ')==false) $col = '`'.$col.'`'; - if(isset($tmpCol[1])) $col = $tmpCol[0].'.'.$col; - - $columns[] = $col; - } - $columns = join(',',$columns); - } - - $query = sprintf("select %s from %s %s %s %s %s", $columns, implode(',',$table_list), implode(' ',$left_join), $index_hint, $condition, $groupby_query.$orderby_query); - $query = sprintf('%s limit %d, %d', $query, $start_count, $list_count); - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - - $result = $this->_query($query); - if($this->isError()) { - $buff = new Object(); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array(); - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - - $virtual_no = $total_count - ($page-1)*$list_count; - $data = array(); - while($tmp = $this->db_fetch_object($result)) { - $data[$virtual_no--] = $tmp; - } - $buff = new Object(); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = $data; - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - function db_insert_id() { return mysql_insert_id($this->fd); @@ -784,6 +445,10 @@ { return mysql_fetch_object($result); } + + function getParser(){ + return new DBParser('`'); + } } return new DBMysql; From 69bca759f6956e410513d42e97ad36af3b5ee04b Mon Sep 17 00:00:00 2001 From: ucorina Date: Fri, 3 Jun 2011 14:50:12 +0000 Subject: [PATCH 28/82] Fix for DELETE statement. MySql class refactoring to use new DBClasses. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8449 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 5 ++ classes/db/DBCubrid.class.php | 10 ++- classes/db/DBMysql.class.php | 81 +++++++++++++++++---- classes/db/queryparts/Query.class.php | 4 + classes/db/queryparts/table/Table.class.php | 4 + classes/xml/XmlQueryParser.class.php | 5 +- 6 files changed, 89 insertions(+), 20 deletions(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 560713944..f9c9a37ca 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -483,6 +483,11 @@ function getDeleteSql($query){ $sql = 'DELETE '; + + // TODO Add support for deleting based on alias, for both simple FROM and multi table join FROM clause + $tables = $query->getTables(); + + $sql .= $tables[0]->getAlias(); $from = $query->getFromString(); if($from == '') return new Object(-1, "Invalid query"); diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index df7e79bd2..f02f8f8c2 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -574,7 +574,8 @@ function _executeInsertAct($queryObject) { $query = $this->getInsertSql($queryObject); - + if(is_a($query, 'Object')) return; + $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result = $this->_query ($query); @@ -591,6 +592,8 @@ function _executeUpdateAct($queryObject) { $query = $this->getUpdateSql($queryObject); + if(is_a($query, 'Object')) return; + $result = $this->_query($query); if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); @@ -605,6 +608,8 @@ function _executeDeleteAct($queryObject) { $query = $this->getDeleteSql($queryObject); + if(is_a($query, 'Object')) return; + $result = $this->_query ($query); if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); @@ -621,7 +626,8 @@ // TODO Rewrite with Query object as input function _executeSelectAct($queryObject){ $query = $this->getSelectSql($queryObject); - + if(is_a($query, 'Object')) return; + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; $result = $this->_query ($query); diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index cc00681c7..72f7bfe09 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -152,7 +152,7 @@ // Notify to start a query execution $this->actStart($query); // Run the query statement - $result = @mysql_query($query, $this->fd); + $result = mysql_query($query, $this->fd); // Error Check if(mysql_error($this->fd)) $this->setError(mysql_errno($this->fd), mysql_error($this->fd)); // Notify to complete a query execution @@ -164,12 +164,16 @@ /** * @brief Fetch results **/ - function _fetch($result) { + function _fetch($result, $arrayIndexEndValue = NULL) { if(!$this->isConnected() || $this->isError() || !$result) return; while($tmp = $this->db_fetch_object($result)) { - $output[] = $tmp; + if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $tmp; + else $output[] = $tmp; + } + if(count($output)==1){ + if(isset($arrayIndexEndValue)) return $output; + else return $output[0]; } - if(count($output)==1) return $output[0]; return $output; } @@ -384,6 +388,7 @@ //if($output->priority) $priority = $output->priority['type'].'_priority'; $query = $this->getInsertSql($queryObject); + if(is_a($query, 'Object')) return; return $this->_query($query); } @@ -397,6 +402,7 @@ //if($output->priority) $priority = $output->priority['type'].'_priority'; $query = $this->getUpdateSql($queryObject); + if(is_a($query, 'Object')) return; return $this->_query($query); } @@ -404,8 +410,10 @@ * @brief Handle deleteAct **/ function _executeDeleteAct($queryObject) { - $query = $this->getDeleteSql($queryObject); - + $query = $this->getDeleteSql($queryObject); + + if(is_a($query, 'Object')) return; + //priority setting // TODO Check what priority does //$priority = ''; @@ -421,19 +429,62 @@ **/ function _executeSelectAct($queryObject) { $query = $this->getSelectSql($queryObject); + + if(is_a($query, 'Object')) return; + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - - $result = $this->_query($query); - if($this->isError()) return; - + // TODO Add support for click count - // TODO Add code for pagination - $data = $this->_fetch($result); + // TODO Add code for pagination + + $result = $this->_query ($query); + if ($this->isError ()) { + if ($limit && $output->limit->isPageHandler()){ + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + }else + return; + } - $buff = new Object(); - $buff->data = $data; + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } - return $buff; + $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result_count = $this->_query($count_query); + $count_output = $this->_fetch($result_count); + $total_count = (int)$count_output->count; + + // Total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; + } else $total_page = 1; + + + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; + $data = $this->_fetch($result, $virtual_no); + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $queryObject->getLimit()->page; + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + }else{ + $data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } + + return $buff; } function db_insert_id() diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index db3b9f1f3..70853981e 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -136,6 +136,10 @@ return "($columnsList) \n VALUES ($valuesList)"; } + function getTables(){ + return $this->tables; + } + function getFromString(){ $from = ''; $simple_table_count = 0; diff --git a/classes/db/queryparts/table/Table.class.php b/classes/db/queryparts/table/Table.class.php index b2b7d5506..022be04f1 100644 --- a/classes/db/queryparts/table/Table.class.php +++ b/classes/db/queryparts/table/Table.class.php @@ -17,6 +17,10 @@ return $this->name; } + function getAlias(){ + return $this->alias; + } + function isJoinTable(){ if(in_array($tableName,array('left join','left outer join','right join','right outer join'))) return true; return false; diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 1b4b4514d..2886a507d 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -32,9 +32,8 @@ function &getDBParser(){ static $dbParser; if(!$dbParser){ - //$oDB = &DB::getParser(); - //self::$dbParser = $oDB->getParser(); - $dbParser = new DBParser('"'); + $oDB = &DB::getInstance(); + $dbParser = $oDB->getParser(); } return $dbParser; } From a85aec5dc05ce3e9920cfe7fa753d0ae8be3c5f9 Mon Sep 17 00:00:00 2001 From: ucorina Date: Fri, 3 Jun 2011 14:50:31 +0000 Subject: [PATCH 29/82] git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8450 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- config/config.inc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/config.inc.php b/config/config.inc.php index dd84b2b4f..357e52bfb 100644 --- a/config/config.inc.php +++ b/config/config.inc.php @@ -74,7 +74,7 @@ * 0: No output * 1: files/_debug_db_query.php connected to the output **/ - if(!defined('__DEBUG_DB_OUTPUT__')) define('__DEBUG_DB_OUTPUT__', 0); + if(!defined('__DEBUG_DB_OUTPUT__')) define('__DEBUG_DB_OUTPUT__', 1); /** * @brief Query log for only timeout query among DB queries From d071909cded3bb88820ec852088cf79242a751dc Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 6 Jun 2011 09:24:31 +0000 Subject: [PATCH 30/82] Added column type information inside QueryArgument objects. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8451 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/argument/Argument.class.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index da325fe0a..fe8106bea 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -3,6 +3,7 @@ class Argument { var $value; var $name; + var $type; var $isValid; var $errorMessage; @@ -18,6 +19,10 @@ return $this->value; } + function getType(){ + return $this->type; + } + function isValid(){ return $this->isValid; } @@ -34,6 +39,9 @@ function escapeValue($column_type){ if(!isset($this->value)) return; if($column_type === '') return; + + $this->type = $column_type; + //if($column_type === '') $column_type = 'varchar'; if(in_array($column_type, array('date', 'varchar', 'char','text', 'bigtext'))){ if(!is_array($this->value)) From 57b91e1d3e4d015ccce1f509bdf6ef9747f48394 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 6 Jun 2011 15:41:00 +0000 Subject: [PATCH 31/82] Postgres class - removed methods that are no longer needed. Updated to work with new classes. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8452 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 6 + classes/db/DBPostgresql.class.php | 497 +++++--------------- classes/db/queryparts/limit/Limit.class.php | 8 + 3 files changed, 119 insertions(+), 392 deletions(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index f9c9a37ca..8391f0d77 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -518,6 +518,12 @@ return "INSERT INTO $tableName \n $values"; } + + // HACK This is needed because on installation, the XmlQueryParer is used without any configured database + // TODO Change this or make sure the query cache files created before db.config exists are deleted + function getParser(){ + return new DBParser('"'); + } } ?> diff --git a/classes/db/DBPostgresql.class.php b/classes/db/DBPostgresql.class.php index 94e0fdeff..38d54e228 100644 --- a/classes/db/DBPostgresql.class.php +++ b/classes/db/DBPostgresql.class.php @@ -226,15 +226,19 @@ class DBPostgresql extends DB /** * @brief Fetch results **/ - function _fetch($result) + // TODO This is duplicate code - maybe we can find away to abastract the driver + function _fetch($result, $arrayIndexEndValue = NULL) { if (!$this->isConnected() || $this->isError() || !$result) return; while ($tmp = pg_fetch_object($result)) { - $output[] = $tmp; + if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $tmp; + else $output[] = $tmp; } - if (count($output) == 1) - return $output[0]; + if(count($output)==1){ + if(isset($arrayIndexEndValue)) return $output; + else return $output[0]; + } return $output; } @@ -493,428 +497,137 @@ class DBPostgresql extends DB } - /** - * @brief Return conditional clause - **/ - function getCondition($output) - { - if (!$output->conditions) - return; - $condition = $this->_getCondition($output->conditions, $output->column_type); - if ($condition) - $condition = ' where ' . $condition; - return $condition; - } - - function getLeftCondition($conditions, $column_type) - { - return $this->_getCondition($conditions, $column_type); - } - - - function _getCondition($conditions, $column_type) - { - $condition = ''; - foreach ($conditions as $val) { - $sub_condition = ''; - foreach ($val['condition'] as $v) { - if (!isset($v['value'])) - continue; - if ($v['value'] === '') - continue; - if(!in_array(gettype($v['value']), array('string', 'integer', 'double', 'array'))) continue; - continue; - - $name = $v['column']; - $operation = $v['operation']; - $value = $v['value']; - $type = $this->getColumnType($column_type, $name); - $pipe = $v['pipe']; - - $value = $this->getConditionValue($name, $value, $operation, $type, $column_type); - if (!$value) - $value = $v['value']; - $str = $this->getConditionPart($name, $value, $operation); - if ($sub_condition) - $sub_condition .= ' ' . $pipe . ' '; - $sub_condition .= $str; - } - if ($sub_condition) { - if ($condition && $val['pipe']) - $condition .= ' ' . $val['pipe'] . ' '; - $condition .= '(' . $sub_condition . ')'; - } - } - return $condition; - } - - + /** * @brief Handle the insertAct **/ - function _executeInsertAct($output) + function _executeInsertAct($queryObject) { - // List tables - foreach ($output->tables as $key => $val) { - $table_list[] = $this->prefix . $val; - } - // List columns - foreach ($output->columns as $key => $val) { - $name = $val['name']; - $value = $val['value']; - if ($output->column_type[$name] != 'number') { - $value = "'" . $this->addQuotes($value) . "'"; - if (!$value) - $value = 'null'; - } - // sql injection 문제로 xml ì„ ì–¸ì´ numberì¸ ê²½ìš°ì´ë©´ì„œ 넘어온 ê°’ì´ ìˆ«ìží˜•ì´ ì•„ë‹ˆë©´ 숫ìží˜•으로 ê°•ì œ 형변환 - // elseif (!$value || is_numeric($value)) $value = (int)$value; - else $this->_filterNumber(&$value); - - $column_list[] = $name; - $value_list[] = $value; - } - - $query = sprintf("insert into %s (%s) values (%s);", implode(',', $table_list), - implode(',', $column_list), implode(',', $value_list)); + $query = $this->getInsertSql($queryObject); + if(is_a($query, 'Object')) return; + return $this->_query($query); } /** * @brief Handle updateAct **/ - function _executeUpdateAct($output) + function _executeUpdateAct($queryObject) { - // List tables - foreach ($output->tables as $key => $val) { - //$table_list[] = $this->prefix.$val.' as '.$key; - $table_list[] = $this->prefix . $val; - } - // List columns - foreach ($output->columns as $key => $val) { - if (!isset($val['value'])) - continue; - $name = $val['name']; - $value = $val['value']; - if (strpos($name, '.') !== false && strpos($value, '.') !== false) - $column_list[] = $name . ' = ' . $value; - else { - if ($output->column_type[$name] != 'number') - $value = "'" . $this->addQuotes($value) . "'"; - // sql injection 문제로 xml ì„ ì–¸ì´ numberì¸ ê²½ìš°ì´ë©´ì„œ 넘어온 ê°’ì´ ìˆ«ìží˜•ì´ ì•„ë‹ˆë©´ 숫ìží˜•으로 ê°•ì œ 형변환 - else $this->_filterNumber(&$value); - - $column_list[] = sprintf("%s = %s", $name, $value); - } - } - // List the conditional clause - $condition = $this->getCondition($output); - - $query = sprintf("update %s set %s %s", implode(',', $table_list), implode(',', - $column_list), $condition); - + $query = $this->getUpdateSql($queryObject); + if(is_a($query, 'Object')) return; return $this->_query($query); } /** * @brief Handle deleteAct **/ - function _executeDeleteAct($output) + function _executeDeleteAct($queryObject) { - // List tables - foreach ($output->tables as $key => $val) { - $table_list[] = $this->prefix . $val; - } - // List the conditional clause - $condition = $this->getCondition($output); - - $query = sprintf("delete from %s %s", implode(',', $table_list), $condition); - + $query = $this->getDeleteSql($queryObject); + + if(is_a($query, 'Object')) return; return $this->_query($query); } + /** + * + * override + * @param $queryObject + */ + function getSelectSql($query){ + $select = $query->getSelectString(); + if($select == '') return new Object(-1, "Invalid query"); + $select = 'SELECT ' .$select; + + $from = $query->getFromString(); + if($from == '') return new Object(-1, "Invalid query"); + $from = ' FROM '.$from; + + $where = $query->getWhereString(); + if($where != '') $where = ' WHERE ' . $where; + + $groupBy = $query->getGroupByString(); + if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; + + $orderBy = $query->getOrderByString(); + if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; + + $limit = $query->getLimitString(); + if($limit != '') $limit = ' LIMIT ' . $query->getLimit()->getLimit() . ' OFFSET ' . $query->getLimit()->getOffset(); + + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; + } + /** * @brief Handle selectAct * * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($output) + function _executeSelectAct($queryObject) { - // List tables - $table_list = array(); - foreach ($output->tables as $key => $val) { - $table_list[] = $this->prefix . $val . ' as ' . $key; - } - - $left_join = array(); - // why??? - $left_tables = (array )$output->left_tables; - - foreach ($left_tables as $key => $val) { - $condition = $this->_getCondition($output->left_conditions[$key], $output-> - column_type); - if ($condition) { - $left_join[] = $val . ' ' . $this->prefix . $output->_tables[$key] . ' as ' . $key . - ' on (' . $condition . ')'; - } - } - - $click_count = array(); - if(!$output->columns){ - $output->columns = array(array('name'=>'*')); - } - - $column_list = array(); - foreach ($output->columns as $key => $val) { - $name = $val['name']; - $alias = $val['alias']; - if($val['click_count']) $click_count[] = $val['name']; - - if (substr($name, -1) == '*') { - $column_list[] = $name; - } elseif (strpos($name, '.') === false && strpos($name, '(') === false) { - if ($alias) - $column_list[$alias] = sprintf('%s as %s', $name, $alias); - else - $column_list[] = sprintf('%s', $name); - } else { - if ($alias) - $column_list[$alias] = sprintf('%s as %s', $name, $alias); - else - $column_list[] = sprintf('%s', $name); + $query = $this->getSelectSql($queryObject); + + if(is_a($query, 'Object')) return; + + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; + + // TODO Add support for click count + // TODO Add code for pagination + + $result = $this->_query ($query); + if ($this->isError ()) { + if ($limit && $output->limit->isPageHandler()){ + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + }else + return; } - } - $columns = implode(',', $column_list); - $condition = $this->getCondition($output); + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } - $output->column_list = $column_list; - if ($output->list_count && $output->page) - return $this->_getNavigationData($table_list, $columns, $left_join, $condition, - $output); - // Add a condition to use an index when sorting in order by list_order, update_order - if ($output->order) { - $conditions = $this->getConditionList($output); - if (!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach ($output->order as $key => $val) { - $col = $val[0]; - if (!in_array($col, array('list_order', 'update_order'))) - continue; - if ($condition) - $condition .= sprintf(' and %s < 2100000000 ', $col); - else - $condition = sprintf(' where %s < 2100000000 ', $col); - } - } - } + $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result_count = $this->_query($count_query); + $count_output = $this->_fetch($result_count); + $total_count = (int)$count_output->count; + + // Total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; + } else $total_page = 1; + + + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; + $data = $this->_fetch($result, $virtual_no); + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $queryObject->getLimit()->page; + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + }else{ + $data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } - if (count($output->groups)) { - /* - var_dump("= column output start = "); - var_dump(sizeof ($output->columns) . " = end length == "); - var_dump($output->columns); - var_dump("= column output end = " . "\n"); - var_dump($output->groups); - var_dump("=== " . "\n"); - var_dump(debug_backtrace()); - - foreach($output->columns as $key => $val) { - $name = $val['name']; - $alias = $val['alias']; - } */ - $group_list = array(); - foreach ($output->groups as $gkey => $gval) { - foreach ($output->columns as $key => $val) { - $name = $val['name']; - $alias = $val['alias']; - if (trim($name) == trim($gval)) { - $group_list[] = $alias; - break; - } - } - - if($column_list[$gval]) $output->arg_columns[] = $column_list[$gval]; - - } - $groupby_query = sprintf(' group by %s', implode(',', $group_list)); - // var_dump($query); - } - - if ($output->order) { - foreach ($output->order as $key => $val) { - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if (count($index_list)) $orderby_query = ' order by ' . implode(',', $index_list); - } - - if(count($output->arg_columns)) - { - $columns = join(',',$output->arg_columns); - } - - $query = sprintf("select %s from %s %s %s %s", $columns, implode(',', $table_list), implode(' ', $left_join), $condition, $groupby_query.$orderby_query); - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_query($query); - if ($this->isError()) - return; - - if(count($click_count)>0 && count($output->conditions)>0){ - $_query = ''; - foreach($click_count as $k => $c) $_query .= sprintf(',%s=%s+1 ',$c,$c); - $_query = sprintf('update %s set %s %s',implode(',',$table_list), substr($_query,1), $condition); - $this->_query($_query); - } - - - $data = $this->_fetch($result); - - $buff = new Object(); - $buff->data = $data; - return $buff; + return $buff; } - - /** - * @brief Paging is handled if navigation information exists in the query xml - * - * It is quite convenient although its structure is not good at all .. -_-; - **/ - function _getNavigationData($table_list, $columns, $left_join, $condition, $output) - { - require_once (_XE_PATH_ . 'classes/page/PageHandler.class.php'); - - $column_list = $output->column_list; - /* - // Modified to find total number of SELECT queries having group by clause - // If it works correctly, uncomment the following codes - // - $count_condition = count($output->groups) ? sprintf('%s group by %s', $condition, implode(', ', $output->groups)) : $condition; - $total_count = $this->getCountCache($output->tables, $count_condition); - if ($total_count === false) { - $count_query = sprintf('select count(*) as count from %s %s %s', implode(', ', $table_list), implode(' ', $left_join), $count_condition); - if (count($output->groups)) - $count_query = sprintf('select count(*) as count from (%s) xet', $count_query); - $result = $this->_query($count_query); - $count_output = $this->_fetch($result); - $total_count = (int)$count_output->count; - $this->putCountCache($output->tables, $count_condition, $total_count); - } - */ - - // Get a total count - $count_query = sprintf("select count(*) as count from %s %s %s", implode(',', $table_list), implode(' ', $left_join), $condition); - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id . ' count(*)'):''; - $result = $this->_query($count_query); - $count_output = $this->_fetch($result); - $total_count = (int)$count_output->count; - - $list_count = $output->list_count['value']; - if (!$list_count) $list_count = 20; - $page_count = $output->page_count['value']; - if (!$page_count) $page_count = 10; - $page = $output->page['value']; - if (!$page) - $page = 1; - - // Get a total page - if ($total_count) $total_page = (int)(($total_count - 1) / $list_count) + 1; - else $total_page = 1; - - // Check Page variables - if ($page > $total_page) $page = $total_page; - $start_count = ($page - 1) * $list_count; - // Add a condition to use an index when sorting in order by list_order, update_order - if ($output->order) { - $conditions = $this->getConditionList($output); - if (!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach ($output->order as $key => $val) { - $col = $val[0]; - if (!in_array($col, array('list_order', 'update_order'))) - continue; - if ($condition) - $condition .= sprintf(' and %s < 2100000000 ', $col); - else - $condition = sprintf(' where %s < 2100000000 ', $col); - } - } - } - - if (count($output->groups)) { - /* - var_dump("= column output start = "); - var_dump(sizeof ($output->columns) . " = end length == "); - var_dump($output->columns); - var_dump("= column output end = " . "\n"); - var_dump($output->groups); - var_dump("=== " . "\n"); - var_dump(debug_backtrace()); - - foreach($output->columns as $key => $val) { - $name = $val['name']; - $alias = $val['alias']; - } */ - $group_list = array(); - foreach ($output->groups as $gkey => $gval) { - foreach ($output->columns as $key => $val) { - $name = $val['name']; - $alias = $val['alias']; - if (trim($name) == trim($gval)) { - $group_list[] = $alias; - break; - } - } - - if($column_list[$gval]) $output->arg_columns[] = $column_list[$gval]; - - } - $groupby_query = sprintf(' group by %s', implode(',', $group_list)); - // var_dump($query); - } - - if ($output->order) { - foreach ($output->order as $key => $val) { - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if (count($index_list)) $orderby_query = ' order by ' . implode(',', $index_list); - } - - if(count($output->arg_columns)) - { - $columns = join(',',$output->arg_columns); - } - - $query = sprintf("select %s from %s %s %s", $columns, implode(',', $table_list), implode(' ', $left_join), $condition); - $query = sprintf('%s offset %d limit %d', $query, $start_count, $list_count); - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - - $result = $this->_query($query); - if ($this->isError()) { - $buff = new Object(); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array(); - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - - $virtual_no = $total_count - ($page - 1) * $list_count; - while ($tmp = pg_fetch_object($result)) { - $data[$virtual_no--] = $tmp; - } - - $buff = new Object(); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = $data; - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; + + function getParser(){ + return new DBParser('"'); } } diff --git a/classes/db/queryparts/limit/Limit.class.php b/classes/db/queryparts/limit/Limit.class.php index fd8147e47..743b25095 100644 --- a/classes/db/queryparts/limit/Limit.class.php +++ b/classes/db/queryparts/limit/Limit.class.php @@ -19,6 +19,14 @@ else return false; } + function getOffset(){ + return $this->start; + } + + function getLimit(){ + return $this->list_count; + } + function toString(){ if ($this->page) return $this->start . ' , ' . $this->list_count; else return $this->list_count; From d7cf3cb7317b005b15c51abfb2347307a6618b6e Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 7 Jun 2011 16:17:36 +0000 Subject: [PATCH 32/82] Removed extra methods from Firebird, Msssql and SqlLite db classes. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8455 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBFirebird.class.php | 397 +----------------------- classes/db/DBMssql.class.php | 481 +---------------------------- classes/db/DBSqlite3_pdo.class.php | 361 ---------------------- 3 files changed, 16 insertions(+), 1223 deletions(-) diff --git a/classes/db/DBFirebird.class.php b/classes/db/DBFirebird.class.php index c44ae1e1a..209731755 100644 --- a/classes/db/DBFirebird.class.php +++ b/classes/db/DBFirebird.class.php @@ -616,161 +616,26 @@ } } - /** - * @brief Return conditional clause - **/ - function getCondition($output) { - if(!$output->conditions) return; - $condition = $this->_getCondition($output->conditions,$output->column_type,$output->_tables); - if($condition) $condition = ' where '.$condition; - return $condition; - } - - function getLeftCondition($conditions,$column_type,$tables){ - return $this->_getCondition($conditions,$column_type,$tables); - } - - - function _getCondition($conditions,$column_type,$tables) { - $condition = ''; - foreach($conditions as $val) { - $sub_condition = ''; - foreach($val['condition'] as $v) { - if(!isset($v['value'])) continue; - if($v['value'] === '') continue; - if(!in_array(gettype($v['value']), array('string', 'integer', 'double'))) continue; - - $name = $v['column']; - $operation = $v['operation']; - $value = $v['value']; - $type = $this->getColumnType($column_type,$name); - $pipe = $v['pipe']; - - $value = $this->getConditionValue('"'.$name.'"', $value, $operation, $type, $column_type); - if(!$value) $value = $v['value']; - - $name = $this->autoQuotes($name); - $value = $this->autoValueQuotes($value, $tables); - - $str = $this->getConditionPart($name, $value, $operation); - if($sub_condition) $sub_condition .= ' '.$pipe.' '; - $sub_condition .= $str; - } - if($sub_condition) { - if($condition && $val['pipe']) $condition .= ' '.$val['pipe'].' '; - $condition .= '('.$sub_condition.')'; - } - } - - return $condition; - } /** * @brief Handle the insertAct **/ function _executeInsertAct($output) { - // tables - foreach($output->tables as $key => $val) { - $table_list[] = '"'.$this->prefix.$val.'"'; - } - // Columns - foreach($output->columns as $key => $val) { - $name = $val['name']; - $value = $val['value']; - - $value = str_replace("'", "`", $value); - - if($output->column_type[$name]=="text" || $output->column_type[$name]=="bigtext"){ - if(!isset($val['value'])) continue; - $blh = ibase_blob_create($this->fd); - ibase_blob_add($blh, $value); - $value = ibase_blob_close($blh); - } - else if($output->column_type[$name]!='number') { -// if(!$value) $value = 'null'; - } - else $this->_filterNumber(&$value); - - $column_list[] = '"'.$name.'"'; - $value_list[] = $value; - $questions[] = "?"; - } - - $query = sprintf("insert into %s (%s) values (%s);", implode(',',$table_list), implode(',',$column_list), implode(',', $questions)); - - $result = $this->_query($query, $value_list); - if(!$this->transaction_started) @ibase_commit($this->fd); - return $result; + } /** * @brief handles updateAct **/ function _executeUpdateAct($output) { - // Tables - foreach($output->tables as $key => $val) { - $table_list[] = '"'.$this->prefix.$val.'"'; - } - // Columns - foreach($output->columns as $key => $val) { - if(!isset($val['value'])) continue; - $name = $val['name']; - $value = $val['value']; - - $value = str_replace("'", "`", $value); - - if(strpos($name,'.')!==false&&strpos($value,'.')!==false) $column_list[] = $name.' = '.$value; - else { - if($output->column_type[$name]=="text" || $output->column_type[$name]=="bigtext"){ - $blh = ibase_blob_create($this->fd); - ibase_blob_add($blh, $value); - $value = ibase_blob_close($blh); - } - else if($output->column_type[$name]=='number' || - $output->column_type[$name]=='bignumber' || - $output->column_type[$name]=='float') { - // put double-quotes on column name if an expression is entered - preg_match("/(?i)[a-z][a-z0-9_]+/", $value, $matches); - - foreach($matches as $key => $val) { - $value = str_replace($val, "\"".$val."\"", $value); - } - - if($matches != null) { - $column_list[] = sprintf("\"%s\" = %s", $name, $value); - continue; - } - } - - $values[] = $value; - $column_list[] = sprintf('"%s" = ?', $name); - } - } - // conditional clause - $condition = $this->getCondition($output); - - $query = sprintf("update %s set %s %s;", implode(',',$table_list), implode(',',$column_list), $condition); - $result = $this->_query($query, $values); - if(!$this->transaction_started) @ibase_commit($this->fd); - return $result; + } /** * @brief handles deleteAct **/ function _executeDeleteAct($output) { - // Tables - foreach($output->tables as $key => $val) { - $table_list[] = '"'.$this->prefix.$val.'"'; - } - // List the conditional clause - $condition = $this->getCondition($output); - - $query = sprintf("delete from %s %s;", implode(',',$table_list), $condition); - - $result = $this->_query($query); - if(!$this->transaction_started) @ibase_commit($this->fd); - return $result; + } /** @@ -780,263 +645,9 @@ * it supports a method as navigation **/ function _executeSelectAct($output) { - // Tables - $table_list = array(); - foreach($output->tables as $key => $val) { - $table_list[] = sprintf("\"%s%s\" as \"%s\"", $this->prefix, $val, $key); - } - - $left_join = array(); - // why??? - $left_tables= (array)$output->left_tables; - - foreach($left_tables as $key => $val) { - $condition = $this->getLeftCondition($output->left_conditions[$key],$output->column_type,$output->_tables); - if($condition){ - $left_join[] = $val . ' "'.$this->prefix.$output->_tables[$key].'" as "'.$key.'" on (' . $condition . ')'; - } - } - - $click_count = array(); - if(!$output->columns){ - $output->columns = array(array('name'=>'*')); - } - - $column_list = array(); - foreach($output->columns as $key => $val) { - $name = $val['name']; - $alias = $val['alias']; - if($val['click_count']) $click_count[] = $val['name']; - - if($alias == "") - $column_list[] = $this->autoQuotes($name); - else - $column_list[$alias] = sprintf("%s as \"%s\"", $this->autoQuotes($name), $alias); - } - $columns = implode(',',$column_list); - - $condition = $this->getCondition($output); - - $output->column_list = $column_list; - if($output->list_count && $output->page) return $this->_getNavigationData($table_list, $columns, $left_join, $condition, $output); - // query added in the condition to use an index when ordering by list_order, update_order - if($output->order) { - $conditions = $this->getConditionList($output); - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and "%s" < 2100000000 ', $col); - else $condition = sprintf(' where "%s" < 2100000000 ', $col); - } - } - } - // apply when using list_count - if($output->list_count['value']) $limit = sprintf('FIRST %d', $output->list_count['value']); - else $limit = ''; - - - if($output->groups) { - foreach($output->groups as $key => $val) { - $group_list[] = $this->autoQuotes($val); - if($column_list[$val]) $output->arg_columns[] = $column_list[$val]; - } - if(count($group_list)) $groupby_query = sprintf(" group by %s", implode(",",$group_list)); - } - - if($output->order) { - foreach($output->order as $key => $val) { - $index_list[] = sprintf("%s %s", $this->autoQuotes($val[0]), $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $orderby_query = sprintf(" order by %s", implode(",",$index_list)); - } - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - if(strpos($col,'"')===false && strpos($col,' ')==false) $columns[] = '"'.$col.'"'; - else $columns[] = $col; - } - - $columns = join(',',$columns); - } - - $query = sprintf("select %s from %s %s %s %s", $columns, implode(',',$table_list),implode(' ',$left_join), $condition, $groupby_query.$orderby_query); - $query .= ";"; - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_query($query); - if($this->isError()) { - if(!$this->transaction_started) @ibase_rollback($this->fd); - return; - } - - $data = $this->_fetch($result, $output); - if(!$this->transaction_started) @ibase_commit($this->fd); - - if(count($click_count)>0 && count($output->conditions)>0){ - $_query = ''; - foreach($click_count as $k => $c) $_query .= sprintf(',%s=%s+1 ',$c,$c); - $_query = sprintf('update %s set %s %s',implode(',',$table_list), substr($_query,1), $condition); - $this->_query($_query); - } - - $buff = new Object(); - $buff->data = $data; - return $buff; + } - /** - * @brief paginates when navigation info exists in the query xml - * - * it is convenient although its structure is not good .. -_-; - **/ - function _getNavigationData($table_list, $columns, $left_join, $condition, $output) { - require_once(_XE_PATH_.'classes/page/PageHandler.class.php'); - - $column_list = $output->column_list; - - $query_groupby = ''; - if ($output->groups) { - foreach ($output->groups as $key => $val){ - $group_list[] = $this->autoQuotes($val); - if($column_list[$val]) $output->arg_columns[] = $column_list[$val]; - } - if (count($group_list)) $query_groupby = sprintf(" GROUP BY %s", implode(", ", $group_list)); - } - - /* - // modified to get the number of rows by SELECT query with group by clause - // activate the commented codes when you confirm it works correctly - // - $count_condition = strlen($query_groupby) ? sprintf('%s group by %s', $condition, $query_groupby) : $condition; - $total_count = $this->getCountCache($output->tables, $count_condition); - if($total_count === false) { - $count_query = sprintf('select count(*) as "count" from %s %s %s', implode(', ', $table_list), implode(' ', $left_join), $count_condition); - if (count($output->groups)) - $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); - $result = $this->_query($count_query); - $count_output = $this->_fetch($result); - $total_count = (int)$count_output->count; - $this->putCountCache($output->tables, $count_condition, $total_count); - } - */ - // total number of rows - $count_query = sprintf("select count(*) as \"count\" from %s %s %s", implode(',',$table_list),implode(' ',$left_join), $condition); - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id . ' count(*)'):''; - $result = $this->_query($count_query); - $count_output = $this->_fetch($result); - if(!$this->transaction_started) @ibase_commit($this->fd); - - $total_count = (int)$count_output->count; - - $list_count = $output->list_count['value']; - if(!$list_count) $list_count = 20; - $page_count = $output->page_count['value']; - if(!$page_count) $page_count = 10; - $page = $output->page['value']; - if(!$page) $page = 1; - // total pages - if($total_count) $total_page = (int)( ($total_count-1) / $list_count) + 1; - else $total_page = 1; - // check the page variables - if($page > $total_page) $page = $total_page; - $start_count = ($page-1)*$list_count; - // query added in the condition to use an index when ordering by list_order, update_order - if($output->order) { - $conditions = $this->getConditionList($output); - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and "%s" < 2100000000 ', $col); - else $condition = sprintf(' where "%s" < 2100000000 ', $col); - } - } - } - - $limit = sprintf('FIRST %d SKIP %d ', $list_count, $start_count); - - - if($output->order) { - foreach($output->order as $key => $val) { - $index_list[] = sprintf("%s %s", $this->autoQuotes($val[0]), $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $orderby_query = sprintf(" ORDER BY %s", implode(",",$index_list)); - } - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - if(strpos($col,'"')===false && strpos($col,' ')==false) $columns[] = '"'.$col.'"'; - else $columns[] = $col; - } - - $columns = join(',',$columns); - } - - $query = sprintf('SELECT %s %s FROM %s %s %s, %s', $limit, $columns, implode(',',$table_list), implode(' ',$left_join), $condition, $groupby_query.$orderby_query); - $query .= ";"; - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_query($query); - if($this->isError()) { - if(!$this->transaction_started) @ibase_rollback($this->fd); - - $buff = new Object(); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array(); - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - - $virtual_no = $total_count - ($page-1)*$list_count; - while($tmp = ibase_fetch_object($result)) { - foreach($tmp as $key => $val){ - $type = $output->column_type[$key]; - // $key value is an alias when type value is null. get type by finding the actual column name - if($type == null && $output->columns && count($output->columns)) { - foreach($output->columns as $cols) { - if($cols['alias'] == $key) { - // checks if the format is table.column or a regular expression - preg_match("/\w+[.](\w+)/", $cols['name'], $matches); - if($matches) { - $type = $output->column_type[$matches[1]]; - } - else { - $type = $output->column_type[$cols['name']]; - } - } - } - } - - if(($type == "text" || $type == "bigtext") && $tmp->{$key}) { - $blob_data = ibase_blob_info($tmp->{$key}); - $blob_hndl = ibase_blob_open($tmp->{$key}); - $tmp->{$key} = ibase_blob_get($blob_hndl, $blob_data[0]); - ibase_blob_close($blob_hndl); - } - } - - $data[$virtual_no--] = $tmp; - } - - if(!$this->transaction_started) @ibase_commit($this->fd); - - $buff = new Object(); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = $data; - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } } return new DBFireBird; diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index 272412027..2feada8c3 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -89,8 +89,7 @@ array( 'Database' => $this->database,'UID'=>$this->userid,'PWD'=>$this->password )); -// Check connections - + // Check connections if($this->conn){ $this->is_connected = true; $this->password = md5($this->password); @@ -113,6 +112,7 @@ /** * @brief handles quatation of the string variables from the query **/ + // TODO See what to do about this function addQuotes($string) { if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); //if(!is_numeric($string)) $string = str_replace("'","''",$string); @@ -408,217 +408,29 @@ } } - /** - * @brief Return conditional clause - **/ - function getCondition($output) { - if(!$output->conditions) return; - $condition = $this->_getCondition($output->conditions,$output->column_type); - if($condition) $condition = ' where '.$condition; - return $condition; - } - - function getLeftCondition($conditions,$column_type){ - return $this->_getCondition($conditions,$column_type); - } - - - function _getCondition($conditions,$column_type) { - $condition = ''; - - foreach($conditions as $val) { - $sub_condition = ''; - foreach($val['condition'] as $v) { - if(!isset($v['value'])) continue; - if($v['value'] === '') continue; - if(!in_array(gettype($v['value']), array('string', 'integer', 'double'))) continue; - - $name = $v['column']; - if(preg_match('/^substr\(/i',$name)) $name = preg_replace('/^substr\(/i','substring(',$name); - $operation = $v['operation']; - $value = $v['value']; - - $type = $this->getColumnType($column_type,$name); - $pipe = $v['pipe']; - - $value = $this->getConditionValue($name, $value, $operation, $type, $column_type); - if(!$value) $value = $v['value']; - $str = $this->getConditionPart($name, $value, $operation); - if($sub_condition) $sub_condition .= ' '.$pipe.' '; - $sub_condition .= $str; - } - if($sub_condition) { - if($condition && $val['pipe']) $condition .= ' '.$val['pipe'].' '; - $condition .= '('.$sub_condition.')'; - } - } - return $condition; - } - - - function getConditionValue($name, $value, $operation, $type, $column_type) { - - if($type == 'number') { - if(strpos($value,',')===false && strpos($value,'(')===false){ - - if(is_integer($value)){ - $this->param[] = array('type'=>'number','value'=>(int)$value); - return '?'; - }else{ - return $value; - } - } - } - - if(strpos($name,'.')!==false&&strpos($value,'.')!==false) { - list($table_name, $column_name) = explode('.',$value); - if($column_type[$column_name]){ - return $value; - } - } - - switch($operation) { - case 'like_prefix' : - $value = preg_replace('/(^\'|\'$){1}/','',$value); - $this->param[] = array('type'=>$column_type[$name],'value'=>$value); - - $value = "? + '%'"; - break; - case 'like_tail' : - $value = preg_replace('/(^\'|\'$){1}/','',$value); - $this->param[] = array('type'=>$column_type[$name],'value'=>$value); - - $value = "'%' + ?"; - break; - case 'like' : - $value = preg_replace('/(^\'|\'$){1}/','',$value); - $this->param[] = array('type'=>$column_type[$name],'value'=>$value); - - $value = "'%' + ? + '%'"; - break; - case 'notin' : - preg_match_all('/,?\'([^\']*)\'/',$value,$match); - $val = array(); - foreach($match[1] as $k => $v){ - $this->param[] = array('type'=>$column_type[$name],'value'=>trim($v)); - $val[] ='?'; - } - $value = join(',',$val); - break; - case 'in' : - preg_match_all('/,?\'([^\']*)\'/',$value,$match); - $val = array(); - foreach($match[1] as $k => $v){ - $this->param[] = array('type'=>$column_type[$name],'value'=>trim($v)); - $val[] ='?'; - } - $value = join(',',$val); - break; - default: - $value = preg_replace('/(^\'|\'$){1}/','',$value); - $this->param[] = array('type'=>$column_type[$name],'value'=>$value); - $value = '?'; - break; - } - - return $value; - } - + /** * @brief Handle the insertAct **/ - function _executeInsertAct($output) { - - // List tables - foreach($output->tables as $key => $val) { - $table_list[] = '['.$this->prefix.$val.']'; - } - // List columns - foreach($output->columns as $key => $val) { - $name = $val['name']; - $value = $val['value']; - - if($output->column_type[$name]!='number') { - $value = $this->addQuotes($value); - if(!$value) $value = ''; - } elseif(is_numeric($value)){ - if(!$value) $value = ''; - $value = (int)$value; - } elseif(!$value){ - $value = ''; - } - // sql injection 문제로 xml ì„ ì–¸ì´ numberì¸ ê²½ìš°ì´ë©´ì„œ 넘어온 ê°’ì´ ìˆ«ìží˜•ì´ ì•„ë‹ˆë©´ 숫ìží˜•으로 ê°•ì œ 형변환 - else $this->_filterNumber(&$value); - - $column_list[] = '['.$name.']'; - $value_list[] = '?'; - - $this->param[] = array('type'=>$output->column_type[$name], 'value'=>$value); - } - - $query = sprintf("insert into %s (%s) values (%s);", implode(',',$table_list), implode(',',$column_list), implode(',', $value_list)); - + // TODO Lookup _filterNumber against sql injection - see if it is still needed and how to integrate + function _executeInsertAct($queryObject) { + $query = ''; return $this->_query($query); } /** * @brief Handle updateAct **/ - function _executeUpdateAct($output) { - // List tables - foreach($output->tables as $key => $val) { - $table_list[] = '['.$this->prefix.$val.']'; - } - -// List columns - - foreach($output->columns as $key => $val) { - if(!isset($val['value'])) continue; - - $name = $val['name']; - $value = $val['value']; - if(strpos($name,'.')!==false&&strpos($value,'.')!==false){ - $column_list[] = $name.' = '.$value; - } else { - if($output->column_type[$name]!='number'){ - $value = $this->addQuotes($value); - if(!$value) $value = ''; - - $this->param[] = array('type'=>$output->column_type[$name], 'value'=>$value); - $column_list[] = sprintf("[%s] = ?", $name); - }elseif(!$value || is_numeric($value)){ - $value = (int)$value; - - $this->param[] = array('type'=>$output->column_type[$name], 'value'=>$value); - $column_list[] = sprintf("[%s] = ?", $name); - }else{ - if(!$value) $value = ''; - $this->_filterNumber(&$value); - $column_list[] = sprintf("[%s] = %s", $name, $value); - } - } - } - // List the conditional clause - $condition = $this->getCondition($output); - - $query = sprintf("update %s set %s %s", implode(',',$table_list), implode(',',$column_list), $condition); - + function _executeUpdateAct($queryObject) { + $query = ''; return $this->_query($query); } /** * @brief Handle deleteAct **/ - function _executeDeleteAct($output) { - // List tables - foreach($output->tables as $key => $val) { - $table_list[] = '['.$this->prefix.$val.']'; - } - // List the conditional clause - $condition = $this->getCondition($output); - - $query = sprintf("delete from %s %s", implode(',',$table_list), $condition); - + function _executeDeleteAct($queryObject) { + $query = ''; return $this->_query($query); } @@ -628,115 +440,10 @@ * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($output) { - // List tables - $table_list = array(); - foreach($output->tables as $key => $val) { - $table_list[] = '['.$this->prefix.$val.'] as '.$key; - } - - $left_join = array(); - // why??? - $left_tables= (array)$output->left_tables; - - foreach($left_tables as $key => $val) { - $condition = $this->_getCondition($output->left_conditions[$key],$output->column_type); - if($condition){ - $left_join[] = $val . ' ['.$this->prefix.$output->_tables[$key].'] as '.$key . ' on (' . $condition . ')'; - } - } - - $click_count = array(); - if(!$output->columns){ - $output->columns = array(array('name'=>'*')); - } - - $column_list = array(); - foreach($output->columns as $key => $val) { - $name = $val['name']; - if(preg_match('/^substr\(/i',$name)) $name = preg_replace('/^substr\(/i','substring(',$name); - $alias = $val['alias']; - if($val['click_count']) $click_count[] = $val['name']; - - if(substr($name,-1) == '*') { - $column_list[] = $name; - } elseif(strpos($name,'.')===false && strpos($name,'(')===false) { - if($alias) $column_list[$alias] = sprintf('[%s] as [%s]', $name, $alias); - else $column_list[] = sprintf('[%s]',$name); - } else { - if($alias) $column_list[$alias] = sprintf('%s as [%s]', $name, $alias); - else $column_list[] = sprintf('%s',$name); - } - } - $columns = implode(',',$column_list); - - $condition = $this->getCondition($output); - - $output->column_list = $column_list; - if($output->list_count && $output->page) return $this->_getNavigationData($table_list, $columns, $left_join, $condition, $output); - // Add a condition to use an index when sorting in order by list_order, update_order - if($output->order) { - $conditions = $this->getConditionList($output); - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' where %s < 2100000000 ', $col); - } - } - } - - if(count($output->groups)){ - foreach($output->groups as $k => $v ){ - if(preg_match('/^substr\(/i',$v)) $output->groups[$k] = preg_replace('/^substr\(/i','substring(',$v); - if($column_list[$v]) $output->arg_columns[] = $column_list[$v]; - } - $groupby_query = sprintf(' group by %s', implode(',',$output->groups)); - } - - if($output->order && !preg_match('/count\(\*\)/i',$columns) ) { - foreach($output->order as $key => $val) { - if(preg_match('/^substr\(/i',$val[0])) $name = preg_replace('/^substr\(/i','substring(',$val[0]); - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $orderby_query = ' order by '.implode(',',$index_list); - } - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - unset($tmpCol); - $tmpCol = explode('.', $col); - if(isset($tmpCol[1])) $col = $tmpCol[1]; - - if(strpos($col,'[')===false && strpos($col,' ')==false) $col = '['.$col.']'; - if(isset($tmpCol[1])) $col = $tmpCol[0].'.'.$col; - - $columns[] = $col; - } - - $columns = join(',',$columns); - } - - $query = sprintf("%s from %s %s %s %s", $columns, implode(',',$table_list),implode(' ',$left_join), $condition, $groupby_query.$orderby_query); - // Apply when using list_count - if($output->list_count['value']) $query = sprintf('select top %d %s', $output->list_count['value'], $query); - else $query = "select ".$query; - + function _executeSelectAct($queryObject) { $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; $result = $this->_query($query); if($this->isError()) return; - - if(count($click_count)>0 && count($output->conditions)>0){ - $_query = ''; - foreach($click_count as $k => $c) $_query .= sprintf(',%s=%s+1 ',$c,$c); - $_query = sprintf('update %s set %s %s',implode(',',$table_list), substr($_query,1), $condition); - $this->_query($_query); - } - $data = $this->_fetch($result); $buff = new Object(); @@ -744,171 +451,7 @@ return $buff; } - /** - * @brief Paging is handled if navigation information exists in the query xml - * - * It is quite convenient although its structure is not good at all .. -_-; - **/ - function _getNavigationData($table_list, $columns, $left_join, $condition, $output) { - require_once(_XE_PATH_.'classes/page/PageHandler.class.php'); - - $column_list = $output->column_list; - - // Get a total count - if(count($output->groups)){ - foreach($output->groups as $k => $v ){ - if(preg_match('/^substr\(/i',$v)) $output->groups[$k] = preg_replace('/^substr\(/i','substring(',$v); - if($column_list[$v]) $output->arg_columns[] = $column_list[$v]; - } - $count_condition = sprintf('%s group by %s', $condition, implode(', ', $output->groups)); - }else{ - $count_condition = $condition; - } - - $count_query = sprintf("select count(*) as count from %s %s %s", implode(', ', $table_list), implode(' ', $left_join), $count_condition); - if (count($output->groups)) $count_query = sprintf('select count(*) as count from (%s) xet', $count_query); - - $param = $this->param; - - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id . ' count(*)'):''; - $result = $this->_query($count_query); - - $this->param = $param; - $count_output = $this->_fetch($result); - - $total_count = (int)$count_output->count; - - $list_count = $output->list_count['value']; - if(!$list_count) $list_count = 20; - $page_count = $output->page_count['value']; - if(!$page_count) $page_count = 10; - $page = $output->page['value']; - if(!$page) $page = 1; - // Get a total page - if($total_count) $total_page = (int)( ($total_count-1) / $list_count) + 1; - else $total_page = 1; - // Check Page variables - if($page > $total_page) $page = $total_page; - $start_count = ($page-1)*$list_count; - // Add a condition to use an index when sorting in order by list_order, update_order - $conditions = $this->getConditionList($output); - if($output->order) { - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' %s < 2100000000 ', $col); - } - } - } - - // Add group by clause - if(count($output->groups)){ - foreach($output->groups as $k => $v ){ - if(preg_match('/^substr\(/i',$v)) $output->groups[$k] = preg_replace('/^substr\(/i','substring(',$v); - if($column_list[$v]) $output->arg_columns[] = $column_list[$v]; - } - - $group = sprintf('group by %s', implode(',',$output->groups)); - } - - // Add order by clause - $order_targets = array(); - if($output->order) { - foreach($output->order as $key => $val) { - if(preg_match('/^substr\(/i',$val[0])) $name = preg_replace('/^substr\(/i','substring(',$val[0]); - $order_targets[$val[0]] = $val[1]; - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $order .= 'order by '.implode(',',$index_list); - } - if(!count($order_targets)) { - if(in_array('list_order',$conditions)) $order_targets['list_order'] = 'asc'; - else $order_targets['xe_seq'] = 'desc'; - } - - if(count($output->arg_columns)) - { - $columns = array(); - foreach($output->arg_columns as $col){ - unset($tmpCol); - $tmpCol = explode('.', $col); - if(isset($tmpCol[1])) $col = $tmpCol[1]; - - if(strpos($col,'[')===false && strpos($col,' ')==false) $col = '['.$col.']'; - if(isset($tmpCol[1])) $col = $tmpCol[0].'.'.$col; - - $columns[] = $col; - } - - $columns = join(',',$columns); - } - - if($start_count<1) { - $query = sprintf('select top %d %s from %s %s %s %s %s', $list_count, $columns, implode(',',$table_list), implode(' ',$left_join), $condition, $group, $order); - - } else { - foreach($order_targets as $k => $v) { - $first_columns[] = sprintf('%s(%s) as %s', $v=='asc'?'max':'min', $k, $k); - $first_sub_columns[] = $k; - } - - // Fetch values to sort - $param = $this->param; - $first_query = sprintf("select %s from (select top %d %s from %s %s %s %s %s) xet", implode(',',$first_columns), $start_count, implode(',',$first_sub_columns), implode(',',$table_list), implode(' ',$left_join), $condition, $group, $order); - $result = $this->_query($first_query); - $this->param = $param; - $tmp = $this->_fetch($result); - - - - // Re-execute a query by using fetched values - $sub_cond = array(); - foreach($order_targets as $k => $v) { - $sub_cond[] = sprintf("%s %s '%s'", $k, $v=='asc'?'>':'<', $tmp->{$k}); - } - $sub_condition = ' and( '.implode(' and ',$sub_cond).' )'; - - if($condition) $condition .= $sub_condition; - else $condition = ' where '.$sub_condition; - $query = sprintf('select top %d %s from %s %s %s %s %s', $list_count, $columns, implode(',',$table_list), implode(' ',$left_join), $condition, $group, $order); - } - - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_query($query); - - if($this->isError()) { - $buff = new Object(); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array(); - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - - $virtual_no = $total_count - ($page-1)*$list_count; - - $output = $this->_fetch($result); - if(!is_array($output)) $output = array($output); - - foreach($output as $k => $v) { - $data[$virtual_no--] = $v; - } - - $buff = new Object(); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = $data; - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } - + } return new DBMssql; diff --git a/classes/db/DBSqlite3_pdo.class.php b/classes/db/DBSqlite3_pdo.class.php index b2f9abd00..35f496679 100644 --- a/classes/db/DBSqlite3_pdo.class.php +++ b/classes/db/DBSqlite3_pdo.class.php @@ -399,76 +399,10 @@ } } - /** - * @brief Return conditional clause(where) - **/ - function getCondition($output) { - if(!$output->conditions) return; - $condition = $this->_getCondition($output->conditions,$output->column_type); - if($condition) $condition = ' where '.$condition; - return $condition; - } - - function getLeftCondition($conditions,$column_type){ - return $this->_getCondition($conditions,$column_type); - } - - - function _getCondition($conditions,$column_type) { - $condition = ''; - foreach($conditions as $val) { - $sub_condition = ''; - foreach($val['condition'] as $v) { - if(!isset($v['value'])) continue; - if($v['value'] === '') continue; - if(!in_array(gettype($v['value']), array('string', 'integer', 'double', 'array'))) continue; - - $name = $v['column']; - $operation = $v['operation']; - $value = $v['value']; - $type = $this->getColumnType($column_type,$name); - $pipe = $v['pipe']; - - $value = $this->getConditionValue($name, $value, $operation, $type, $column_type); - if(!$value) $value = $v['value']; - $str = $this->getConditionPart($name, $value, $operation); - if($sub_condition) $sub_condition .= ' '.$pipe.' '; - $sub_condition .= $str; - } - if($sub_condition) { - if($condition && $val['pipe']) $condition .= ' '.$val['pipe'].' '; - $condition .= '('.$sub_condition.')'; - } - } - return $condition; - } - /** * @brief insertAct **/ function _executeInsertAct($output) { - // list tables - foreach($output->tables as $key => $val) { - $table_list[] = $this->prefix.$val; - } - // list columns - foreach($output->columns as $key => $val) { - $name = $val['name']; - $value = $val['value']; - - $key_list[] = $name; - - if($output->column_type[$name]!='number') $val_list[] = $this->addQuotes($value); - else { - $this->_filterNumber(&$value); - $val_list[] = $value; - } - - $prepare_list[] = '?'; - } - - $query = sprintf("INSERT INTO %s (%s) VALUES (%s);", implode(',',$table_list), implode(',',$key_list), implode(',',$prepare_list)); - $this->_prepare($query); $val_count = count($val_list); @@ -481,59 +415,6 @@ * @brief updateAct **/ function _executeUpdateAct($output) { - $table_count = count(array_values($output->tables)); - // If a target table is one - if($table_count == 1) { - // list tables - list($target_table) = array_values($output->tables); - $target_table = $this->prefix.$target_table; - // list columns - foreach($output->columns as $key => $val) { - if(!isset($val['value'])) continue; - $name = $val['name']; - $value = $val['value']; - if(strpos($name,'.')!==false&&strpos($value,'.')!==false) $column_list[] = $name.' = '.$value; - else { - if($output->column_type[$name]!='number') $value = "'".$this->addQuotes($value)."'"; - else $this->_filterNumber(&$value); - - $column_list[] = sprintf("%s = %s", $name, $value); - } - } - // List where cluase - $condition = $this->getCondition($output); - - $query = sprintf("update %s set %s %s", $target_table, implode(',',$column_list), $condition); - // If tables to update are morea than two (In sqlite, it is possible to update a single table only. Let me know if you know a better way) - } elseif($table_count == 2) { - // List tables - foreach($output->tables as $key => $val) { - $table_list[$val] = $this->prefix.$key; - } - list($source_table, $target_table) = array_values($table_list); - // List where cluase - $condition = $this->getCondition($output); - foreach($table_list as $key => $val) { - $condition = eregi_replace($key.'\\.', $val.'.', $condition); - } - // List columns - foreach($output->columns as $key => $val) { - if(!isset($val['value'])) continue; - $name = $val['name']; - $value = $val['value']; - list($s_prefix, $s_column) = explode('.',$name); - list($t_prefix, $t_column) = explode('.',$value); - - $s_table = $table_list[$s_prefix]; - $t_table = $table_list[$t_prefix]; - $column_list[] = sprintf(' %s = (select %s from %s %s) ', $s_column, $t_column, $t_table, $condition); - } - - $query = sprintf('update %s set %s where exists(select * from %s %s)', $source_table, implode(',', $column_list), $target_table, $condition); - } else { - return; - } - $this->_prepare($query); return $this->_execute(); } @@ -542,15 +423,6 @@ * @brief deleteAct **/ function _executeDeleteAct($output) { - // List tables - foreach($output->tables as $key => $val) { - $table_list[] = $this->prefix.$val; - } - // List the conditional clause - $condition = $this->getCondition($output); - - $query = sprintf("delete from %s %s", implode(',',$table_list), $condition); - $this->_prepare($query); return $this->_execute(); } @@ -562,243 +434,10 @@ * navigation method supported **/ function _executeSelectAct($output) { - // List tables - $table_list = array(); - foreach($output->tables as $key => $val) { - $table_list[] = $this->prefix.$val.' as '.$key; - } - - $left_join = array(); - // why??? - $left_tables= (array)$output->left_tables; - - foreach($left_tables as $key => $val) { - $condition = $this->_getCondition($output->left_conditions[$key],$output->column_type); - if($condition){ - $left_join[] = $val . ' '.$this->prefix.$output->_tables[$key].' as '.$key . ' on (' . $condition . ')'; - } - } - - - $click_count = array(); - if(!$output->columns){ - $output->columns = array(array('name'=>'*')); - } - - $column_list = array(); - foreach($output->columns as $key => $val) { - $name = $val['name']; - $alias = $val['alias']; - if($val['click_count']) $click_count[] = $val['name']; - - if(substr($name,-1) == '*') { - $column_list[] = $name; - } elseif(strpos($name,'.')===false && strpos($name,'(')===false) { - if($alias) $column_list[$alias] = sprintf('%s as %s', $name, $alias); - else $column_list[] = sprintf('%s',$name); - } else { - if($alias) $column_list[$alias] = sprintf('%s as %s', $name, $alias); - else $column_list[] = sprintf('%s',$name); - } - } - $columns = implode(',',$column_list); - - $condition = $this->getCondition($output); - - $output->column_list = $column_list; - if($output->list_count && $output->page) return $this->_getNavigationData($table_list, $columns, $left_join, $condition, $output); - // add the condition to the query to use an index for ordering by list_order, update_order - if($output->order) { - $conditions = $this->getConditionList($output); - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' where %s < 2100000000 ', $col); - } - } - } - - if(count($output->groups)){ - $groupby_query = sprintf(' group by %s', implode(',',$output->groups)); - if(count($output->arg_columns)) - { - foreach($output->groups as $group) - { - if($column_list[$group]) $output->arg_columns[] = $column_list[$group]; - } - } - } - - if($output->order) { - foreach($output->order as $key => $val) { - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $orderby_query = ' order by '.implode(',',$index_list); - } - - if(count($output->arg_columns)) - { - $columns = join(',',$output->arg_columns); - } - - $query = sprintf("select %s from %s %s %s %s", $columns, implode(',',$table_list),implode(' ',$left_join), $condition, $groupby_query.$orderby_query); - // apply when using list_count - if($output->list_count['value']) $query = sprintf('%s limit %d', $query, $output->list_count['value']); - - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $this->_prepare($query); - $data = $this->_execute(); - if($this->isError()) return; - - if(count($click_count)>0 && count($output->conditions)>0){ - $_query = ''; - foreach($click_count as $k => $c) $_query .= sprintf(',%s=%s+1 ',$c,$c); - $_query = sprintf('update %s set %s %s',implode(',',$table_list), substr($_query,1), $condition); - $this->_query($_query); - } - $buff = new Object(); $buff->data = $data; return $buff; } - - /** - * @brief Paging is handled if navigation information exists in the query xml - * - * It is quite convenient although its structure is not good at all .. -_-; - **/ - function _getNavigationData($table_list, $columns, $left_join, $condition, $output) { - require_once(_XE_PATH_.'classes/page/PageHandler.class.php'); - - $column_list = $output->column_list; - /* - // Modified to find total number of SELECT queries having group by clause - // If it works correctly, uncomment the following codes - // - $count_condition = count($output->groups) ? sprintf('%s group by %s', $condition, implode(', ', $output->groups)) : $condition; - $total_count = $this->getCountCache($output->tables, $count_condition); - if($total_count === false) { - $count_query = sprintf("select count(*) as count from %s %s %s", implode(', ', $table_list), implode(' ', $left_join), $count_condition); - if (count($output->groups)) - $count_query = sprintf('select count(*) as count from (%s) xet', $count_query); - $result = $this->_query($count_query); - $count_output = $this->_fetch($result); - $total_count = (int)$count_output->count; - $this->putCountCache($output->tables, $count_condition, $total_count); - } - */ - // Get a total count - $count_query = sprintf("select count(*) as count from %s %s %s", implode(',',$table_list),implode(' ',$left_join), $condition); - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id . ' count(*)'):''; - $this->_prepare($count_query); - $count_output = $this->_execute(); - $total_count = (int)$count_output->count; - - $list_count = $output->list_count['value']; - if(!$list_count) $list_count = 20; - $page_count = $output->page_count['value']; - if(!$page_count) $page_count = 10; - $page = $output->page['value']; - if(!$page) $page = 1; - // Get a total page - if($total_count) $total_page = (int)( ($total_count-1) / $list_count) + 1; - else $total_page = 1; - // Check Page variables - if($page > $total_page) $page = $total_page; - $start_count = ($page-1)*$list_count; - // Add a condition to use an index when sorting in order by list_order, update_order - if($output->order) { - $conditions = $this->getConditionList($output); - if(!in_array('list_order', $conditions) && !in_array('update_order', $conditions)) { - foreach($output->order as $key => $val) { - $col = $val[0]; - if(!in_array($col, array('list_order','update_order'))) continue; - if($condition) $condition .= sprintf(' and %s < 2100000000 ', $col); - else $condition = sprintf(' where %s < 2100000000 ', $col); - } - } - } - - if(count($output->groups)){ - $groupby_query = sprintf(' group by %s', implode(',',$output->groups)); - if(count($output->arg_columns)) - { - foreach($output->groups as $group) - { - if($column_list[$group]) $output->arg_columns[] = $column_list[$group]; - } - } - } - - if($output->order) { - foreach($output->order as $key => $val) { - $index_list[] = sprintf('%s %s', $val[0], $val[1]); - if(count($output->arg_columns) && $column_list[$val[0]]) $output->arg_columns[] = $column_list[$val[0]]; - } - if(count($index_list)) $orderby_query = ' order by '.implode(',',$index_list); - } - - if(count($output->arg_columns)) - { - $columns = join(',',$output->arg_columns); - } - - // Return the result - $buff = new Object(); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array(); - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - - // Query Execution - $query = sprintf("select %s from %s %s %s %s", $columns, implode(',',$table_list),implode(' ',$left_join), $condition, $groupby_query.$orderby_query); - $query = sprintf('%s limit %d, %d', $query, $start_count, $list_count); - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - - $this->_prepare($query); - - if($this->isError()) { - $this->setError($this->handler->errorCode(), print_r($this->handler->errorInfo(),true)); - $this->actFinish(); - return $buff; - } - - $this->stmt->execute(); - - if($this->stmt->errorCode() != '00000') { - $this->setError($this->stmt->errorCode(), print_r($this->stmt->errorInfo(),true)); - $this->actFinish(); - return $buff; - } - - $output = null; - $virtual_no = $total_count - ($page-1)*$list_count; - while($tmp = $this->stmt->fetch(PDO::FETCH_ASSOC)) { - unset($obj); - foreach($tmp as $key => $val) { - $pos = strpos($key, '.'); - if($pos) $key = substr($key, $pos+1); - $obj->{$key} = $val; - } - $data[$virtual_no--] = $obj; - } - - $this->stmt = null; - $this->actFinish(); - - $buff = new Object(); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $page; - $buff->data = $data; - - $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); - return $buff; - } } return new DBSqlite3_pdo; From e41c45433e3a35d914c7cf0b76f3c09638a8c970 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 7 Jun 2011 16:21:55 +0000 Subject: [PATCH 33/82] add some unit tests for CUBRID git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8456 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/XmlParser.class.php | 6 +- classes/xml/XmlQueryParser.class.php | 10 +- test-phpUnit/DeleteXmlTest_Cubrid.php | 38 +++ test-phpUnit/ExpressionParserTest.php | 4 +- test-phpUnit/Helper.class.php | 14 ++ test-phpUnit/InsertXmlTest_Cubrid.php | 140 +++++++++++ test-phpUnit/QueryTester.class.php | 322 ++++++++++++++++++++++++++ test-phpUnit/SelectXmlTest_Cubrid.php | 170 ++++++++++++++ test-phpUnit/UpdateXmlTest_Cubrid.php | 84 +++++++ test-phpUnit/config.inc.php | 35 +++ 10 files changed, 814 insertions(+), 9 deletions(-) create mode 100644 test-phpUnit/DeleteXmlTest_Cubrid.php create mode 100644 test-phpUnit/Helper.class.php create mode 100644 test-phpUnit/InsertXmlTest_Cubrid.php create mode 100644 test-phpUnit/QueryTester.class.php create mode 100644 test-phpUnit/SelectXmlTest_Cubrid.php create mode 100644 test-phpUnit/UpdateXmlTest_Cubrid.php create mode 100644 test-phpUnit/config.inc.php diff --git a/classes/xml/XmlParser.class.php b/classes/xml/XmlParser.class.php index adc564b5d..fb63fbed1 100644 --- a/classes/xml/XmlParser.class.php +++ b/classes/xml/XmlParser.class.php @@ -120,10 +120,10 @@ $node_name = strtolower($node_name); $cur_obj = array_pop($this->output); $parent_obj = &$this->output[count($this->output)-1]; - if($this->lang&&$cur_obj->attrs->{'xml:lang'}&&$cur_obj->attrs->{'xml:lang'}!=$this->lang) return; - if($this->lang&&$parent_obj->{$node_name}->attrs->{'xml:lang'}&&$parent_obj->{$node_name}->attrs->{'xml:lang'}!=$this->lang) return; + if(isset($this->lang)&&$cur_obj->attrs->{'xml:lang'}&&$cur_obj->attrs->{'xml:lang'}!=$this->lang) return; + if(isset($this->lang)&&$parent_obj->{$node_name}->attrs->{'xml:lang'}&&$parent_obj->{$node_name}->attrs->{'xml:lang'}!=$this->lang) return; - if($parent_obj->{$node_name}) { + if(isset($parent_obj->{$node_name})) { $tmp_obj = $parent_obj->{$node_name}; if(is_array($tmp_obj)) { array_push($parent_obj->{$node_name}, $cur_obj); diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 2886a507d..243a57548 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -29,14 +29,14 @@ } // singleton - function &getDBParser(){ + /* function &getDBParser(){ static $dbParser; if(!$dbParser){ $oDB = &DB::getInstance(); $dbParser = $oDB->getParser(); } return $dbParser; - } + }*/ function getXmlFileContent($xml_file){ $buff = FileHandler::readFile($xml_file); @@ -45,7 +45,11 @@ unset($buff); return $xml_obj; } - + function &getDBParser(){ + if(!$this->dbParser) + $this->dbParser = new DBParser('"'); + return $this->dbParser; + } } ?> diff --git a/test-phpUnit/DeleteXmlTest_Cubrid.php b/test-phpUnit/DeleteXmlTest_Cubrid.php new file mode 100644 index 000000000..5f27edb8a --- /dev/null +++ b/test-phpUnit/DeleteXmlTest_Cubrid.php @@ -0,0 +1,38 @@ +getNewParserOutputString($xml_file, '"', $argsString); + echo $outputString; + $output = eval($outputString); + + if(!is_a($output, 'Query')){ + if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; + }else { + $db = new DBCubrid(); + $querySql = $db->getDeleteSql($output); + + // Remove whitespaces, tabs and all + $querySql = Helper::cleanQuery($querySql); + $expected = Helper::cleanQuery($expected); + } + + // Test + $this->assertEquals($expected, $querySql); + } + + function test_module_deleteActionForward(){ + $xml_file = _XE_PATH_ . "modules/module/queries/deleteActionForward.xml"; + $argsString = '$args->module = "page"; + $args->type = "page"; + $args->act = "tata";'; + $expected = 'delete from "xe_action_forward" as "action_forward" + where "module" = \'page\' + and "type" = \'page\' + and "act" = \'tata\''; + $this->_test($xml_file, $argsString, $expected); + } + } \ No newline at end of file diff --git a/test-phpUnit/ExpressionParserTest.php b/test-phpUnit/ExpressionParserTest.php index e4e46b43a..ea16176ee 100644 --- a/test-phpUnit/ExpressionParserTest.php +++ b/test-phpUnit/ExpressionParserTest.php @@ -1,6 +1,5 @@ \ No newline at end of file diff --git a/test-phpUnit/InsertXmlTest_Cubrid.php b/test-phpUnit/InsertXmlTest_Cubrid.php new file mode 100644 index 000000000..9edcdf4fe --- /dev/null +++ b/test-phpUnit/InsertXmlTest_Cubrid.php @@ -0,0 +1,140 @@ +getNewParserOutputString($xml_file, '"', $argsString); + //echo $outputString; + $output = eval($outputString); + + if(!is_a($output, 'Query')){ + if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; + }else { + $db = new DBCubrid(); + $querySql = $db->getInsertSql($output); + + // Remove whitespaces, tabs and all + $querySql = Helper::cleanQuery($querySql); + $expected = Helper::cleanQuery($expected); + } + + // Test + $this->assertEquals($expected, $querySql); + } + + function test_module_insertModule(){ + $xml_file = _XE_PATH_ . "modules/module/queries/insertModule.xml"; + $argsString = ' $args->module_category_srl = 0; + $args->browser_title = "test"; + $args->layout_srl = 0; + $args->mlayout_srl = 0; + $args->module = "page"; + $args->mid = "test"; + $args->site_srl = 0; + $args->module_srl = 47374;'; + $expected = 'insert into "xe_modules" + ("site_srl" + , "module_srl" + , "module_category_srl" + , "mid" + , "browser_title" + , "layout_srl" + , "module" + , "is_default" + , "open_rss" + , "regdate" + , "mlayout_srl" + , "use_mobile") + values + (0 + , 47374 + , 0 + , \'test\' + , \'test\' + , 0 + , \'page\' + , \'n\' + , \'y\' + , \''.date("YmdHis").'\' + , 0 + , \'n\')'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_insertSiteTodayStatus(){ + //\''.date("YmdHis").'\' + $xml_file = _XE_PATH_ . "modules/counter/queries/insertTodayStatus.xml"; + $argsString = ' $args->regdate = 0; + $args->unique_visitor = 0; + $args->pageview = 0;'; + $expected = 'insert into "xe_counter_status" + ("regdate" + , "unique_visitor" + , "pageview") + values + (0 + , 0 + , 0)'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_insertCounterLog(){ + $xml_file = _XE_PATH_ . "modules/counter/queries/insertCounterLog.xml"; + $argsString = ' $args->site_srl = 0; + $args->regdate = "20110607120619"; + $args->ipaddress = "127.0.0.1"; + $args->user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24";'; + $expected = 'insert into "xe_counter_log" + ("site_srl", "regdate", "ipaddress", "user_agent") + VALUES (0, \'20110607120619\', \'127.0.0.1\', \'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24\') + '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_insertMember(){ + $xml_file = _XE_PATH_ . "modules/member/queries/insertMember.xml"; + $argsString = ' $args->member_srl = 203; + $args->user_id = "cacao"; + $args->email_address = "teta@ar.ro"; + $args->password = "23e5484cb88f3c07bcce2920a5e6a2a7"; + $args->email_id = "teta"; + $args->email_host = "ar.ro"; + $args->user_name = "trident"; + $args->nick_name = "aloha"; + $args->homepage = "http://jkgjfk./ww"; + $args->allow_mailing = "Y"; + $args->allow_message = "Y"; + $args->denied = "N"; + $args->limit_date = ""; + $args->regdate = "20110607121952"; + $args->change_password_date = "20110607121952"; + $args->last_login = "20110607121952"; + $args->is_admin = "N"; + $args->extra_vars = "O:8:\"stdClass\":2:{s:4:\"body\";s:0:\"\";s:7:\"_filter\";s:6:\"insert\";}"; + $args->list_order = -203; + '; + $expected = 'INSERT INTO "xe_member" + ("member_srl", "user_id", "email_address", "password", "email_id", "email_host", "user_name", "nick_name", + "homepage", "allow_mailing", "allow_message", "denied", "limit_date", "regdate", "change_password_date", + "last_login", "is_admin", "extra_vars", "list_order") + VALUES (203, \'cacao\', \'teta@ar.ro\', \'23e5484cb88f3c07bcce2920a5e6a2a7\', \'teta\', \'ar.ro\', \'trident\', + \'aloha\', \'http://jkgjfk./ww\', \'Y\', \'Y\', \'N\', \'\', \'20110607121952\', \'20110607121952\', + \'20110607121952\', \'N\', \'O:8:"stdClass":2:{s:4:"body";s:0:"";s:7:"_filter";s:6:"insert";}\', -203)'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_insertModuleExtraVars(){ + $xml_file = _XE_PATH_ . "modules/module/queries/insertModuleExtraVars.xml"; + $argsString = ' $args->module_srl = 202; + $args->name = "_filter"; + $args->value = "insert_page"; + '; + $expected = 'INSERT INTO "xe_module_extra_vars" + ("module_srl", "name", "value") + VALUES (202, \'_filter\', \'insert_page\') + '; + $this->_test($xml_file, $argsString, $expected); + } + } \ No newline at end of file diff --git a/test-phpUnit/QueryTester.class.php b/test-phpUnit/QueryTester.class.php new file mode 100644 index 000000000..32b1daa04 --- /dev/null +++ b/test-phpUnit/QueryTester.class.php @@ -0,0 +1,322 @@ +getXmlFileContent($xml_file); + + $dbParser = new DBParser($escape_char); + $parser = new QueryParser($xml_obj->query, $dbParser); + return $parser->toString(); + } + + function getOldParserOutput($query_id, $xml_file){ + $cache_file = _TEST_PATH_ . "cache/".$query_id.'.cache.php'; + $parser = new OldXmlQueryParser(); + $parser->parse($query_id, $xml_file, $cache_file); + $buff = FileHandler::readFile($cache_file); + return $buff; + } + + function cleanOutputAndAddArgs($outputString, $argsString = ''){ + $outputString = str_replace("", "", $outputString); + $outputString = $argsString . $outputString; + return $outputString; + } + + function getXmlFileContent($xml_file){ + return FileHandler::readFile($xml_file); + } + + function printOutput($output){ + if(is_object($output)) { + var_dump($output); return; + } + $output = htmlspecialchars($output); + + $output = preg_replace('/select/i', 'SELECT', $output); + $output = preg_replace('/from/i', '
FROM', $output); + $output = preg_replace('/where/i', '
WHERE', $output); + $output = preg_replace('/group by/i', '
GROUP BY', $output); + $output = preg_replace('/order by/i', '
ORDER BY', $output); + + $output = str_replace("\n", "
", $output); + + echo '
'
+					.$output
+				.'
'; + } + + function getNewParserOutputString($xml_file, $escape_char, $argsString){ + $outputString = ''; + $outputString = $this->getNewParserOutput($xml_file, $escape_char); + $outputString = $this->cleanOutputAndAddArgs($outputString, $argsString); + return $outputString; + } + + function getNewParserQuery($outputString){ + //echo $outputString; + //exit(0); + $output = eval($outputString); + if(is_a($output, 'Object')) + if(!$output->toBool()) return("Date incorecte! Query-ul nu a putut fi executat."); + $db = new DBCubrid(); + if($output->getAction() == 'select') + return $db->getSelectSql($output); + else if($output->getAction() == 'insert') + return $db->getInsertSql($output); + else if($output->getAction() == 'update') + return $db->getUpdateSql($output); + else if($output->getAction() == 'delete') + return $db->getDeleteSql($output); + } + + function testNewParser($xml_file, $escape_char, $argsString, $show_output_string){ + $outputString = $this->getNewParserOutputString($xml_file, $escape_char, $argsString); + $query = $this->getNewParserQuery($outputString); + + echo ''; + if($show_output_string){ + echo ''; + $this->printOutput($outputString); + echo ''; + } + + echo ''; + $this->printOutput($query); + echo ''; + echo ''; + } + + function getOldParserOutputString($query_id, $xml_file, $argsString){ + $outputString = $this->getOldParserOutput($query_id, $xml_file); + $outputString = $this->cleanOutputAndAddArgs($outputString, $argsString); + return $outputString; + } + + function getOldParserQuery($outputString){ + $output = eval($outputString); + if(is_a($output, 'Object')) + if(!$output->toBool()) exit("Date incorecte! Query-ul nu a putut fi executat."); + + /* SQL Server + * + $db = new DBMssql(false); + if($output->action == "select") + return $db->_executeSelectAct($output); + else if($output->action == "insert") + return $db->_executeInsertAct($output); + else if($output->action == "delete") + return $db->_executeDeleteAct($output); + else if($output->action == "update") + return $db->_executeUpdateAct($output); + */ + + /* + * Mysql + */ + $db = new DBMysql(false); + if($output->action == "select") + $db->_executeSelectAct($output); + else if($output->action == "insert") + $db->_executeInsertAct($output); + else if($output->action == "delete") + $db->_executeDeleteAct($output); + else if($output->action == "update") + $db->_executeUpdateAct($output); + return $db->getLatestQuery(); + } + + function testOldParser($query_id, $xml_file, $argsString, $show_output_string){ + $outputString = $this->getOldParserOutputString($query_id, $xml_file, $argsString); + $query = $this->getOldParserQuery($outputString); + + + echo ''; + if($show_output_string){ + echo ''; + $this->printOutput($outputString); + echo ''; + } + + echo ''; + $this->printOutput($query); + echo ''; + echo ''; + } + + function showXmlInputFile($xml_file){ + echo ''; + echo ''; + $xml_file_content = $this->getXmlFileContent($xml_file); + $this->printOutput($xml_file_content); + echo ''; + } + + function test($query_id, $xml_file, $argsString, $show_output_string, $escape_char = '"'){ + echo "

$query_id

"; + echo ''; + + $this->showXmlInputFile($xml_file); + + $this->testNewParser($xml_file, $escape_char, $argsString, $show_output_string); + + //$this->testOldParser($query_id, $xml_file, $argsString, $show_output_string); + + echo '
'; + } + + function test_addon_getAddonInfo($show_output_string = false){ + $argsString = '$args->addon = "captcha";'; + $this->test("modules.addon.getAddonInfo" + , $this->getQueryPath("modules", "addon", "getAddonInfo") + , $argsString + , $show_output_string); + } + + function test_addon_getAddons($show_output_string = false){ + $argsString = ''; + $this->test("modules.addon.getAddons" + , $this->getQueryPath("modules", "addon", "getAddons") + , $argsString + , $show_output_string); + } + + function test_admin_getCommentCount($show_output_string = false){ + $argsString = ''; + $this->test("modules.admin.getCommentCount" + , $this->getQueryPath("modules", "admin", "getCommentCount") + , $argsString + , $show_output_string); + } + + function test_admin_getCommentDeclaredStatus($show_output_string = false){ + $argsString = '$args->date = "20110411";'; + $this->test("modules.admin.getCommentDeclaredStatus" + , $this->getQueryPath("modules", "admin", "getCommentDeclaredStatus") + , $argsString + , $show_output_string); + } + + function test_module_getDefaultModules($show_output_string = false){ + $argsString = ''; + $this->test("modules.module.getDefaultModules" + , $this->getQueryPath("modules", "module", "getDefaultModules") + , $argsString + , $show_output_string); + } + + function test_module_getModuleCategories($show_output_string = false){ + $argsString = ''; + $this->test("modules.module.getModuleCategories" + , $this->getQueryPath("modules", "module", "getModuleCategories") + , $argsString + , $show_output_string); + } + + function test_module_getNonuniqueDomains($show_output_string = false){ + $argsString = ''; + $this->test("modules.module.getNonuniqueDomains" + , $this->getQueryPath("modules", "module", "getNonuniqueDomains") + , $argsString + , $show_output_string); + } + + function test_module_getAdminId($show_output_string = false){ + $argsString = '$args->module_srl = 23;'; + $this->test("modules.module.getAdminId" + , $this->getQueryPath("modules", "module", "getAdminId") + , $argsString + , $show_output_string); + } + function test_module_getSiteInfo($show_output_string = false){ + $argsString = '$args->site_srl = 0;'; + $this->test("modules.module.getSiteInfo" + , $this->getQueryPath("modules", "module", "getSiteInfo") + , $argsString + , $show_output_string); + } + function test_module_insertModule($show_output_string = false){ + $argsString = ' $args->module_category_srl = 0; + $args->browser_title = "test"; + $args->layout_srl = 0; + $args->mlayout_srl = 0; + $args->module = "page"; + $args->mid = "test"; + $args->site_srl = 0; + $args->module_srl = 47374;'; + $this->test("modules.module.insertModule" + , $this->getQueryPath("modules", "module", "insertModule") + , $argsString + , $show_output_string); + } + function test_module_updateModule($show_output_string = false){ + $argsString = ' $args->module_category_srl = 0; + $args->browser_title = "test"; + $args->layout_srl = 0; + $args->mlayout_srl = 0; + $args->module = "page"; + $args->mid = "test"; + $args->use_mobile = ""; + $args->site_srl = 0; + $args->module_srl = 47374;'; + $this->test("modules.module.updateModule" + , $this->getQueryPath("modules", "module", "updateModule") + , $argsString + , $show_output_string); + } + function test_admin_deleteActionForward($show_output_string = false){ + $argsString = '$args->module = "page"; + $args->type = "page"; + $args->act = "tata";'; + $this->test("modules.admin.deleteActionForward" + , $this->getQueryPath("modules", "module", "deleteActionForward") + , $argsString + , $show_output_string); + } + + function test_member_getAutologin($show_output_string = false){ + $argsString = '$args->autologin_key = 10;'; + $this->test("modules.member.getAutologin" + , $this->getQueryPath("modules", "member", "getAutologin") + , $argsString + , $show_output_string); + } + + function test_opage_getOpageList($show_output_string = false){ + $argsString = '$args->s_title = "yuhuu"; + $args->module = 12;'; + $this->test("modules.opage.getOpageList" + , $this->getQueryPath("modules", "opage", "getOpageList") + , $argsString + , $show_output_string); + } + function test_getPageList($show_output_string = false){ + $argsString = '$args->sort_index = "module_srl"; + $args->page_count = 10; + $args->s_module_category_srl = 0; + $args->s_mid = "test"; + $args->s_browser_title = "caca";'; + + $this->test("modules.page.getPageList" + , $this->getQueryPath("modules", "page", "getPageList") + , $argsString + , $show_output_string); + } + + + + } +?> \ No newline at end of file diff --git a/test-phpUnit/SelectXmlTest_Cubrid.php b/test-phpUnit/SelectXmlTest_Cubrid.php new file mode 100644 index 000000000..ff65dae9c --- /dev/null +++ b/test-phpUnit/SelectXmlTest_Cubrid.php @@ -0,0 +1,170 @@ +getNewParserOutputString($xml_file, '"', $argsString); + $output = eval($outputString); + if(!is_a($output, 'Query')){ + if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; + }else { + $db = new DBCubrid(); + $querySql = $db->getSelectSql($output); + + // Remove whitespaces, tabs and all + $querySql = Helper::cleanQuery($querySql); + $expected = Helper::cleanQuery($expected); + } + + // Test + $this->assertEquals($expected, $querySql); + } + + function testSelectStar(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; + $argsString = '$args->module_srl = 10;'; + $expected = 'SELECT * FROM "xe_module_admins" as "module_admins" , "xe_member" as "member" WHERE "module_srl" = 10 and "member"."member_srl" = "module_admins"."member_srl"'; + $this->_test($xml_file, $argsString, $expected); + } + + function testRquiredParameter(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; + $argsString = ''; + $expected = 'Date incorecte! Query-ul nu a putut fi executat.'; + $this->_test($xml_file, $argsString, $expected); + } + + function testWithoutCategoriesTag(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getModuleCategories.xml"; + $argsString = ''; + $expected = 'SELECT * FROM "xe_module_categories" as "module_categories" ORDER BY "title" asc'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_getDefaultModules(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getDefaultModules.xml"; + $argsString = ''; + $expected = 'SELECT "modules"."site_srl" + , "modules"."module" + , "modules"."mid" + , "modules"."browser_title" + , "module_categories"."title" as "category" + , "modules"."module_srl" + FROM "xe_modules" as "modules" + left join "xe_module_categories" as "module_categories" + on "module_categories"."module_category_srl" = "modules"."module_category_srl" + WHERE "modules"."site_srl" = 0 + ORDER BY "modules"."module" asc, "module_categories"."title" asc, "modules"."mid" asc'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_getSiteInfo(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getSiteInfo.xml"; + $argsString = '$args->site_srl = 0;'; + $expected = 'SELECT "modules"."site_srl" as "module_site_srl" + , "modules"."module_srl" as "module_srl" + , "modules"."module" as "module" + , "modules"."module_category_srl" as "module_category_srl" + , "modules"."layout_srl" as "layout_srl" + , "modules"."mlayout_srl" as "mlayout_srl" + , "modules"."use_mobile" as "use_mobile" + , "modules"."menu_srl" as "menu_srl" + , "modules"."mid" as "mid" + , "modules"."skin" as "skin" + , "modules"."mskin" as "mskin" + , "modules"."browser_title" as "browser_title" + , "modules"."description" as "description" + , "modules"."is_default" as "is_default" + , "modules"."content" as "content" + , "modules"."mcontent" as "mcontent" + , "modules"."open_rss" as "open_rss" + , "modules"."header_text" as "header_text" + , "modules"."footer_text" as "footer_text" + , "modules"."regdate" as "regdate" + , "sites"."site_srl" as "site_srl" + , "sites"."domain" as "domain" + , "sites"."index_module_srl" as "index_module_srl" + , "sites"."default_language" as "default_language" + FROM "xe_sites" as "sites" + left join "xe_modules" as "modules" on "modules"."module_srl" = "sites"."index_module_srl" + WHERE "sites"."site_srl" = 0 '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_addon_getAddonInfo(){ + $xml_file = _XE_PATH_ . "modules/addon/queries/getAddonInfo.xml"; + $argsString = '$args->addon = "captcha";'; + $expected = 'SELECT * + FROM "xe_addons" as "addons" + WHERE "addon" = \'captcha\' '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_addon_getAddons(){ + $xml_file = _XE_PATH_ . "modules/addon/queries/getAddons.xml"; + $argsString = ''; + $expected = 'SELECT * + FROM "xe_addons" as "addons" + ORDER BY "addon" asc'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_admin_getCommentCount(){ + $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentCount.xml"; + $argsString = ''; + $expected = 'SELECT count(*) as "count" + FROM "xe_comments" as "comments"'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_admin_getCommentDeclaredStatus(){ + $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentDeclaredStatus.xml"; + $argsString = '$args->date = "20110411";'; + $expected = 'SELECT substr("regdate",1,8) as "date", count(*) as "count" + FROM "xe_comment_declared_log" as "comment_declared_log" + WHERE "regdate" >= \'20110411\' + GROUP BY substr("regdate",1,8) + ORDER BY substr("regdate",1,8) asc limit 2'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_member_getAutoLogin(){ + $xml_file = _XE_PATH_ . "modules/member/queries/getAutoLogin.xml"; + $argsString = '$args->autologin_key = 10;'; + $expected = 'SELECT "member"."user_id" as "user_id" + , "member"."password" as "password" + , "member_autologin"."autologin_key" as "autologin_key" + FROM "xe_member" as "member" , "xe_member_autologin" as "member_autologin" + WHERE "member_autologin"."autologin_key" = \'10\' + and "member"."member_srl" = "member_autologin"."member_srl"'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_opage_getOpageList(){ + $xml_file = _XE_PATH_ . "modules/opage/queries/getOpageList.xml"; + $argsString = '$args->s_title = "yuhuu"; + $args->module = \'opage\';'; + $expected = 'SELECT * + FROM "xe_modules" as "modules" + WHERE "module" = \'opage\' and ("browser_title" like \'%yuhuu%\') + ORDER BY "module_srl" desc + LIMIT 0, 20'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_syndication_getGrantedModules(){ + $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml"; + $argsString = '$args->module_srl = 12; + $args->name = array(\'access\',\'view\',\'list\');'; + $expected = 'select "module_srl" + from "xe_module_grants" as "module_grants" + where "name" in (\'access\',\'view\',\'list\') + and ("group_srl" >= -2 + or "group_srl" = -2 + or "group_srl" = -2) + group by "module_srl"'; + $this->_test($xml_file, $argsString, $expected); + } + } \ No newline at end of file diff --git a/test-phpUnit/UpdateXmlTest_Cubrid.php b/test-phpUnit/UpdateXmlTest_Cubrid.php new file mode 100644 index 000000000..47cf97e0a --- /dev/null +++ b/test-phpUnit/UpdateXmlTest_Cubrid.php @@ -0,0 +1,84 @@ +getNewParserOutputString($xml_file, '"', $argsString); + $output = eval($outputString); + if(!is_a($output, 'Query')){ + if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; + }else { + $db = new DBCubrid(); + $querySql = $db->getUpdateSql($output); + + // Remove whitespaces, tabs and all + $querySql = Helper::cleanQuery($querySql); + $expected = Helper::cleanQuery($expected); + } + + // Test + $this->assertEquals($expected, $querySql); + } + + function test_module_updateModule(){ + $xml_file = _XE_PATH_ . "modules/module/queries/updateModule.xml"; + $argsString = ' $args->module_category_srl = 0; + $args->browser_title = "test"; + $args->layout_srl = 0; + $args->mlayout_srl = 0; + $args->module = "page"; + $args->mid = "test"; + $args->use_mobile = ""; + $args->site_srl = 0; + $args->module_srl = 47374;'; + $expected = 'UPDATE "xe_modules" + SET "module" = \'page\' + , "mid" = \'test\' + , "browser_title" = \'test\' + , "description" = \'\' + , "is_default" = \'N\' + , "open_rss" = \'Y\' + , "header_text" = \'\' + , "footer_text" = \'\' + , "use_mobile" = \'\' + WHERE "site_srl" = 0 + AND "module_srl" = 47374'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_updateMember(){ + $xml_file = _XE_PATH_ . "modules/member/queries/updateLastLogin.xml"; + $argsString = ' $args->member_srl = 4; + $args->last_login = "20110607120549";'; + $expected = 'UPDATE "xe_member" SET "member_srl" = 4, "last_login" = \'20110607120549\' WHERE "member_srl" = 4'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_updatePoint(){ + $xml_file = _XE_PATH_ . "modules/point/queries/updatePoint.xml"; + $argsString = ' $args->member_srl = 4; + $args->point = 105;'; + $expected = 'UPDATE "xe_point" SET "point" = 105 WHERE "member_srl" = 4'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_updateCounterUnique(){ + $xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml"; + $argsString = '$args->regdate = 20110607; + '; + $expected = 'UPDATE "xe_counter_status" SET "unique_visitor" = unique_visitor+1, + "pageview" = pageview+1 WHERE "regdate" = 20110607 '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_updateMenu(){ + $xml_file = _XE_PATH_ . "modules/menu/queries/updateMenu.xml"; + $argsString = '$args->menu_srl = 204; + $args->title = "test_menu"; + '; + $expected = 'UPDATE "xe_menu" SET "title" = \'test_menu\' WHERE "menu_srl" = 204'; + $this->_test($xml_file, $argsString, $expected); + } + } \ No newline at end of file diff --git a/test-phpUnit/config.inc.php b/test-phpUnit/config.inc.php new file mode 100644 index 000000000..d264597db --- /dev/null +++ b/test-phpUnit/config.inc.php @@ -0,0 +1,35 @@ + \ No newline at end of file From 313bfca8e83c60e10f7fe1cfb553ce555b963b64 Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 7 Jun 2011 17:18:32 +0000 Subject: [PATCH 34/82] Updated the query parts that work with arguments (conditions, update and insert expressions) to work with QueryArgument objects instead of string values. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8457 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../queryparts/condition/Condition.class.php | 44 +++++++---- .../expression/DeleteExpression.class.php | 1 + .../expression/InsertExpression.class.php | 11 +-- .../expression/UpdateExpression.class.php | 24 ++++-- classes/db/queryparts/limit/Limit.class.php | 6 +- .../queryparts/order/OrderByColumn.class.php | 5 +- classes/xml/XmlParser.class.php | 1 - classes/xml/XmlQueryParser.class.php | 5 +- .../tags/column/InsertColumnTag.class.php | 2 +- .../tags/column/UpdateColumnTag.class.php | 2 +- .../tags/condition/ConditionTag.class.php | 2 +- .../tags/navigation/IndexTag.class.php | 2 +- .../tags/navigation/LimitTag.class.php | 4 +- test-phpUnit/DeleteXmlTest_Cubrid.php | 6 +- test-phpUnit/InsertXmlTest_Cubrid.php | 78 +------------------ test-phpUnit/SelectXmlTest_Cubrid.php | 12 ++- test-phpUnit/UpdateXmlTest_Cubrid.php | 35 +-------- test-phpUnit/config.inc.php | 49 ++++++------ 18 files changed, 120 insertions(+), 169 deletions(-) diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index b77ed1173..d4ca862d0 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -2,19 +2,39 @@ class Condition { var $column_name; - var $value; + var $argument; var $operation; var $pipe; - function Condition($column_name, $value, $operation, $pipe = ""){ + var $_value; + + function Condition($column_name, $argument, $operation, $pipe = ""){ $this->column_name = $column_name; - $this->value = $value; + $this->argument = $argument; $this->operation = $operation; $this->pipe = $pipe; + if($this->hasArgument()) + $this->_value = $argument->getValue(); + else + $this->_value = $argument; + } + + function hasArgument(){ + return is_a($this->argument, 'Argument'); } function toString(){ - return $this->pipe . ' ' . $this->getConditionPart(); + return $this->toStringWithValue(); + } + + function toStringWithoutValue(){ + if($this->hasArgument()) + return $this->pipe . ' ' . $this->getConditionPart("?"); + else return $this->toString(); + } + + function toStringWithValue(){ + return $this->pipe . ' ' . $this->getConditionPart($this->_value); } function setPipe($pipe){ @@ -35,22 +55,20 @@ case 'notin' : case 'notequal' : // if variable is not set or is not string or number, return - if(!isset($this->value)) return false; - if($this->value === '') return false; - if(!in_array(gettype($this->value), array('string', 'integer'))) return false; + if(!isset($this->_value)) return false; + if($this->_value === '') return false; + if(!in_array(gettype($this->_value), array('string', 'integer'))) return false; break; case 'between' : - if(!is_array($this->value)) return false; - if(count($this->value)!=2) return false; + if(!is_array($this->_value)) return false; + if(count($this->_value)!=2) return false; } return true; } - - function getConditionPart() { - + + function getConditionPart($value) { $name = $this->column_name; - $value = $this->value; $operation = $this->operation; switch($operation) { diff --git a/classes/db/queryparts/expression/DeleteExpression.class.php b/classes/db/queryparts/expression/DeleteExpression.class.php index 041173f2f..611510109 100644 --- a/classes/db/queryparts/expression/DeleteExpression.class.php +++ b/classes/db/queryparts/expression/DeleteExpression.class.php @@ -6,6 +6,7 @@ * */ + // TODO Fix this class class DeleteExpression extends Expression { var $value; diff --git a/classes/db/queryparts/expression/InsertExpression.class.php b/classes/db/queryparts/expression/InsertExpression.class.php index 633bacaf5..24892c577 100644 --- a/classes/db/queryparts/expression/InsertExpression.class.php +++ b/classes/db/queryparts/expression/InsertExpression.class.php @@ -8,19 +8,20 @@ */ class InsertExpression extends Expression { - var $value; + var $argument; - function InsertExpression($column_name, $value){ + function InsertExpression($column_name, $argument){ parent::Expression($column_name); - $this->value = $value; + $this->argument = $argument; } function getValue(){ - return $this->value; + return $this->argument->getValue(); } function show(){ - if(!isset($this->value)) return false; + $value = $this->argument->getValue(); + if(!isset($value)) return false; return true; } } diff --git a/classes/db/queryparts/expression/UpdateExpression.class.php b/classes/db/queryparts/expression/UpdateExpression.class.php index fb3047ee3..ca3114d3b 100644 --- a/classes/db/queryparts/expression/UpdateExpression.class.php +++ b/classes/db/queryparts/expression/UpdateExpression.class.php @@ -7,25 +7,35 @@ */ class UpdateExpression extends Expression { - var $value; + var $argument; - function UpdateExpression($column_name, $value){ + function UpdateExpression($column_name, $argument){ parent::Expression($column_name); - $this->value = $value; + $this->argument = $argument; } function getExpression(){ - return "$this->column_name = $this->value"; + return $this->getExpressionWithValue(); + } + + function getExpressionWithValue(){ + $value = $this->argument->getValue(); + return "$this->column_name = $value"; + } + + function getExpressionWithoutValue(){ + return "$this->column_name = ?"; } function getValue(){ // TODO Escape value according to column type instead of variable type - if(!is_numeric($this->value)) return "'".$this->value."'"; - return $this->value; + $value = $this->argument->getValue(); + if(!is_numeric($value)) return "'".$value."'"; + return $value; } function show(){ - if(!$this->value) return false; + if(!$this->argument->getValue()) return false; return true; } } diff --git a/classes/db/queryparts/limit/Limit.class.php b/classes/db/queryparts/limit/Limit.class.php index 743b25095..a64b27e8a 100644 --- a/classes/db/queryparts/limit/Limit.class.php +++ b/classes/db/queryparts/limit/Limit.class.php @@ -24,12 +24,12 @@ } function getLimit(){ - return $this->list_count; + return $this->list_count->getValue(); } function toString(){ - if ($this->page) return $this->start . ' , ' . $this->list_count; - else return $this->list_count; + if ($this->page) return $this->start . ' , ' . $this->list_count->getValue(); + else return $this->list_count->getValue(); } } ?> \ No newline at end of file diff --git a/classes/db/queryparts/order/OrderByColumn.class.php b/classes/db/queryparts/order/OrderByColumn.class.php index b5db8e9ce..c33749488 100644 --- a/classes/db/queryparts/order/OrderByColumn.class.php +++ b/classes/db/queryparts/order/OrderByColumn.class.php @@ -9,7 +9,10 @@ } function toString(){ - return $this->column_name . ' ' . $this->sort_order; + $result = is_a($this->column_name, 'Argument') ? $this->column_name->getValue() : $this->column_name; + $result .= ' '; + $result .= is_a($this->sort_order, 'Argument') ? $this->sort_order->getValue() : $this->sort_order; + return $result; } } diff --git a/classes/xml/XmlParser.class.php b/classes/xml/XmlParser.class.php index fb63fbed1..3350a7a59 100644 --- a/classes/xml/XmlParser.class.php +++ b/classes/xml/XmlParser.class.php @@ -44,7 +44,6 @@ if(__DEBUG__==3) $start = getMicroTime(); $this->lang = Context::getLangType(); - $this->input = $input?$input:$GLOBALS['HTTP_RAW_POST_DATA']; $this->input = str_replace(array('',''),array('',''),$this->input); diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 243a57548..0899d93c7 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -32,8 +32,9 @@ /* function &getDBParser(){ static $dbParser; if(!$dbParser){ - $oDB = &DB::getInstance(); - $dbParser = $oDB->getParser(); + //$oDB = &DB::getInstance(); + //$dbParser = $oDB->getParser(); + return new DBParser('"'); } return $dbParser; }*/ diff --git a/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php index 1d42ffb3a..c34f1bafc 100644 --- a/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/InsertColumnTag.class.php @@ -19,7 +19,7 @@ } function getExpressionString(){ - return sprintf('new InsertExpression(\'%s\', $%s_argument->getValue())' + return sprintf('new InsertExpression(\'%s\', $%s_argument)' , $this->name , $this->argument->argument_name); } diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php index 93d4c2b5b..9dcf1be9a 100644 --- a/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php +++ b/classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php @@ -21,7 +21,7 @@ } function getExpressionString(){ - return sprintf('new UpdateExpression(\'%s\', $%s_argument->getValue())' + return sprintf('new UpdateExpression(\'%s\', $%s_argument)' , $this->name , $this->argument->argument_name); } diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index 3f25da9fa..ed7e31a01 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -50,7 +50,7 @@ function getConditionString(){ return sprintf("new Condition('%s',%s,%s%s)" , $this->column_name - , $this->default_column ? "'" . $this->default_column . "'" : '$' . $this->argument_name . '_argument->getValue()' + , $this->default_column ? "'" . $this->default_column . "'" : '$' . $this->argument_name . '_argument' , '"'.$this->operation.'"' , $this->pipe ? ", '" . $this->pipe . "'" : '' ); diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index aae32d16b..0d8f9829f 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -26,7 +26,7 @@ } function toString(){ - return sprintf("new OrderByColumn(\$%s_argument->getValue(), %s)", $this->argument_name, $this->sort_order); + return sprintf("new OrderByColumn(\$%s_argument, %s)", $this->argument_name, $this->sort_order); } function getArguments(){ diff --git a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php index 68a006946..d0a22447d 100644 --- a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php @@ -21,8 +21,8 @@ } function toString(){ - if ($this->page)return sprintf("new Limit(\$%s_argument->getValue(), \$%s_argument->getValue(), \$%s_argument->getValue())",$this->list_count->var, $this->page->var, $this->page_count->var); - else return sprintf("new Limit(\$%s_argument->getValue())", $this->list_count->var); + if ($this->page)return sprintf("new Limit(\$%s_argument, \$%s_argument, \$%s_argument)",$this->list_count->var, $this->page->var, $this->page_count->var); + else return sprintf("new Limit(\$%s_argument)", $this->list_count->var); } function getArguments(){ diff --git a/test-phpUnit/DeleteXmlTest_Cubrid.php b/test-phpUnit/DeleteXmlTest_Cubrid.php index 5f27edb8a..da146978a 100644 --- a/test-phpUnit/DeleteXmlTest_Cubrid.php +++ b/test-phpUnit/DeleteXmlTest_Cubrid.php @@ -6,7 +6,6 @@ function _test($xml_file, $argsString, $expected){ $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); - echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ @@ -35,4 +34,9 @@ and "act" = \'tata\''; $this->_test($xml_file, $argsString, $expected); } + +// $queryTester->test_admin_deleteActionForward(); +// $queryTester->test_module_insertModule(); + + } \ No newline at end of file diff --git a/test-phpUnit/InsertXmlTest_Cubrid.php b/test-phpUnit/InsertXmlTest_Cubrid.php index 9edcdf4fe..c61eca9bb 100644 --- a/test-phpUnit/InsertXmlTest_Cubrid.php +++ b/test-phpUnit/InsertXmlTest_Cubrid.php @@ -5,8 +5,8 @@ function _test($xml_file, $argsString, $expected){ $tester = new QueryTester(); + echo $xml_file . $argsString; $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); - //echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ @@ -62,79 +62,9 @@ , \'n\')'; $this->_test($xml_file, $argsString, $expected); } + +// $queryTester->test_admin_deleteActionForward(); +// $queryTester->test_module_insertModule(); - function test_module_insertSiteTodayStatus(){ - //\''.date("YmdHis").'\' - $xml_file = _XE_PATH_ . "modules/counter/queries/insertTodayStatus.xml"; - $argsString = ' $args->regdate = 0; - $args->unique_visitor = 0; - $args->pageview = 0;'; - $expected = 'insert into "xe_counter_status" - ("regdate" - , "unique_visitor" - , "pageview") - values - (0 - , 0 - , 0)'; - $this->_test($xml_file, $argsString, $expected); - } - function test_module_insertCounterLog(){ - $xml_file = _XE_PATH_ . "modules/counter/queries/insertCounterLog.xml"; - $argsString = ' $args->site_srl = 0; - $args->regdate = "20110607120619"; - $args->ipaddress = "127.0.0.1"; - $args->user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24";'; - $expected = 'insert into "xe_counter_log" - ("site_srl", "regdate", "ipaddress", "user_agent") - VALUES (0, \'20110607120619\', \'127.0.0.1\', \'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24\') - '; - $this->_test($xml_file, $argsString, $expected); - } - - function test_module_insertMember(){ - $xml_file = _XE_PATH_ . "modules/member/queries/insertMember.xml"; - $argsString = ' $args->member_srl = 203; - $args->user_id = "cacao"; - $args->email_address = "teta@ar.ro"; - $args->password = "23e5484cb88f3c07bcce2920a5e6a2a7"; - $args->email_id = "teta"; - $args->email_host = "ar.ro"; - $args->user_name = "trident"; - $args->nick_name = "aloha"; - $args->homepage = "http://jkgjfk./ww"; - $args->allow_mailing = "Y"; - $args->allow_message = "Y"; - $args->denied = "N"; - $args->limit_date = ""; - $args->regdate = "20110607121952"; - $args->change_password_date = "20110607121952"; - $args->last_login = "20110607121952"; - $args->is_admin = "N"; - $args->extra_vars = "O:8:\"stdClass\":2:{s:4:\"body\";s:0:\"\";s:7:\"_filter\";s:6:\"insert\";}"; - $args->list_order = -203; - '; - $expected = 'INSERT INTO "xe_member" - ("member_srl", "user_id", "email_address", "password", "email_id", "email_host", "user_name", "nick_name", - "homepage", "allow_mailing", "allow_message", "denied", "limit_date", "regdate", "change_password_date", - "last_login", "is_admin", "extra_vars", "list_order") - VALUES (203, \'cacao\', \'teta@ar.ro\', \'23e5484cb88f3c07bcce2920a5e6a2a7\', \'teta\', \'ar.ro\', \'trident\', - \'aloha\', \'http://jkgjfk./ww\', \'Y\', \'Y\', \'N\', \'\', \'20110607121952\', \'20110607121952\', - \'20110607121952\', \'N\', \'O:8:"stdClass":2:{s:4:"body";s:0:"";s:7:"_filter";s:6:"insert";}\', -203)'; - $this->_test($xml_file, $argsString, $expected); - } - - function test_module_insertModuleExtraVars(){ - $xml_file = _XE_PATH_ . "modules/module/queries/insertModuleExtraVars.xml"; - $argsString = ' $args->module_srl = 202; - $args->name = "_filter"; - $args->value = "insert_page"; - '; - $expected = 'INSERT INTO "xe_module_extra_vars" - ("module_srl", "name", "value") - VALUES (202, \'_filter\', \'insert_page\') - '; - $this->_test($xml_file, $argsString, $expected); - } } \ No newline at end of file diff --git a/test-phpUnit/SelectXmlTest_Cubrid.php b/test-phpUnit/SelectXmlTest_Cubrid.php index ff65dae9c..090e83c87 100644 --- a/test-phpUnit/SelectXmlTest_Cubrid.php +++ b/test-phpUnit/SelectXmlTest_Cubrid.php @@ -7,6 +7,7 @@ $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); $output = eval($outputString); + if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { @@ -166,5 +167,14 @@ or "group_srl" = -2) group by "module_srl"'; $this->_test($xml_file, $argsString, $expected); - } + } + +// $queryTester->test_admin_deleteActionForward(); +// $queryTester->test_module_insertModule(); +// $queryTester->test_module_updateModule(); + + +// $queryTester->test_opage_getOpageList(); + + } \ No newline at end of file diff --git a/test-phpUnit/UpdateXmlTest_Cubrid.php b/test-phpUnit/UpdateXmlTest_Cubrid.php index 47cf97e0a..dbb15edb9 100644 --- a/test-phpUnit/UpdateXmlTest_Cubrid.php +++ b/test-phpUnit/UpdateXmlTest_Cubrid.php @@ -47,38 +47,9 @@ AND "module_srl" = 47374'; $this->_test($xml_file, $argsString, $expected); } + +// $queryTester->test_admin_deleteActionForward(); +// $queryTester->test_module_insertModule(); - function test_module_updateMember(){ - $xml_file = _XE_PATH_ . "modules/member/queries/updateLastLogin.xml"; - $argsString = ' $args->member_srl = 4; - $args->last_login = "20110607120549";'; - $expected = 'UPDATE "xe_member" SET "member_srl" = 4, "last_login" = \'20110607120549\' WHERE "member_srl" = 4'; - $this->_test($xml_file, $argsString, $expected); - } - function test_module_updatePoint(){ - $xml_file = _XE_PATH_ . "modules/point/queries/updatePoint.xml"; - $argsString = ' $args->member_srl = 4; - $args->point = 105;'; - $expected = 'UPDATE "xe_point" SET "point" = 105 WHERE "member_srl" = 4'; - $this->_test($xml_file, $argsString, $expected); - } - - function test_module_updateCounterUnique(){ - $xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml"; - $argsString = '$args->regdate = 20110607; - '; - $expected = 'UPDATE "xe_counter_status" SET "unique_visitor" = unique_visitor+1, - "pageview" = pageview+1 WHERE "regdate" = 20110607 '; - $this->_test($xml_file, $argsString, $expected); - } - - function test_module_updateMenu(){ - $xml_file = _XE_PATH_ . "modules/menu/queries/updateMenu.xml"; - $argsString = '$args->menu_srl = 204; - $args->title = "test_menu"; - '; - $expected = 'UPDATE "xe_menu" SET "title" = \'test_menu\' WHERE "menu_srl" = 204'; - $this->_test($xml_file, $argsString, $expected); - } } \ No newline at end of file diff --git a/test-phpUnit/config.inc.php b/test-phpUnit/config.inc.php index d264597db..6429209f4 100644 --- a/test-phpUnit/config.inc.php +++ b/test-phpUnit/config.inc.php @@ -1,35 +1,38 @@ - \ No newline at end of file From b6a1088995c30de12f424dd92f31cf25480fff71 Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 7 Jun 2011 19:01:58 +0000 Subject: [PATCH 35/82] Updated DB classes for supporting prepared statements - SQL string can now be returned with '?' instead of argument values. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8458 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 22 +++++------ classes/db/DBMssql.class.php | 39 +++++++++++++++++++ classes/db/queryparts/Query.class.php | 27 +++++++------ .../queryparts/condition/Condition.class.php | 6 ++- .../condition/ConditionGroup.class.php | 6 +-- .../expression/InsertExpression.class.php | 6 ++- .../expression/UpdateExpression.class.php | 6 ++- .../db/queryparts/table/JoinTable.class.php | 4 +- classes/xml/XmlQueryParser.class.php | 24 ++++++------ classes/xml/xmlquery/QueryParser.class.php | 3 +- .../xml/xmlquery/argument/Argument.class.php | 2 +- test-phpUnit/QueryTester.class.php | 12 +++--- test-phpUnit/SelectXmlTest_Cubrid.php | 1 + test-phpUnit/config.inc.php | 1 + 14 files changed, 107 insertions(+), 52 deletions(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 8391f0d77..cd504d9c9 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -457,16 +457,16 @@ $this->_query($query); } - function getSelectSql($query){ - $select = $query->getSelectString(); + function getSelectSql($query, $with_values = true){ + $select = $query->getSelectString($with_values); if($select == '') return new Object(-1, "Invalid query"); $select = 'SELECT ' .$select; - $from = $query->getFromString(); + $from = $query->getFromString($with_values); if($from == '') return new Object(-1, "Invalid query"); $from = ' FROM '.$from; - $where = $query->getWhereString(); + $where = $query->getWhereString($with_values); if($where != '') $where = ' WHERE ' . $where; $groupBy = $query->getGroupByString(); @@ -481,7 +481,7 @@ return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; } - function getDeleteSql($query){ + function getDeleteSql($query, $with_values = true){ $sql = 'DELETE '; // TODO Add support for deleting based on alias, for both simple FROM and multi table join FROM clause @@ -489,32 +489,32 @@ $sql .= $tables[0]->getAlias(); - $from = $query->getFromString(); + $from = $query->getFromString($with_values); if($from == '') return new Object(-1, "Invalid query"); $sql .= ' FROM '.$from; - $where = $query->getWhereString(); + $where = $query->getWhereString($with_values); if($where != '') $sql .= ' WHERE ' . $where; return $sql; } - function getUpdateSql($query){ + function getUpdateSql($query, $with_values = true){ $columnsList = $query->getSelectString(); if($columnsList == '') return new Object(-1, "Invalid query"); $tableName = $query->getFirstTableName(); if($tableName == '') return new Object(-1, "Invalid query"); - $where = $query->getWhereString(); + $where = $query->getWhereString($with_values); if($where != '') $where = ' WHERE ' . $where; return "UPDATE $tableName SET $columnsList ".$where; } - function getInsertSql($query){ + function getInsertSql($query, $with_values = true){ $tableName = $query->getFirstTableName(); - $values = $query->getInsertString(); + $values = $query->getInsertString($with_values); return "INSERT INTO $tableName \n $values"; } diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index 2feada8c3..d5c7793f4 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -434,6 +434,42 @@ return $this->_query($query); } + function getSelectSql($query){ + $with_value = false; + + //$limitOffset = $query->getLimit()->getOffset(); + //if($limitOffset) + // TODO Implement Limit with offset with subquery + $limit = '';$limitCount = ''; + if($query->getLimit()) + $limitCount = $query->getLimit()->getLimit(); + if($limitCount != '') $limit = 'SELECT TOP ' . $limitCount; + + $select = $query->getSelectString($with_values); + if($select == '') return new Object(-1, "Invalid query"); + if($limit != '') + $select = $limit.' '.$select; + else + $select = 'SELECT ' .$select; + + $from = $query->getFromString($with_values); + if($from == '') return new Object(-1, "Invalid query"); + $from = ' FROM '.$from; + + $where = $query->getWhereString($with_values); + if($where != '') $where = ' WHERE ' . $where; + + $groupBy = $query->getGroupByString(); + if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; + + $orderBy = $query->getOrderByString(); + if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; + + + + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; + } + /** * @brief Handle selectAct * @@ -451,6 +487,9 @@ return $buff; } + function getParser(){ + return new DBParser("[", "]"); + } } diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 70853981e..513627535 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -11,6 +11,11 @@ var $orderby; var $limit; + var $arguments = array(); + + function addArgument($argument){ + $this->arguments[] = $argument; + } function setQueryId($queryID){ $this->queryID = $queryID; @@ -106,28 +111,28 @@ return $this->action; } - function getSelectString(){ + function getSelectString($with_values = true){ $select = ''; foreach($this->columns as $column){ if($column->show()) - $select .= $column->getExpression() . ', '; + $select .= $column->getExpression($with_values) . ', '; } if(trim($select) == '') return ''; $select = substr($select, 0, -2); return $select; } - function getUpdateString(){ - return $this->getSelectString(); + function getUpdateString($with_values = true){ + return $this->getSelectString($with_values); } - function getInsertString(){ + function getInsertString($with_values = true){ $columnsList = ''; $valuesList = ''; foreach($this->columns as $column){ if($column->show()){ $columnsList .= $column->getColumnName() . ', '; - $valuesList .= $column->getValue() . ', '; + $valuesList .= $column->getValue($with_values) . ', '; } } $columnsList = substr($columnsList, 0, -2); @@ -140,23 +145,23 @@ return $this->tables; } - function getFromString(){ + function getFromString($with_values = true){ $from = ''; $simple_table_count = 0; foreach($this->tables as $table){ - if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString() . ' '; - else $from .= ', '.$table->toString() . ' '; + if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString($with_values) . ' '; + else $from .= ', '.$table->toString($with_values) . ' '; $simple_table_count++; } if(trim($from) == '') return ''; return $from; } - function getWhereString(){ + function getWhereString($with_values = true){ $where = ''; if(count($this->conditions) > 0){ foreach($this->conditions as $conditionGroup){ - $where .= $conditionGroup->toString(); + $where .= $conditionGroup->toString($with_values); } if(trim($where) == '') return ''; diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index d4ca862d0..b2c4a3dfa 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -23,8 +23,10 @@ return is_a($this->argument, 'Argument'); } - function toString(){ - return $this->toStringWithValue(); + function toString($withValue = true){ + if($withValue) + return $this->toStringWithValue(); + return $this->toStringWithoutValue(); } function toStringWithoutValue(){ diff --git a/classes/db/queryparts/condition/ConditionGroup.class.php b/classes/db/queryparts/condition/ConditionGroup.class.php index cab975d7d..a7d3b3321 100644 --- a/classes/db/queryparts/condition/ConditionGroup.class.php +++ b/classes/db/queryparts/condition/ConditionGroup.class.php @@ -4,12 +4,12 @@ var $conditions; var $pipe; - function ConditionGroup($conditions, $pipe = ""){ + function ConditionGroup($conditions, $pipe = "") { $this->conditions = $conditions; $this->pipe = $pipe; } - function toString(){ + function toString($with_value = true){ if($this->pipe !== "") $group = $this->pipe .' ('; else $group = ''; @@ -19,7 +19,7 @@ foreach($this->conditions as $condition){ if($condition->show()){ if($cond_indx === 0) $condition->setPipe(""); - $group .= $condition->toString() . ' '; + $group .= $condition->toString($with_value) . ' '; $cond_indx++; } } diff --git a/classes/db/queryparts/expression/InsertExpression.class.php b/classes/db/queryparts/expression/InsertExpression.class.php index 24892c577..be546ffc2 100644 --- a/classes/db/queryparts/expression/InsertExpression.class.php +++ b/classes/db/queryparts/expression/InsertExpression.class.php @@ -15,8 +15,10 @@ $this->argument = $argument; } - function getValue(){ - return $this->argument->getValue(); + function getValue($with_values = true){ + if($with_values) + return $this->argument->getValue(); + return '?'; } function show(){ diff --git a/classes/db/queryparts/expression/UpdateExpression.class.php b/classes/db/queryparts/expression/UpdateExpression.class.php index ca3114d3b..e1c606673 100644 --- a/classes/db/queryparts/expression/UpdateExpression.class.php +++ b/classes/db/queryparts/expression/UpdateExpression.class.php @@ -14,8 +14,10 @@ $this->argument = $argument; } - function getExpression(){ - return $this->getExpressionWithValue(); + function getExpression($with_value = true){ + if($with_value) + return $this->getExpressionWithValue(); + return $this->getExpressionWithoutValue(); } function getExpressionWithValue(){ diff --git a/classes/db/queryparts/table/JoinTable.class.php b/classes/db/queryparts/table/JoinTable.class.php index 7294a5167..7738667d1 100644 --- a/classes/db/queryparts/table/JoinTable.class.php +++ b/classes/db/queryparts/table/JoinTable.class.php @@ -20,12 +20,12 @@ $this->conditions = $conditions; } - function toString(){ + function toString($with_value = true){ $part = $this->join_type . ' ' . $this->name ; $part .= $this->alias ? ' as ' . $this->alias : ''; $part .= ' on '; foreach($this->conditions as $conditionGroup) - $part .= $conditionGroup->toString(); + $part .= $conditionGroup->toString($with_value); return $part; } diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 0899d93c7..542640dab 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -14,8 +14,14 @@ class XmlQueryParser extends XmlParser { var $dbParser; + var $db_type; + + function XmlQueryParser($db_type = NULL){ + $this->db_type = $db_type; + } function parse($query_id, $xml_file, $cache_file) { + // Read xml file $xml_obj = $this->getXmlFileContent($xml_file); @@ -29,15 +35,17 @@ } // singleton - /* function &getDBParser(){ + function &getDBParser(){ static $dbParser; if(!$dbParser){ - //$oDB = &DB::getInstance(); - //$dbParser = $oDB->getParser(); - return new DBParser('"'); + if(isset($this->db_type)) + $oDB = &DB::getInstance($this->db_type); + else + $oDB = &DB::getInstance(); + $dbParser = $oDB->getParser(); } return $dbParser; - }*/ + } function getXmlFileContent($xml_file){ $buff = FileHandler::readFile($xml_file); @@ -46,11 +54,5 @@ unset($buff); return $xml_obj; } - - function &getDBParser(){ - if(!$this->dbParser) - $this->dbParser = new DBParser('"'); - return $this->dbParser; - } } ?> diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 6daca4389..53d939c5d 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -119,9 +119,10 @@ class QueryParser { foreach($arguments as $argument){ if(isset($argument) && $argument->getArgumentName()){ $prebuff .= $argument->toString(); - $prebuff .= sprintf("$%s_argument->escapeValue('%s');\n" + $prebuff .= sprintf("$%s_argument->setColumnType('%s');\n" , $argument->getArgumentName() , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); + $prebuff .= sprintf('$query->addArgument($%s_argument);', $argument->getArgumentName()); } } $prebuff .= "\n"; diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index fe8106bea..d3acf9830 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -36,7 +36,7 @@ $this->value = $default_value; } - function escapeValue($column_type){ + function setColumnType($column_type){ if(!isset($this->value)) return; if($column_type === '') return; diff --git a/test-phpUnit/QueryTester.class.php b/test-phpUnit/QueryTester.class.php index 32b1daa04..0f558b40e 100644 --- a/test-phpUnit/QueryTester.class.php +++ b/test-phpUnit/QueryTester.class.php @@ -12,11 +12,11 @@ return _XE_PATH_ . $type ."/".$name."/queries/" . $query_name . ".xml"; } - function getNewParserOutput($xml_file, $escape_char = '"'){ - $newXmlQueryParser = new XmlQueryParser(); + function getNewParserOutput($xml_file, $escape_char = '"', $db_type = NULL){ + $newXmlQueryParser = new XmlQueryParser($db_type); $xml_obj = $newXmlQueryParser->getXmlFileContent($xml_file); - - $dbParser = new DBParser($escape_char); + + $dbParser = $newXmlQueryParser->getDBParser(); $parser = new QueryParser($xml_obj->query, $dbParser); return $parser->toString(); } @@ -59,9 +59,9 @@ .''; } - function getNewParserOutputString($xml_file, $escape_char, $argsString){ + function getNewParserOutputString($xml_file, $escape_char, $argsString, $db_type = NULL){ $outputString = ''; - $outputString = $this->getNewParserOutput($xml_file, $escape_char); + $outputString = $this->getNewParserOutput($xml_file, $escape_char, $db_type); $outputString = $this->cleanOutputAndAddArgs($outputString, $argsString); return $outputString; } diff --git a/test-phpUnit/SelectXmlTest_Cubrid.php b/test-phpUnit/SelectXmlTest_Cubrid.php index 090e83c87..424d086d6 100644 --- a/test-phpUnit/SelectXmlTest_Cubrid.php +++ b/test-phpUnit/SelectXmlTest_Cubrid.php @@ -6,6 +6,7 @@ function _test($xml_file, $argsString, $expected){ $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); + //echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ diff --git a/test-phpUnit/config.inc.php b/test-phpUnit/config.inc.php index 6429209f4..d85b07d74 100644 --- a/test-phpUnit/config.inc.php +++ b/test-phpUnit/config.inc.php @@ -18,6 +18,7 @@ require_once(_XE_PATH_.'classes/db/DB.class.php'); require_once(_XE_PATH_.'classes/db/DBCubrid.class.php'); + require_once(_XE_PATH_.'classes/db/DBMssql.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); From d6a81c6ba90508c6e911683139622d678b2defda Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 7 Jun 2011 19:03:12 +0000 Subject: [PATCH 36/82] Added unit tests for MSSQL SELECT syntax. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8459 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- test-phpUnit/SelectXmlTest_Mssql.php | 174 +++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 test-phpUnit/SelectXmlTest_Mssql.php diff --git a/test-phpUnit/SelectXmlTest_Mssql.php b/test-phpUnit/SelectXmlTest_Mssql.php new file mode 100644 index 000000000..227808c3c --- /dev/null +++ b/test-phpUnit/SelectXmlTest_Mssql.php @@ -0,0 +1,174 @@ +getNewParserOutputString($xml_file, '[', $argsString, 'mssql'); + //echo $outputString; + $output = eval($outputString); + + if(!is_a($output, 'Query')){ + if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; + }else { + $db = &DB::getInstance('mssql'); + $querySql = $db->getSelectSql($output); + + // Remove whitespaces, tabs and all + $querySql = Helper::cleanQuery($querySql); + $expected = Helper::cleanQuery($expected); + } + + // Test + $this->assertEquals($expected, $querySql); + } + + function testSelectStar(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; + $argsString = '$args->module_srl = 10;'; + $expected = 'SELECT * FROM [xe_module_admins] as [module_admins] , [xe_member] as [member] WHERE [module_srl] = ? and [member].[member_srl] = [module_admins].[member_srl]'; + $this->_test($xml_file, $argsString, $expected); + } + + function testRquiredParameter(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; + $argsString = ''; + $expected = 'Date incorecte! Query-ul nu a putut fi executat.'; + $this->_test($xml_file, $argsString, $expected); + } + + function testWithoutCategoriesTag(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getModuleCategories.xml"; + $argsString = ''; + $expected = 'SELECT * FROM [xe_module_categories] as [module_categories] ORDER BY [title] asc'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_getDefaultModules(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getDefaultModules.xml"; + $argsString = ''; + $expected = 'SELECT [modules].[site_srl] + , [modules].[module] + , [modules].[mid] + , [modules].[browser_title] + , [module_categories].[title] as [category] + , [modules].[module_srl] + FROM [xe_modules] as [modules] + left join [xe_module_categories] as [module_categories] + on [module_categories].[module_category_srl] = [modules].[module_category_srl] + WHERE [modules].[site_srl] = ? + ORDER BY [modules].[module] asc, [module_categories].[title] asc, [modules].[mid] asc'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_getSiteInfo(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getSiteInfo.xml"; + $argsString = '$args->site_srl = 0;'; + $expected = 'SELECT [modules].[site_srl] as [module_site_srl] + , [modules].[module_srl] as [module_srl] + , [modules].[module] as [module] + , [modules].[module_category_srl] as [module_category_srl] + , [modules].[layout_srl] as [layout_srl] + , [modules].[mlayout_srl] as [mlayout_srl] + , [modules].[use_mobile] as [use_mobile] + , [modules].[menu_srl] as [menu_srl] + , [modules].[mid] as [mid] + , [modules].[skin] as [skin] + , [modules].[mskin] as [mskin] + , [modules].[browser_title] as [browser_title] + , [modules].[description] as [description] + , [modules].[is_default] as [is_default] + , [modules].[content] as [content] + , [modules].[mcontent] as [mcontent] + , [modules].[open_rss] as [open_rss] + , [modules].[header_text] as [header_text] + , [modules].[footer_text] as [footer_text] + , [modules].[regdate] as [regdate] + , [sites].[site_srl] as [site_srl] + , [sites].[domain] as [domain] + , [sites].[index_module_srl] as [index_module_srl] + , [sites].[default_language] as [default_language] + FROM [xe_sites] as [sites] + left join [xe_modules] as [modules] on [modules].[module_srl] = [sites].[index_module_srl] + WHERE [sites].[site_srl] = ? '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_addon_getAddonInfo(){ + $xml_file = _XE_PATH_ . "modules/addon/queries/getAddonInfo.xml"; + $argsString = '$args->addon = "captcha";'; + $expected = 'SELECT * + FROM [xe_addons] as [addons] + WHERE [addon] = ? '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_addon_getAddons(){ + $xml_file = _XE_PATH_ . "modules/addon/queries/getAddons.xml"; + $argsString = ''; + $expected = 'SELECT * + FROM [xe_addons] as [addons] + ORDER BY [addon] asc'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_admin_getCommentCount(){ + $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentCount.xml"; + $argsString = ''; + $expected = 'SELECT count(*) as [count] + FROM [xe_comments] as [comments]'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_admin_getCommentDeclaredStatus(){ + $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentDeclaredStatus.xml"; + $argsString = '$args->date = "20110411";'; + $expected = 'SELECT TOP 2 substr([regdate],1,8) as [date], count(*) as [count] + FROM [xe_comment_declared_log] as [comment_declared_log] + WHERE [regdate] >= ? + GROUP BY substr([regdate],1,8) + ORDER BY substr([regdate],1,8) asc'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_member_getAutoLogin(){ + $xml_file = _XE_PATH_ . "modules/member/queries/getAutoLogin.xml"; + $argsString = '$args->autologin_key = 10;'; + $expected = 'SELECT [member].[user_id] as [user_id] + , [member].[password] as [password] + , [member_autologin].[autologin_key] as [autologin_key] + FROM [xe_member] as [member] , [xe_member_autologin] as [member_autologin] + WHERE [member_autologin].[autologin_key] = ? + and [member].[member_srl] = [member_autologin].[member_srl]'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_opage_getOpageList(){ + $xml_file = _XE_PATH_ . "modules/opage/queries/getOpageList.xml"; + $argsString = '$args->s_title = "yuhuu"; + $args->module = \'opage\';'; + $expected = 'SELECT TOP 20 * + FROM [xe_modules] as [modules] + WHERE [module] = ? and ([browser_title] like ?) + ORDER BY [module_srl] desc'; + $this->_test($xml_file, $argsString, $expected); + } + + // TODO Something fishy about this query - to be investigated + /* + function test_syndication_getGrantedModules(){ + $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml"; + $argsString = '$args->module_srl = 12; + $args->name = array(\'access\',\'view\',\'list\');'; + $expected = 'select "module_srl" + from "xe_module_grants" as "module_grants" + where "name" in (?) + and ("group_srl" >= -2 + or "group_srl" = -2 + or "group_srl" = -2) + group by "module_srl"'; + $this->_test($xml_file, $argsString, $expected); + } + */ + } \ No newline at end of file From 4b3e59195664b3a920b1935947cd1915d30e14df Mon Sep 17 00:00:00 2001 From: lickawtl Date: Wed, 8 Jun 2011 16:24:04 +0000 Subject: [PATCH 37/82] revert to revision 8456 git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8464 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- test-phpUnit/DeleteXmlTest_Cubrid.php | 5 +- test-phpUnit/InsertXmlTest_Cubrid.php | 84 +++++++++++++++++++++++++-- test-phpUnit/SelectXmlTest_Cubrid.php | 6 +- test-phpUnit/UpdateXmlTest_Cubrid.php | 38 +++++++++++- 4 files changed, 121 insertions(+), 12 deletions(-) diff --git a/test-phpUnit/DeleteXmlTest_Cubrid.php b/test-phpUnit/DeleteXmlTest_Cubrid.php index da146978a..d73537bd0 100644 --- a/test-phpUnit/DeleteXmlTest_Cubrid.php +++ b/test-phpUnit/DeleteXmlTest_Cubrid.php @@ -5,13 +5,14 @@ function _test($xml_file, $argsString, $expected){ $tester = new QueryTester(); - $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - $db = new DBCubrid(); + //$db = new DBCubrid(); + $db = &DB::getInstance('cubrid'); $querySql = $db->getDeleteSql($output); // Remove whitespaces, tabs and all diff --git a/test-phpUnit/InsertXmlTest_Cubrid.php b/test-phpUnit/InsertXmlTest_Cubrid.php index c61eca9bb..eba6bb9b3 100644 --- a/test-phpUnit/InsertXmlTest_Cubrid.php +++ b/test-phpUnit/InsertXmlTest_Cubrid.php @@ -5,14 +5,14 @@ function _test($xml_file, $argsString, $expected){ $tester = new QueryTester(); - echo $xml_file . $argsString; - $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - $db = new DBCubrid(); + //$db = new DBCubrid(); + $db = &DB::getInstance('cubrid'); $querySql = $db->getInsertSql($output); // Remove whitespaces, tabs and all @@ -62,9 +62,81 @@ , \'n\')'; $this->_test($xml_file, $argsString, $expected); } - + function test_module_insertSiteTodayStatus(){ + //\''.date("YmdHis").'\' + $xml_file = _XE_PATH_ . "modules/counter/queries/insertTodayStatus.xml"; + $argsString = ' $args->regdate = 0; + $args->unique_visitor = 0; + $args->pageview = 0;'; + $expected = 'insert into "xe_counter_status" + ("regdate" + , "unique_visitor" + , "pageview") + values + (0 + , 0 + , 0)'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_insertCounterLog(){ + $xml_file = _XE_PATH_ . "modules/counter/queries/insertCounterLog.xml"; + $argsString = ' $args->site_srl = 0; + $args->regdate = "20110607120619"; + $args->ipaddress = "127.0.0.1"; + $args->user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24";'; + $expected = 'insert into "xe_counter_log" + ("site_srl", "regdate", "ipaddress", "user_agent") + VALUES (0, \'20110607120619\', \'127.0.0.1\', \'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24\') + '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_insertMember(){ + $xml_file = _XE_PATH_ . "modules/member/queries/insertMember.xml"; + $argsString = ' $args->member_srl = 203; + $args->user_id = "cacao"; + $args->email_address = "teta@ar.ro"; + $args->password = "23e5484cb88f3c07bcce2920a5e6a2a7"; + $args->email_id = "teta"; + $args->email_host = "ar.ro"; + $args->user_name = "trident"; + $args->nick_name = "aloha"; + $args->homepage = "http://jkgjfk./ww"; + $args->allow_mailing = "Y"; + $args->allow_message = "Y"; + $args->denied = "N"; + $args->limit_date = ""; + $args->regdate = "20110607121952"; + $args->change_password_date = "20110607121952"; + $args->last_login = "20110607121952"; + $args->is_admin = "N"; + $args->extra_vars = "O:8:\"stdClass\":2:{s:4:\"body\";s:0:\"\";s:7:\"_filter\";s:6:\"insert\";}"; + $args->list_order = -203; + '; + $expected = 'INSERT INTO "xe_member" + ("member_srl", "user_id", "email_address", "password", "email_id", "email_host", "user_name", "nick_name", + "homepage", "allow_mailing", "allow_message", "denied", "limit_date", "regdate", "change_password_date", + "last_login", "is_admin", "extra_vars", "list_order") + VALUES (203, \'cacao\', \'teta@ar.ro\', \'23e5484cb88f3c07bcce2920a5e6a2a7\', \'teta\', \'ar.ro\', \'trident\', + \'aloha\', \'http://jkgjfk./ww\', \'Y\', \'Y\', \'N\', \'\', \'20110607121952\', \'20110607121952\', + \'20110607121952\', \'N\', \'O:8:"stdClass":2:{s:4:"body";s:0:"";s:7:"_filter";s:6:"insert";}\', -203)'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_insertModuleExtraVars(){ + $xml_file = _XE_PATH_ . "modules/module/queries/insertModuleExtraVars.xml"; + $argsString = ' $args->module_srl = 202; + $args->name = "_filter"; + $args->value = "insert_page"; + '; + $expected = 'INSERT INTO "xe_module_extra_vars" + ("module_srl", "name", "value") + VALUES (202, \'_filter\', \'insert_page\') + '; + $this->_test($xml_file, $argsString, $expected); + } // $queryTester->test_admin_deleteActionForward(); // $queryTester->test_module_insertModule(); - - + } \ No newline at end of file diff --git a/test-phpUnit/SelectXmlTest_Cubrid.php b/test-phpUnit/SelectXmlTest_Cubrid.php index 424d086d6..2fffbe3f7 100644 --- a/test-phpUnit/SelectXmlTest_Cubrid.php +++ b/test-phpUnit/SelectXmlTest_Cubrid.php @@ -5,14 +5,16 @@ function _test($xml_file, $argsString, $expected){ $tester = new QueryTester(); - $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); + //echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - $db = new DBCubrid(); + //$db = new DBCubrid(); + $db = &DB::getInstance('cubrid'); $querySql = $db->getSelectSql($output); // Remove whitespaces, tabs and all diff --git a/test-phpUnit/UpdateXmlTest_Cubrid.php b/test-phpUnit/UpdateXmlTest_Cubrid.php index dbb15edb9..f6cc7707a 100644 --- a/test-phpUnit/UpdateXmlTest_Cubrid.php +++ b/test-phpUnit/UpdateXmlTest_Cubrid.php @@ -5,12 +5,13 @@ function _test($xml_file, $argsString, $expected){ $tester = new QueryTester(); - $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - $db = new DBCubrid(); + //$db = new DBCubrid(); + $db = &DB::getInstance('cubrid'); $querySql = $db->getUpdateSql($output); // Remove whitespaces, tabs and all @@ -47,6 +48,39 @@ AND "module_srl" = 47374'; $this->_test($xml_file, $argsString, $expected); } + function test_module_updateMember(){ + $xml_file = _XE_PATH_ . "modules/member/queries/updateLastLogin.xml"; + $argsString = ' $args->member_srl = 4; + $args->last_login = "20110607120549";'; + $expected = 'UPDATE "xe_member" SET "member_srl" = 4, "last_login" = \'20110607120549\' WHERE "member_srl" = 4'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_updatePoint(){ + $xml_file = _XE_PATH_ . "modules/point/queries/updatePoint.xml"; + $argsString = ' $args->member_srl = 4; + $args->point = 105;'; + $expected = 'UPDATE "xe_point" SET "point" = 105 WHERE "member_srl" = 4'; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_updateCounterUnique(){ + $xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml"; + $argsString = '$args->regdate = 20110607; + '; + $expected = 'UPDATE "xe_counter_status" SET "unique_visitor" = unique_visitor+1, + "pageview" = pageview+1 WHERE "regdate" = 20110607 '; + $this->_test($xml_file, $argsString, $expected); + } + + function test_module_updateMenu(){ + $xml_file = _XE_PATH_ . "modules/menu/queries/updateMenu.xml"; + $argsString = '$args->menu_srl = 204; + $args->title = "test_menu"; + '; + $expected = 'UPDATE "xe_menu" SET "title" = \'test_menu\' WHERE "menu_srl" = 204'; + $this->_test($xml_file, $argsString, $expected); + } // $queryTester->test_admin_deleteActionForward(); // $queryTester->test_module_insertModule(); From 32fe8750e9e55d8522e9c006bf5fb47557103df5 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Mon, 20 Jun 2011 09:25:58 +0000 Subject: [PATCH 38/82] bug-fix pagination Limit git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8510 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 4 ++-- classes/db/queryparts/limit/Limit.class.php | 2 +- test-phpUnit/SelectXmlTest_Cubrid.php | 24 +++++++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index f02f8f8c2..d87904abe 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -668,9 +668,9 @@ $buff = new Object (); $buff->total_count = $total_count; $buff->total_page = $total_page; - $buff->page = $queryObject->getLimit()->page; + $buff->page = $queryObject->getLimit()->page->getValue(); $buff->data = $data; - $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page->getValue(), $queryObject->getLimit()->page_count); }else{ $data = $this->_fetch($result); $buff = new Object (); diff --git a/classes/db/queryparts/limit/Limit.class.php b/classes/db/queryparts/limit/Limit.class.php index a64b27e8a..e5fa18a74 100644 --- a/classes/db/queryparts/limit/Limit.class.php +++ b/classes/db/queryparts/limit/Limit.class.php @@ -8,7 +8,7 @@ function Limit($list_count, $page= NULL, $page_count= NULL){ $this->list_count = $list_count; if ($page){ - $this->start = ($page-1)*$list_count; + $this->start = ($page-1)*$list_count->getValue(); $this->page_count = $page_count; $this->page = $page; } diff --git a/test-phpUnit/SelectXmlTest_Cubrid.php b/test-phpUnit/SelectXmlTest_Cubrid.php index 2fffbe3f7..c2b82dd61 100644 --- a/test-phpUnit/SelectXmlTest_Cubrid.php +++ b/test-phpUnit/SelectXmlTest_Cubrid.php @@ -171,6 +171,30 @@ group by "module_srl"'; $this->_test($xml_file, $argsString, $expected); } + + function test_syndication_getDocumentList(){ + define('__ZBXE__', 1); + + require_once(_XE_PATH_.'classes/page/PageHandler.class.php'); + + $db = &DB::getInstance('cubrid'); + $args = new StdClass(); + $args->module_srl = NULL; + $args->exclude_module_srl = NULL; + $args->category_srl = NULL; + $args->sort_index = 'list_order'; + $args->order_type = 'asc'; + $args->page = 5; + $args->list_count = 30; + $args->page_count = 10; + $args->start_date = NULL; + $args->end_date = NULL; + $args->member_srl = NULL; + $output = $db->executeQuery('document.getDocumentList', $args); + + $this->assertTrue(is_int($output->page)); + // $this->assertTrue($output->page == 5); + } // $queryTester->test_admin_deleteActionForward(); // $queryTester->test_module_insertModule(); From 6f17aa5759578056374fbd398aafe830dc5b1e76 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 20 Jun 2011 14:03:27 +0000 Subject: [PATCH 39/82] Updated query classes in order to support prepared statements - added support for parameter binding. Added unit tests for mssql select using new prepared statement syntax. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8511 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/Query.class.php | 37 ++++++++++++++++--- .../queryparts/condition/Condition.class.php | 5 +++ .../condition/ConditionGroup.class.php | 11 ++++++ .../expression/InsertExpression.class.php | 4 ++ .../expression/SelectExpression.class.php | 4 ++ .../expression/StarExpression.class.php | 4 ++ .../expression/UpdateExpression.class.php | 4 ++ .../queryparts/order/OrderByColumn.class.php | 8 ++++ classes/xml/xmlquery/QueryParser.class.php | 2 +- .../xml/xmlquery/argument/Argument.class.php | 4 ++ test-phpUnit/SelectXmlTest_Mssql.php | 26 ++++++++----- 11 files changed, 93 insertions(+), 16 deletions(-) diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 513627535..d64f28416 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -11,12 +11,8 @@ var $orderby; var $limit; - var $arguments = array(); - - function addArgument($argument){ - $this->arguments[] = $argument; - } - + var $arguments = null; + function setQueryId($queryID){ $this->queryID = $queryID; } @@ -202,6 +198,35 @@ function getFirstTableName(){ return $this->tables[0]->getName(); } + + function getArguments(){ + if(!isset($this->arguments)){ + $this->arguments = array(); + + // Column arguments + foreach($this->columns as $column){ + if($column->show()){ + $arg = $column->getArgument(); + if($arg) $this->arguments[] = $arg; + } + } + + // Condition arguments + if(count($this->conditions) > 0) + foreach($this->conditions as $conditionGroup){ + $args = $conditionGroup->getArguments(); + if(count($args) > 0) $this->arguments = array_merge($this->arguments, $args); + } + + // Navigation arguments + if(count($this->orderby) > 0) + foreach($this->orderby as $order){ + $args = $order->getArguments(); + if(count($args) > 0) $this->arguments = array_merge($this->arguments, $args); + } + } + return $this->arguments; + } } diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index b2c4a3dfa..ac8130c89 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -23,6 +23,11 @@ return is_a($this->argument, 'Argument'); } + function getArgument(){ + if($this->hasArgument()) return $this->argument; + return null; + } + function toString($withValue = true){ if($withValue) return $this->toStringWithValue(); diff --git a/classes/db/queryparts/condition/ConditionGroup.class.php b/classes/db/queryparts/condition/ConditionGroup.class.php index a7d3b3321..e044254f1 100644 --- a/classes/db/queryparts/condition/ConditionGroup.class.php +++ b/classes/db/queryparts/condition/ConditionGroup.class.php @@ -31,5 +31,16 @@ return $group; } + + function getArguments(){ + $args = array(); + foreach($this->conditions as $condition){ + if($condition->show()){ + $arg = $condition->getArgument(); + if($arg) $args[] = $arg; + } + } + return $args; + } } ?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/InsertExpression.class.php b/classes/db/queryparts/expression/InsertExpression.class.php index be546ffc2..07c8a14f0 100644 --- a/classes/db/queryparts/expression/InsertExpression.class.php +++ b/classes/db/queryparts/expression/InsertExpression.class.php @@ -26,6 +26,10 @@ if(!isset($value)) return false; return true; } + + function getArgument(){ + return $this->argument; + } } ?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/SelectExpression.class.php b/classes/db/queryparts/expression/SelectExpression.class.php index 5de23b43a..8a9db88ba 100644 --- a/classes/db/queryparts/expression/SelectExpression.class.php +++ b/classes/db/queryparts/expression/SelectExpression.class.php @@ -28,5 +28,9 @@ function show() { return true; } + + function getArgument(){ + return null; + } } ?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/StarExpression.class.php b/classes/db/queryparts/expression/StarExpression.class.php index c718fdbc9..eb8d35030 100644 --- a/classes/db/queryparts/expression/StarExpression.class.php +++ b/classes/db/queryparts/expression/StarExpression.class.php @@ -12,5 +12,9 @@ function StarExpression(){ parent::SelectExpression("*"); } + + function getArgument(){ + return null; + } } ?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/UpdateExpression.class.php b/classes/db/queryparts/expression/UpdateExpression.class.php index e1c606673..8ec05d250 100644 --- a/classes/db/queryparts/expression/UpdateExpression.class.php +++ b/classes/db/queryparts/expression/UpdateExpression.class.php @@ -40,6 +40,10 @@ if(!$this->argument->getValue()) return false; return true; } + + function getArgument(){ + return $this->argument; + } } diff --git a/classes/db/queryparts/order/OrderByColumn.class.php b/classes/db/queryparts/order/OrderByColumn.class.php index c33749488..8866c057a 100644 --- a/classes/db/queryparts/order/OrderByColumn.class.php +++ b/classes/db/queryparts/order/OrderByColumn.class.php @@ -14,6 +14,14 @@ $result .= is_a($this->sort_order, 'Argument') ? $this->sort_order->getValue() : $this->sort_order; return $result; } + + function getArguments(){ + $args = array(); + if(is_a($this->column_name, 'Argument')) + $args[]= $this->column_name; + if(is_a($this->sort_order, 'Argument')) + $args[] = $this->sort_order; + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 53d939c5d..d9bc88399 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -109,6 +109,7 @@ class QueryParser { $this->setTableColumnTypes($tables); + // TODO Check if this work with arguments in join clause $arguments = array(); if($columns) $arguments = array_merge($arguments, $columns->getArguments()); @@ -122,7 +123,6 @@ class QueryParser { $prebuff .= sprintf("$%s_argument->setColumnType('%s');\n" , $argument->getArgumentName() , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); - $prebuff .= sprintf('$query->addArgument($%s_argument);', $argument->getArgumentName()); } } $prebuff .= "\n"; diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index d3acf9830..a05ca0edb 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -14,6 +14,10 @@ $this->isValid = true; } + function getName(){ + return $this->name; + } + function getValue(){ if(is_array($this->value)) return implode(',', $this->value); return $this->value; diff --git a/test-phpUnit/SelectXmlTest_Mssql.php b/test-phpUnit/SelectXmlTest_Mssql.php index 227808c3c..b0274342a 100644 --- a/test-phpUnit/SelectXmlTest_Mssql.php +++ b/test-phpUnit/SelectXmlTest_Mssql.php @@ -3,7 +3,7 @@ class SelectXmlTest_Mssql extends PHPUnit_Framework_TestCase { - function _test($xml_file, $argsString, $expected){ + function _test($xml_file, $argsString, $expected, $expectedArgs = NULL){ $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, '[', $argsString, 'mssql'); //echo $outputString; @@ -14,7 +14,8 @@ }else { $db = &DB::getInstance('mssql'); $querySql = $db->getSelectSql($output); - + $queryArguments = $output->getArguments(); + // Remove whitespaces, tabs and all $querySql = Helper::cleanQuery($querySql); $expected = Helper::cleanQuery($expected); @@ -22,13 +23,20 @@ // Test $this->assertEquals($expected, $querySql); + + // Test query arguments + $argCount = count($expectedArgs); + for($i = 0; $i < $argCount; $i++){ + //echo "$i: $expectedArgs[$i] vs $queryArguments[$i]->getValue()"; + $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue()); + } } function testSelectStar(){ $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; $argsString = '$args->module_srl = 10;'; $expected = 'SELECT * FROM [xe_module_admins] as [module_admins] , [xe_member] as [member] WHERE [module_srl] = ? and [member].[member_srl] = [module_admins].[member_srl]'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected, array(10)); } function testRquiredParameter(){ @@ -59,7 +67,7 @@ on [module_categories].[module_category_srl] = [modules].[module_category_srl] WHERE [modules].[site_srl] = ? ORDER BY [modules].[module] asc, [module_categories].[title] asc, [modules].[mid] asc'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected, array(0)); } function test_module_getSiteInfo(){ @@ -92,7 +100,7 @@ FROM [xe_sites] as [sites] left join [xe_modules] as [modules] on [modules].[module_srl] = [sites].[index_module_srl] WHERE [sites].[site_srl] = ? '; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected, array(0)); } function test_addon_getAddonInfo(){ @@ -101,7 +109,7 @@ $expected = 'SELECT * FROM [xe_addons] as [addons] WHERE [addon] = ? '; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected, array("'captcha'")); } function test_addon_getAddons(){ @@ -129,7 +137,7 @@ WHERE [regdate] >= ? GROUP BY substr([regdate],1,8) ORDER BY substr([regdate],1,8) asc'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected, array("'20110411'")); } function test_member_getAutoLogin(){ @@ -141,7 +149,7 @@ FROM [xe_member] as [member] , [xe_member_autologin] as [member_autologin] WHERE [member_autologin].[autologin_key] = ? and [member].[member_srl] = [member_autologin].[member_srl]'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected, array("'10'")); } function test_opage_getOpageList(){ @@ -152,7 +160,7 @@ FROM [xe_modules] as [modules] WHERE [module] = ? and ([browser_title] like ?) ORDER BY [module_srl] desc'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected, array("'opage'", "'%yuhuu%'")); } // TODO Something fishy about this query - to be investigated From ed3fd79304b6be4caa9b92dd831a0ab1cfe9028e Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 21 Jun 2011 10:01:43 +0000 Subject: [PATCH 40/82] escape string value git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8518 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/DBParser.class.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/classes/xml/xmlquery/DBParser.class.php b/classes/xml/xmlquery/DBParser.class.php index 59cabb9fd..e3d1d0e3b 100644 --- a/classes/xml/xmlquery/DBParser.class.php +++ b/classes/xml/xmlquery/DBParser.class.php @@ -21,7 +21,13 @@ } function escapeString($name){ - return "'".$name."'"; + return "'".$this->escapeStringValue($name)."'"; + } + + function escapeStringValue($value){ + if($value == "*") return $value; + if (!is_numeric($value)) return $value = str_replace("'","\'",$string); + return $value; } function parseTableName($name){ From e13c62c4795f1a19145e5aaecbdde7e4a69c8a08 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 21 Jun 2011 11:27:10 +0000 Subject: [PATCH 41/82] escape string value git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8522 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/DBParser.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/xml/xmlquery/DBParser.class.php b/classes/xml/xmlquery/DBParser.class.php index e3d1d0e3b..7b1acf62a 100644 --- a/classes/xml/xmlquery/DBParser.class.php +++ b/classes/xml/xmlquery/DBParser.class.php @@ -26,7 +26,7 @@ function escapeStringValue($value){ if($value == "*") return $value; - if (!is_numeric($value)) return $value = str_replace("'","\'",$string); + if (is_string($value)) return $value = str_replace("'","\'",$value); return $value; } From 2c21bc07e909592e1edc94f23c7d0ced77396ba2 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 21 Jun 2011 11:28:08 +0000 Subject: [PATCH 42/82] escape string value git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8523 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/argument/Argument.class.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index a05ca0edb..24e33ecf3 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -10,7 +10,14 @@ function Argument($name, $value){ $this->name = $name; - $this->value = $value; + + if($this->type !== 'date'){ + $dbParser = XmlQueryParser::getDBParser(); + $this->value = $dbParser->escapeStringValue($value); + } + else + $this->value = $value; + $this->isValid = true; } From 7f0c67bfae23b94b7de55012afb0ea7ae9a5086e Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 21 Jun 2011 11:56:00 +0000 Subject: [PATCH 43/82] escape string value git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8524 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 1 + 1 file changed, 1 insertion(+) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index cd504d9c9..8eb866797 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -306,6 +306,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/ConditionArgument.class.php'); + require_once(_XE_PATH_.'classes/xml/XmlQueryParser.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/SelectExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/InsertExpression.class.php'); From 33c09230096a0799c5d28eb999c98245bbcd99ea Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 21 Jun 2011 12:20:11 +0000 Subject: [PATCH 44/82] escape string value git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8525 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/DBParser.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/xml/xmlquery/DBParser.class.php b/classes/xml/xmlquery/DBParser.class.php index 7b1acf62a..b58e7c028 100644 --- a/classes/xml/xmlquery/DBParser.class.php +++ b/classes/xml/xmlquery/DBParser.class.php @@ -26,7 +26,7 @@ function escapeStringValue($value){ if($value == "*") return $value; - if (is_string($value)) return $value = str_replace("'","\'",$value); + if (is_string($value)) return $value = str_replace("'","''",$value); return $value; } From 763fc6d56b6a477467d9678f4ea0ed60cda923ee Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 23 Jun 2011 16:04:46 +0000 Subject: [PATCH 45/82] DBMssql class - working version of XE with SQL Server. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8535 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBMssql.class.php | 73 ++++++++++++++++--- classes/db/DBMysql.class.php | 2 +- classes/db/queryparts/Query.class.php | 14 ++-- .../xml/xmlquery/argument/Argument.class.php | 36 ++++++--- modules/install/tpl/filter/mssql.xml | 2 +- 5 files changed, 97 insertions(+), 30 deletions(-) diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index d5c7793f4..7f7d28e3a 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -166,10 +166,11 @@ if(count($this->param)){ foreach($this->param as $k => $o){ - if($o['type'] == 'number'){ - $_param[] = &$o['value']; + if($o->getType() == 'number'){ + $_param[] = $o->getUnescapedValue(); }else{ - $_param[] = array(&$o['value'], SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); + $value = $o->getUnescapedValue(); + $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); } } } @@ -414,7 +415,8 @@ **/ // TODO Lookup _filterNumber against sql injection - see if it is still needed and how to integrate function _executeInsertAct($queryObject) { - $query = ''; + $query = $this->getInsertSql($queryObject); + $this->param = $queryObject->getArguments(); return $this->_query($query); } @@ -422,7 +424,8 @@ * @brief Handle updateAct **/ function _executeUpdateAct($queryObject) { - $query = ''; + $query = $this->getUpdateSql($queryObject); + $this->param = $queryObject->getArguments(); return $this->_query($query); } @@ -430,7 +433,8 @@ * @brief Handle deleteAct **/ function _executeDeleteAct($queryObject) { - $query = ''; + $query = $this->getDeleteSql($queryObject); + $this->param = $queryObject->getArguments(); return $this->_query($query); } @@ -477,14 +481,61 @@ * it supports a method as navigation **/ function _executeSelectAct($queryObject) { + $query = $this->getSelectSql($queryObject); + + // TODO Decide if we continue to pass parameters like this + $this->param = $queryObject->getArguments(); + $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; $result = $this->_query($query); - if($this->isError()) return; - $data = $this->_fetch($result); - $buff = new Object(); - $buff->data = $data; - return $buff; + if ($this->isError ()) { + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + }else + return; + } + + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } + + $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result_count = $this->_query($count_query); + $count_output = $this->_fetch($result_count); + $total_count = (int)$count_output->count; + + // Total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; + } else $total_page = 1; + + + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; + $data = $this->_fetch($result, $virtual_no); + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $queryObject->getLimit()->page; + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + }else{ + $data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } + + return $buff; } function getParser(){ diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index 72f7bfe09..a9bdc9c8c 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -439,7 +439,7 @@ $result = $this->_query ($query); if ($this->isError ()) { - if ($limit && $output->limit->isPageHandler()){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ $buff = new Object (); $buff->total_count = 0; $buff->total_page = 0; diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index d64f28416..1995884db 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -204,12 +204,14 @@ $this->arguments = array(); // Column arguments - foreach($this->columns as $column){ - if($column->show()){ - $arg = $column->getArgument(); - if($arg) $this->arguments[] = $arg; - } - } + if(count($this->columns) > 0){ // The if is for delete statements, all others must have columns + foreach($this->columns as $column){ + if($column->show()){ + $arg = $column->getArgument(); + if($arg) $this->arguments[] = $arg; + } + } + } // Condition arguments if(count($this->conditions) > 0) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 24e33ecf3..cf85710a6 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -26,8 +26,30 @@ } function getValue(){ - if(is_array($this->value)) return implode(',', $this->value); - return $this->value; + $value = $this->escapeValue($this->value); + return $this->toString($value); + } + + function getUnescapedValue(){ + return $this->toString($this->value); + } + + function toString($value){ + if(is_array($value)) return implode(',', $value); + return $value; + } + + function escapeValue($value){ + if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ + if(!is_array($value)) + $value = '\''.$value.'\''; + else { + $total = count($value); + for($i = 0; $i < $total; $i++) + $value[$i] = '\''.$value[$i].'\''; + } + } + return $value; } function getType(){ @@ -54,15 +76,7 @@ $this->type = $column_type; //if($column_type === '') $column_type = 'varchar'; - if(in_array($column_type, array('date', 'varchar', 'char','text', 'bigtext'))){ - if(!is_array($this->value)) - $this->value = '\''.$this->value.'\''; - else { - $total = count($this->value); - for($i = 0; $i < $total; $i++) - $this->value[$i] = '\''.$this->value[$i].'\''; - } - } + } function checkFilter($filter_type){ diff --git a/modules/install/tpl/filter/mssql.xml b/modules/install/tpl/filter/mssql.xml index 5a97ffc06..082438ac2 100644 --- a/modules/install/tpl/filter/mssql.xml +++ b/modules/install/tpl/filter/mssql.xml @@ -15,7 +15,7 @@ - + From af9ced8c5ca673c739cba93a53bcd23d9d744081 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Mon, 27 Jun 2011 13:45:52 +0000 Subject: [PATCH 46/82] start implementing SubQuery git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8538 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/QueryParser.class.php | 94 +----------- .../tags/column/InsertColumnsTag.class.php | 3 +- .../tags/column/SelectColumnsTag.class.php | 3 +- .../tags/column/UpdateColumnsTag.class.php | 3 +- .../condition/ConditionGroupTag.class.php | 3 +- .../xmlquery/tags/query/QueryTag.class.php | 142 ++++++++++++++++++ .../xmlquery/tags/table/TablesTag.class.php | 3 +- 7 files changed, 160 insertions(+), 91 deletions(-) create mode 100644 classes/xml/xmlquery/tags/query/QueryTag.class.php diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index d9bc88399..5272c7857 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -10,28 +10,15 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/JoinConditionsTag.cl require_once(_XE_PATH_.'classes/xml/xmlquery/tags/group/GroupsTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/navigation/NavigationTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/navigation/IndexTag.class.php'); +require_once(_XE_PATH_.'classes/xml/xmlquery/tags/query/QueryTag.class.php'); class QueryParser { - var $query; - var $action; - var $query_id; - - var $column_type; - - function QueryParser($query){ - $this->query = $query; - $this->action = $this->query->attrs->action; - $this->query_id = $this->query->attrs->id; + var $queryTag; + + function QueryParser($query, $isSubQuery = false){ + $this->queryTag = new QueryTag($query, $isSubQuery); } - function getQueryId(){ - return $this->query->attrs->query_id ? $this->query->attrs->query_id : $this->query->attrs->id; - } - - function getAction(){ - return $this->query->attrs->action; - } - function getTableInfo($query_id, $table_name){ $column_type = array(); @@ -77,75 +64,10 @@ class QueryParser { return $column_type; } - function setTableColumnTypes($tables){ - $query_id = $this->getQueryId(); - if(!isset($this->column_type[$query_id])){ - $table_tags = $tables->getTables(); - $column_type = array(); - foreach($table_tags as $table_tag){ - $tag_column_type = $this->getTableInfo($query_id, $table_tag->getTableName()); - $column_type = array_merge($column_type, $tag_column_type); - } - $this->column_type[$query_id] = $column_type; - } - } - function toString(){ - if($this->action == 'select'){ - $columns = new SelectColumnsTag($this->query->columns->column); - }else if($this->action == 'insert'){ - $columns = new InsertColumnsTag($this->query->columns->column); - }else if($this->action == 'update') { - $columns = new UpdateColumnsTag($this->query->columns->column); - }else if($this->action == 'delete') { - $columns = null; - } - - - $tables = new TablesTag($this->query->tables->table); - $conditions = new ConditionsTag($this->query->conditions); - $groups = new GroupsTag($this->query->groups->group); - $navigation = new NavigationTag($this->query->navigation); - - $this->setTableColumnTypes($tables); - - // TODO Check if this work with arguments in join clause - $arguments = array(); - if($columns) - $arguments = array_merge($arguments, $columns->getArguments()); - $arguments = array_merge($arguments, $conditions->getArguments()); - $arguments = array_merge($arguments, $navigation->getArguments()); - - $prebuff = ''; - foreach($arguments as $argument){ - if(isset($argument) && $argument->getArgumentName()){ - $prebuff .= $argument->toString(); - $prebuff .= sprintf("$%s_argument->setColumnType('%s');\n" - , $argument->getArgumentName() - , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); - } - } - $prebuff .= "\n"; - - $buff = ''; - if($columns) - $buff .= '$query->setColumns(' . $columns->toString() . ');'.PHP_EOL; - - $buff .= '$query->setTables(' . $tables->toString() .');'.PHP_EOL; - $buff .= '$query->setConditions('.$conditions->toString() .');'.PHP_EOL; - $buff .= '$query->setGroups(' . $groups->toString() . ');'.PHP_EOL; - $buff .= '$query->setOrder(' . $navigation->getOrderByString() .');'.PHP_EOL; - $buff .= '$query->setLimit(' . $navigation->getLimitString() .');'.PHP_EOL; - - return "setQueryId("%s");%s', $this->query_id, "\n") - . sprintf('$query->setAction("%s");%s', $this->action, "\n") - . $prebuff - . $buff - . 'return $query; ?>'; - - + return "queryTag->toString() + . 'return $query; ?>'; } } diff --git a/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php index 5f0893b1f..a067a6d10 100644 --- a/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php @@ -21,7 +21,8 @@ if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - $this->columns[] = new InsertColumnTag($column); + if($column->name === 'query') $this->columns[] = new QueryTag($column, true); + else $this->columns[] = new InsertColumnTag($column); } } diff --git a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php index e5e741042..f669329e4 100644 --- a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php @@ -17,7 +17,8 @@ if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - $this->columns[] = new SelectColumnTag($column); + if($column->name === 'query') $this->columns[] = new QueryTag($column, true); + else $this->columns[] = new SelectColumnTag($column); } } diff --git a/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php index a0a856af1..581f9ad8a 100644 --- a/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/UpdateColumnsTag.class.php @@ -19,7 +19,8 @@ if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - $this->columns[] = new UpdateColumnTag($column); + if($column->name === 'query') $this->columns[] = new QueryTag($column, true); + else $this->columns[] = new UpdateColumnTag($column); } } diff --git a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php index 728be23b1..57b250e73 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php @@ -11,7 +11,8 @@ if(count($conditions))require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); foreach($conditions as $condition){ - $this->conditions[] = new ConditionTag($condition); + if($condition->name === 'query') $this->conditions[] = new QueryTag($condition, true); + else $this->conditions[] = new ConditionTag($condition); } } diff --git a/classes/xml/xmlquery/tags/query/QueryTag.class.php b/classes/xml/xmlquery/tags/query/QueryTag.class.php new file mode 100644 index 000000000..94906c6db --- /dev/null +++ b/classes/xml/xmlquery/tags/query/QueryTag.class.php @@ -0,0 +1,142 @@ +action = $query->attrs->action; + $this->query_id = $query->attrs->id; + $this->query = $query; + $this->isSubQuery = $isSubQuery; + + $this->getColumns(); + $tables = $this->getTables(); + $this->setTableColumnTypes($tables); + $this->getConditions(); + $this->getGroups(); + $this->getNavigation(); + $this->getPrebuff(); + $this->getBuff(); + } + + function getQueryId(){ + return $this->query->attrs->query_id ? $this->query->attrs->query_id : $this->query->attrs->id; + } + + function getAction(){ + return $this->query->attrs->action; + } + + function setTableColumnTypes($tables){ + $query_id = $this->getQueryId(); + if(!isset($this->column_type[$query_id])){ + $table_tags = $tables->getTables(); + $column_type = array(); + foreach($table_tags as $table_tag){ + $tag_column_type = QueryParser::getTableInfo($query_id, $table_tag->getTableName()); + $column_type = array_merge($column_type, $tag_column_type); + } + $this->column_type[$query_id] = $column_type; + } + } + + function getColumns(){ + if($this->action == 'select'){ + return $this->columns = new SelectColumnsTag($this->query->columns->column); + }else if($this->action == 'insert'){ + return $this->columns = new InsertColumnsTag($this->query->columns->column); + }else if($this->action == 'update') { + return $this->columns = new UpdateColumnsTag($this->query->columns->column); + }else if($this->action == 'delete') { + return $this->columns = null; + } + } + + function getPrebuff(){ + // TODO Check if this work with arguments in join clause + $arguments = array(); + if($this->columns) + $arguments = array_merge($arguments, $this->columns->getArguments()); + $arguments = array_merge($arguments, $this->conditions->getArguments()); + $arguments = array_merge($arguments, $this->navigation->getArguments()); + + $prebuff = ''; + foreach($arguments as $argument){ + if(isset($argument) && $argument->getArgumentName()){ + $prebuff .= $argument->toString(); + $prebuff .= sprintf("$%s_argument->setColumnType('%s');\n" + , $argument->getArgumentName() + , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); + } + } + $prebuff .= "\n"; + + return $this->preBuff = $prebuff; + } + + function getBuff(){ + $buff = ''; + if($this->isSubQuery) $buff .= '$query = new Query();'.PHP_EOL; + else $buff .= '$query = new Query();'.PHP_EOL; + $buff .= sprintf('$query->setQueryId("%s");%s', $this->query_id, "\n"); + $buff .= sprintf('$query->setAction("%s");%s', $this->action, "\n"); + $buff .= $this->preBuff; + if($this->columns) + $buff .= '$query->setColumns(' . $this->columns->toString() . ');'.PHP_EOL; + + $buff .= '$query->setTables(' . $this->tables->toString() .');'.PHP_EOL; + $buff .= '$query->setConditions('.$this->conditions->toString() .');'.PHP_EOL; + $buff .= '$query->setGroups(' . $this->groups->toString() . ');'.PHP_EOL; + $buff .= '$query->setOrder(' . $this->navigation->getOrderByString() .');'.PHP_EOL; + $buff .= '$query->setLimit(' . $this->navigation->getLimitString() .');'.PHP_EOL; + + return $this->buff = $buff; + } + + function getTables(){ + return $this->tables = new TablesTag($this->query->tables->table); + } + + function getConditions(){ + return $this->conditions = new ConditionsTag($this->query->conditions); + } + + function getGroups(){ + return $this->groups = new GroupsTag($this->query->groups->group); + } + + function getNavigation(){ + return $this->navigation = new NavigationTag($this->query->navigation); + } + + function toString(){ + return $this->buff; + } + + function getTableString(){ + return $this->buff; + } + + function getConditionString(){ + return $this->buff; + } + + function getExpressionString(){ + return $this->buff; + } +} +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/table/TablesTag.class.php b/classes/xml/xmlquery/tags/table/TablesTag.class.php index d4560594b..aaa58ae63 100644 --- a/classes/xml/xmlquery/tags/table/TablesTag.class.php +++ b/classes/xml/xmlquery/tags/table/TablesTag.class.php @@ -10,7 +10,8 @@ if(count($xml_tables)) require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); foreach($xml_tables as $table){ - $this->tables[] = new TableTag($table); + if($table->name === 'query') $this->tables[] = new QueryTag($table, true); + else $this->tables[] = new TableTag($table); } } From 0a53ac3e9da7af8d6bb027d37e02c1e6d143db35 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 27 Jun 2011 17:44:56 +0000 Subject: [PATCH 47/82] First version of uncorellated select subquery. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8539 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 187 ++++++++++++++++++ classes/db/queryparts/Query.class.php | 31 ++- classes/db/queryparts/Subquery.class.php | 25 +++ .../tags/column/SelectColumnsTag.class.php | 34 +++- .../xmlquery/tags/query/QueryTag.class.php | 56 ++++-- 5 files changed, 315 insertions(+), 18 deletions(-) create mode 100644 classes/db/queryparts/Subquery.class.php diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 8eb866797..40f966c2e 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -526,5 +526,192 @@ return new DBParser('"'); } + + // TO BE REMOVED - Used for query compare + /** + * @brief returns type of column + * @param[in] $column_type_list list of column type + * @param[in] $name name of column type + * @return column type of $name + * @remarks columns are usually like a.b, so it needs another function + **/ + function getColumnType($column_type_list, $name) { + if(strpos($name, '.') === false) return $column_type_list[$name]; + list($prefix, $name) = explode('.', $name); + return $column_type_list[$name]; + } + /** + * @brief returns the value of condition + * @param[in] $name name of condition + * @param[in] $value value of condition + * @param[in] $operation operation this is used in condition + * @param[in] $type type of condition + * @param[in] $column_type type of column + * @return well modified $value + * @remarks if $operation is like or like_prefix, $value itself will be modified + * @remarks if $type is not 'number', call addQuotes() and wrap with ' ' + **/ + function getConditionValue($name, $value, $operation, $type, $column_type) { + if(!in_array($operation,array('in','notin','between')) && $type == 'number') { + if(is_array($value)){ + $value = join(',',$value); + } + if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; + return $value; + } + + if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { + list($table_name, $column_name) = explode('.', $value); + if($column_type[$column_name]) return $value; + } + + switch($operation) { + case 'like_prefix' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = $value.'%'; + break; + case 'like_tail' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = '%'.$value; + break; + case 'like' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = '%'.$value.'%'; + break; + case 'notin' : + if(is_array($value)) + { + $value = $this->addQuotesArray($value); + if($type=='number') return join(',',$value); + else return "'". join("','",$value)."'"; + } + else + { + return $value; + } + break; + case 'in' : + if(is_array($value)) + { + $value = $this->addQuotesArray($value); + if($type=='number') return join(',',$value); + else return "'". join("','",$value)."'"; + } + else + { + return $value; + } + break; + case 'between' : + if(!is_array($value)) $value = array($value); + $value = $this->addQuotesArray($value); + if($type!='number') + { + foreach($value as $k=>$v) + { + $value[$k] = "'".$v."'"; + } + } + + return $value; + break; + default: + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + } + + return "'".$this->addQuotes($value)."'"; + } + /** + * @brief returns part of condition + * @param[in] $name name of condition + * @param[in] $value value of condition + * @param[in] $operation operation that is used in condition + * @return detail condition + **/ + function getConditionPart($name, $value, $operation) { + switch($operation) { + case 'equal' : + case 'more' : + case 'excess' : + case 'less' : + case 'below' : + case 'like_tail' : + case 'like_prefix' : + case 'like' : + case 'in' : + case 'notin' : + case 'notequal' : + // if variable is not set or is not string or number, return + if(!isset($value)) return; + if($value === '') return; + if(!in_array(gettype($value), array('string', 'integer'))) return; + break; + case 'between' : + if(!is_array($value)) return; + if(count($value)!=2) return; + + } + + switch($operation) { + case 'equal' : + return $name.' = '.$value; + break; + case 'more' : + return $name.' >= '.$value; + break; + case 'excess' : + return $name.' > '.$value; + break; + case 'less' : + return $name.' <= '.$value; + break; + case 'below' : + return $name.' < '.$value; + break; + case 'like_tail' : + case 'like_prefix' : + case 'like' : + return $name.' like '.$value; + break; + case 'in' : + return $name.' in ('.$value.')'; + break; + case 'notin' : + return $name.' not in ('.$value.')'; + break; + case 'notequal' : + return $name.' <> '.$value; + break; + case 'notnull' : + return $name.' is not null'; + break; + case 'null' : + return $name.' is null'; + break; + case 'between' : + return $name.' between ' . $value[0] . ' and ' . $value[1]; + break; + } + } + + /** + * @brief returns condition key + * @param[in] $output result of query + * @return array of conditions of $output + **/ + function getConditionList($output) { + $conditions = array(); + if(count($output->conditions)) { + foreach($output->conditions as $key => $val) { + if($val['condition']) { + foreach($val['condition'] as $k => $v) { + $conditions[] = $v['column']; + } + } + } + } + + return $conditions; + } } ?> diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 1995884db..7612622a8 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -12,7 +12,30 @@ var $limit; var $arguments = null; + + function Query($queryID = null + , $action = null + , $columns = null + , $tables = null + , $conditions = null + , $groups = null + , $orderby = null + , $limit = null){ + $this->queryID = $queryID; + $this->action = $action; + + $this->columns = $columns; + $this->tables = $tables; + $this->conditions = $conditions; + $this->groups = $groups; + $this->orderby = $orderby; + $this->limit = $limit; + } + function show(){ + return true; + } + function setQueryId($queryID){ $this->queryID = $queryID; } @@ -110,8 +133,14 @@ function getSelectString($with_values = true){ $select = ''; foreach($this->columns as $column){ + var_dump($column); if($column->show()) - $select .= $column->getExpression($with_values) . ', '; + if(is_a($column, 'Subquery')){ + $oDB = &DB::getInstance(); + $select .= '(' .$oDB->getSelectSql($column, $with_values) . ') as \''. $column->getAlias().'\', '; + } + else + $select .= $column->getExpression($with_values) . ', '; } if(trim($select) == '') return ''; $select = substr($select, 0, -2); diff --git a/classes/db/queryparts/Subquery.class.php b/classes/db/queryparts/Subquery.class.php new file mode 100644 index 000000000..463aed658 --- /dev/null +++ b/classes/db/queryparts/Subquery.class.php @@ -0,0 +1,25 @@ +alias = $alias; + + $this->queryID = null; + $this->action = null; + + $this->columns = $columns; + $this->tables = $tables; + $this->conditions = $conditions; + $this->groups = $groups; + $this->orderby = $orderby; + $this->limit = $limit; + } + + function getAlias(){ + return $this->alias; + } + } + +?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php index f669329e4..ffe84809c 100644 --- a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php @@ -6,7 +6,10 @@ class SelectColumnsTag { var $columns; - function SelectColumnsTag($xml_columns){ + function SelectColumnsTag($xml_columns_tag){ + $xml_columns = $xml_columns_tag->column; + $xml_queries = $xml_columns_tag->query; + $this->columns = array(); if(!$xml_columns) { @@ -15,17 +18,31 @@ } if(!is_array($xml_columns)) $xml_columns = array($xml_columns); - + foreach($xml_columns as $column){ - if($column->name === 'query') $this->columns[] = new QueryTag($column, true); + if($column->node_name == 'query') $this->columns[] = new QueryTag($column, true); else $this->columns[] = new SelectColumnTag($column); - } + } + + + if(!$xml_queries) { + return; + } + + if(!is_array($xml_queries)) $xml_queries = array($xml_queries); + + foreach($xml_queries as $column){ + $this->columns[] = new QueryTag($column, true); + } } function toString(){ $output_columns = 'array(' . PHP_EOL; foreach($this->columns as $column){ - $output_columns .= $column->getExpressionString() . PHP_EOL . ','; + if(is_a($column, 'QueryTag')) + $output_columns .= $column->toString() . PHP_EOL . ','; + else + $output_columns .= $column->getExpressionString() . PHP_EOL . ','; } $output_columns = substr($output_columns, 0, -1); $output_columns .= ')'; @@ -33,7 +50,12 @@ } function getArguments(){ - return array(); + $arguments = array(); + foreach($this->columns as $column){ + if(is_a($column, 'QueryTag')) + $arguments = array_merge($arguments, $column->getArguments()); + } + return $arguments; } } ?> diff --git a/classes/xml/xmlquery/tags/query/QueryTag.class.php b/classes/xml/xmlquery/tags/query/QueryTag.class.php index 94906c6db..59b94c1df 100644 --- a/classes/xml/xmlquery/tags/query/QueryTag.class.php +++ b/classes/xml/xmlquery/tags/query/QueryTag.class.php @@ -17,12 +17,16 @@ class QueryTag { var $buff; var $isSubQuery; + var $alias; + function QueryTag($query, $isSubQuery = false){ $this->action = $query->attrs->action; $this->query_id = $query->attrs->id; $this->query = $query; $this->isSubQuery = $isSubQuery; - + if($this->isSubQuery) $this->action = 'select'; + $this->alias = $query->attrs->alias; + $this->getColumns(); $tables = $this->getTables(); $this->setTableColumnTypes($tables); @@ -33,6 +37,10 @@ class QueryTag { $this->getBuff(); } + function show(){ + return true; + } + function getQueryId(){ return $this->query->attrs->query_id ? $this->query->attrs->query_id : $this->query->attrs->id; } @@ -56,7 +64,7 @@ class QueryTag { function getColumns(){ if($this->action == 'select'){ - return $this->columns = new SelectColumnsTag($this->query->columns->column); + return $this->columns = new SelectColumnsTag($this->query->columns); }else if($this->action == 'insert'){ return $this->columns = new InsertColumnsTag($this->query->columns->column); }else if($this->action == 'update') { @@ -68,11 +76,7 @@ class QueryTag { function getPrebuff(){ // TODO Check if this work with arguments in join clause - $arguments = array(); - if($this->columns) - $arguments = array_merge($arguments, $this->columns->getArguments()); - $arguments = array_merge($arguments, $this->conditions->getArguments()); - $arguments = array_merge($arguments, $this->navigation->getArguments()); + $arguments = $this->getArguments(); $prebuff = ''; foreach($arguments as $argument){ @@ -90,8 +94,27 @@ class QueryTag { function getBuff(){ $buff = ''; - if($this->isSubQuery) $buff .= '$query = new Query();'.PHP_EOL; - else $buff .= '$query = new Query();'.PHP_EOL; + echo 'start ---'; + var_dump($this); + echo 'end ---'; + //echo 'Luam un query care e '.$this->isSubQuery; + if($this->isSubQuery){ + $buff = 'new Subquery('; + $buff .= "'" . $this->alias . '\', '; + $buff .= ($this->columns ? $this->columns->toString() : 'null' ). ', '.PHP_EOL; + $buff .= $this->tables->toString() .','.PHP_EOL; + $buff .= $this->conditions->toString() .',' .PHP_EOL; + $buff .= $this->groups->toString() . ',' .PHP_EOL; + $buff .= $this->navigation->getOrderByString() .','.PHP_EOL; + $limit = $this->navigation->getLimitString() ; + $buff .= $limit ? $limit : 'null' . PHP_EOL; + $buff .= ')'; + + $this->buff = $buff; + return $this->buff; + } + + $buff .= '$query = new Query();'.PHP_EOL; $buff .= sprintf('$query->setQueryId("%s");%s', $this->query_id, "\n"); $buff .= sprintf('$query->setAction("%s");%s', $this->action, "\n"); $buff .= $this->preBuff; @@ -104,8 +127,9 @@ class QueryTag { $buff .= '$query->setOrder(' . $this->navigation->getOrderByString() .');'.PHP_EOL; $buff .= '$query->setLimit(' . $this->navigation->getLimitString() .');'.PHP_EOL; - return $this->buff = $buff; - } + $this->buff = $buff; + return $this->buff; + } function getTables(){ return $this->tables = new TablesTag($this->query->tables->table); @@ -138,5 +162,15 @@ class QueryTag { function getExpressionString(){ return $this->buff; } + + function getArguments(){ + $arguments = array(); + if($this->columns) + $arguments = array_merge($arguments, $this->columns->getArguments()); + $arguments = array_merge($arguments, $this->conditions->getArguments()); + $arguments = array_merge($arguments, $this->navigation->getArguments()); + return $arguments; + } + } ?> \ No newline at end of file From c3fdbbf399e6e499b4cb9c85e6c537e3b4cae13b Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 28 Jun 2011 08:05:21 +0000 Subject: [PATCH 48/82] Update test folder structure. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8540 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- test-phpUnit/QueryTester.class.php | 3 +-- .../{ => db}/ExpressionParserTest.php | 2 +- .../xml_query/cubrid/CubridDeleteTest.php} | 20 ++++++++----------- .../xml_query/cubrid/CubridInsertTest.php} | 16 ++++++++------- .../xml_query/cubrid/CubridSelectTest.php} | 19 ++++++------------ .../xml_query/cubrid/CubridUpdateTest.php} | 12 +++++------ .../db/xml_query/cubrid/config.cubrid.inc.php | 8 ++++++++ .../xml_query/mssql/MssqlSelectTest.php} | 9 +++++---- .../db/xml_query/mssql/config.mssql.inc.php | 8 ++++++++ test-phpUnit/debug.php | 11 ++++++++++ 10 files changed, 63 insertions(+), 45 deletions(-) rename test-phpUnit/{ => db}/ExpressionParserTest.php (96%) rename test-phpUnit/{DeleteXmlTest_Cubrid.php => db/xml_query/cubrid/CubridDeleteTest.php} (65%) rename test-phpUnit/{InsertXmlTest_Cubrid.php => db/xml_query/cubrid/CubridInsertTest.php} (89%) rename test-phpUnit/{SelectXmlTest_Cubrid.php => db/xml_query/cubrid/CubridSelectTest.php} (92%) rename test-phpUnit/{UpdateXmlTest_Cubrid.php => db/xml_query/cubrid/CubridUpdateTest.php} (88%) create mode 100644 test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php rename test-phpUnit/{SelectXmlTest_Mssql.php => db/xml_query/mssql/MssqlSelectTest.php} (94%) create mode 100644 test-phpUnit/db/xml_query/mssql/config.mssql.inc.php create mode 100644 test-phpUnit/debug.php diff --git a/test-phpUnit/QueryTester.class.php b/test-phpUnit/QueryTester.class.php index 0f558b40e..65227083f 100644 --- a/test-phpUnit/QueryTester.class.php +++ b/test-phpUnit/QueryTester.class.php @@ -16,8 +16,7 @@ $newXmlQueryParser = new XmlQueryParser($db_type); $xml_obj = $newXmlQueryParser->getXmlFileContent($xml_file); - $dbParser = $newXmlQueryParser->getDBParser(); - $parser = new QueryParser($xml_obj->query, $dbParser); + $parser = new QueryParser($xml_obj->query); return $parser->toString(); } diff --git a/test-phpUnit/ExpressionParserTest.php b/test-phpUnit/db/ExpressionParserTest.php similarity index 96% rename from test-phpUnit/ExpressionParserTest.php rename to test-phpUnit/db/ExpressionParserTest.php index ea16176ee..457301643 100644 --- a/test-phpUnit/ExpressionParserTest.php +++ b/test-phpUnit/db/ExpressionParserTest.php @@ -1,5 +1,5 @@ getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); - $output = eval($outputString); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); + $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - //$db = new DBCubrid(); - $db = &DB::getInstance('cubrid'); + $db = &DB::getInstance(); + var_dump($db); $querySql = $db->getDeleteSql($output); // Remove whitespaces, tabs and all @@ -29,15 +30,10 @@ $argsString = '$args->module = "page"; $args->type = "page"; $args->act = "tata";'; - $expected = 'delete from "xe_action_forward" as "action_forward" + $expected = 'delete "action_forward" from "xe_action_forward" as "action_forward" where "module" = \'page\' and "type" = \'page\' and "act" = \'tata\''; $this->_test($xml_file, $argsString, $expected); } - -// $queryTester->test_admin_deleteActionForward(); -// $queryTester->test_module_insertModule(); - - } \ No newline at end of file diff --git a/test-phpUnit/InsertXmlTest_Cubrid.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php similarity index 89% rename from test-phpUnit/InsertXmlTest_Cubrid.php rename to test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php index eba6bb9b3..5b09617f8 100644 --- a/test-phpUnit/InsertXmlTest_Cubrid.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php @@ -1,18 +1,18 @@ getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - //$db = new DBCubrid(); - $db = &DB::getInstance('cubrid'); + $db = &DB::getInstance(); $querySql = $db->getInsertSql($output); // Remove whitespaces, tabs and all @@ -24,6 +24,10 @@ $this->assertEquals($expected, $querySql); } + /** + * Note: this test can fail when comaparing regdate from the $args with + * regdate from the expected string - a few seconds difference + */ function test_module_insertModule(){ $xml_file = _XE_PATH_ . "modules/module/queries/insertModule.xml"; $argsString = ' $args->module_category_srl = 0; @@ -136,7 +140,5 @@ '; $this->_test($xml_file, $argsString, $expected); } -// $queryTester->test_admin_deleteActionForward(); -// $queryTester->test_module_insertModule(); } \ No newline at end of file diff --git a/test-phpUnit/SelectXmlTest_Cubrid.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php similarity index 92% rename from test-phpUnit/SelectXmlTest_Cubrid.php rename to test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index c2b82dd61..bec501905 100644 --- a/test-phpUnit/SelectXmlTest_Cubrid.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -1,11 +1,12 @@ getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); //echo $outputString; $output = eval($outputString); @@ -14,7 +15,7 @@ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { //$db = new DBCubrid(); - $db = &DB::getInstance('cubrid'); + $db = &DB::getInstance(); $querySql = $db->getSelectSql($output); // Remove whitespaces, tabs and all @@ -194,14 +195,6 @@ $this->assertTrue(is_int($output->page)); // $this->assertTrue($output->page == 5); - } - -// $queryTester->test_admin_deleteActionForward(); -// $queryTester->test_module_insertModule(); -// $queryTester->test_module_updateModule(); - - -// $queryTester->test_opage_getOpageList(); - + } } \ No newline at end of file diff --git a/test-phpUnit/UpdateXmlTest_Cubrid.php b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php similarity index 88% rename from test-phpUnit/UpdateXmlTest_Cubrid.php rename to test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php index f6cc7707a..2cee04153 100644 --- a/test-phpUnit/UpdateXmlTest_Cubrid.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php @@ -1,17 +1,17 @@ getNewParserOutputString($xml_file, '"', $argsString, 'cubrid'); - $output = eval($outputString); + $outputString = $tester->getNewParserOutputString($xml_file, '"', $argsString); + $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - //$db = new DBCubrid(); - $db = &DB::getInstance('cubrid'); + $db = &DB::getInstance(); $querySql = $db->getUpdateSql($output); // Remove whitespaces, tabs and all diff --git a/test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php b/test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php new file mode 100644 index 000000000..410ae8dcd --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php @@ -0,0 +1,8 @@ +db_type = 'cubrid'; + $db_info->db_table_prefix = 'xe'; + + $oContext->setDbInfo($db_info); +?> \ No newline at end of file diff --git a/test-phpUnit/SelectXmlTest_Mssql.php b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php similarity index 94% rename from test-phpUnit/SelectXmlTest_Mssql.php rename to test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php index b0274342a..cba14e7a1 100644 --- a/test-phpUnit/SelectXmlTest_Mssql.php +++ b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php @@ -1,18 +1,19 @@ getNewParserOutputString($xml_file, '[', $argsString, 'mssql'); + $outputString = $tester->getNewParserOutputString($xml_file, '[', $argsString); //echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { - $db = &DB::getInstance('mssql'); + $db = &DB::getInstance(); $querySql = $db->getSelectSql($output); $queryArguments = $output->getArguments(); diff --git a/test-phpUnit/db/xml_query/mssql/config.mssql.inc.php b/test-phpUnit/db/xml_query/mssql/config.mssql.inc.php new file mode 100644 index 000000000..01040c220 --- /dev/null +++ b/test-phpUnit/db/xml_query/mssql/config.mssql.inc.php @@ -0,0 +1,8 @@ +db_type = 'mssql'; + $db_info->db_table_prefix = 'xe'; + + $oContext->setDbInfo($db_info); +?> \ No newline at end of file diff --git a/test-phpUnit/debug.php b/test-phpUnit/debug.php new file mode 100644 index 000000000..39208fd6e --- /dev/null +++ b/test-phpUnit/debug.php @@ -0,0 +1,11 @@ +getParser(); + $dbParser = new DBParser('[', ']'); + $parser = new QueryParser($xml_obj->query, $dbParser); + $query_file = $parser->toString(); + var_dump($parser->toString()); + +?> \ No newline at end of file From 4973c78fbcbe380c0b863956d5ca78ddf77d39ab Mon Sep 17 00:00:00 2001 From: ucorina Date: Wed, 29 Jun 2011 13:04:39 +0000 Subject: [PATCH 49/82] Removed a var_dump statement. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8546 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/tags/query/QueryTag.class.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/classes/xml/xmlquery/tags/query/QueryTag.class.php b/classes/xml/xmlquery/tags/query/QueryTag.class.php index 59b94c1df..5a840800e 100644 --- a/classes/xml/xmlquery/tags/query/QueryTag.class.php +++ b/classes/xml/xmlquery/tags/query/QueryTag.class.php @@ -94,9 +94,6 @@ class QueryTag { function getBuff(){ $buff = ''; - echo 'start ---'; - var_dump($this); - echo 'end ---'; //echo 'Luam un query care e '.$this->isSubQuery; if($this->isSubQuery){ $buff = 'new Subquery('; From 01d0925dd523500a788c56bdbcba2411587e2d9e Mon Sep 17 00:00:00 2001 From: ucorina Date: Wed, 29 Jun 2011 15:36:09 +0000 Subject: [PATCH 50/82] merged 1.5.0 branch into 1.5.0-DB git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8547 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- addons/blogapi/blogapi.addon.php | 4 +- .../member_extra_info.lib.php | 2 +- .../point_level_icon/point_level_icon.lib.php | 7 +- config/config.inc.php | 1 + config/func.inc.php | 25 + layouts/user_layout/conf/info.xml | 19 + layouts/user_layout/layout.html | 47 + layouts/user_layout/user_layout.css | 15 + layouts/user_layout/user_layout.js | 5 + modules/counter/tpl/index.html | 4 +- modules/file/conf/module.xml | 6 +- modules/file/file.admin.controller.php | 29 +- modules/file/file.admin.view.php | 9 +- modules/file/ruleset/deleteChecked.xml | 8 + modules/file/ruleset/fileModuleConfig.xml | 12 + modules/file/ruleset/insertConfig.xml | 11 + modules/file/tpl/file_config.html | 6 +- modules/file/tpl/file_list.html | 9 +- modules/file/tpl/file_module_config.html | 7 +- modules/message/message.view.php | 3 +- modules/message/tpl/config.html | 6 +- .../syndication/queries/getDocumentList.xml | 2 +- modules/syndication/tpl/js/syndication.js | 8 +- modules/trash/conf/info.xml | 20 + modules/trash/conf/module.xml | 15 + modules/trash/lang/ko.lang.php | 23 + modules/trash/model/TrashVO.php | 103 ++ modules/trash/queries/deleteTrash.xml | 9 + modules/trash/queries/getTrash.xml | 11 + modules/trash/queries/getTrashList.xml | 21 + modules/trash/queries/insertTrash.xml | 15 + modules/trash/schemas/trash.xml | 10 + modules/trash/tpl/filter/emptyTrash.xml | 12 + modules/trash/tpl/header.html | 2 + modules/trash/tpl/js/trash_admin.js | 33 + modules/trash/tpl/trash_list.html | 69 + modules/trash/trash.admin.controller.php | 140 ++ modules/trash/trash.admin.view.php | 36 + modules/trash/trash.class.php | 39 + modules/trash/trash.controller.php | 12 + modules/trash/trash.model.php | 58 + modules/trash/trash.view.php | 16 + tests/classes/context/Context.test.php | 7 - tests/classes/validator/ValidatorTest.php | 117 ++ tests/classes/validator/insertDocument.xml | 14 + tests/classes/validator/login.xml | 7 + tests/index.php | 23 - tests/modules/module/module.test.php | 19 - tests/modules/module/opage.test.php | 63 - .../HELP_MY_TESTS_DONT_WORK_ANYMORE | 348 ---- tests/simpletest/LICENSE | 502 ----- tests/simpletest/README | 108 -- tests/simpletest/VERSION | 1 - tests/simpletest/authentication.php | 238 --- tests/simpletest/autorun.php | 87 - tests/simpletest/browser.php | 1098 ----------- tests/simpletest/collector.php | 122 -- tests/simpletest/compatibility.php | 173 -- tests/simpletest/cookies.php | 380 ---- tests/simpletest/default_reporter.php | 133 -- tests/simpletest/detached.php | 96 - tests/simpletest/dumper.php | 360 ---- tests/simpletest/eclipse.php | 307 ---- tests/simpletest/encoding.php | 552 ------ tests/simpletest/errors.php | 288 --- tests/simpletest/exceptions.php | 198 -- tests/simpletest/expectation.php | 895 --------- .../simpletest/extensions/pear_test_case.php | 198 -- .../extensions/phpunit_test_case.php | 96 - tests/simpletest/extensions/testdox.php | 42 - tests/simpletest/extensions/testdox/test.php | 108 -- tests/simpletest/form.php | 355 ---- tests/simpletest/frames.php | 596 ------ tests/simpletest/http.php | 624 ------- tests/simpletest/invoker.php | 139 -- tests/simpletest/mock_objects.php | 1581 ---------------- tests/simpletest/page.php | 983 ---------- tests/simpletest/parser.php | 764 -------- tests/simpletest/reflection_php4.php | 136 -- tests/simpletest/reflection_php5.php | 380 ---- tests/simpletest/remote.php | 117 -- tests/simpletest/reporter.php | 447 ----- tests/simpletest/scorer.php | 863 --------- tests/simpletest/selector.php | 137 -- tests/simpletest/shell_tester.php | 333 ---- tests/simpletest/simpletest.php | 478 ----- tests/simpletest/socket.php | 216 --- tests/simpletest/tag.php | 1418 -------------- tests/simpletest/test/acceptance_test.php | 1633 ----------------- tests/simpletest/test/adapter_test.php | 77 - tests/simpletest/test/all_tests.php | 13 - tests/simpletest/test/authentication_test.php | 145 -- tests/simpletest/test/autorun_test.php | 13 - tests/simpletest/test/bad_test_suite.php | 10 - tests/simpletest/test/browser_test.php | 779 -------- tests/simpletest/test/collector_test.php | 51 - tests/simpletest/test/command_line_test.php | 40 - tests/simpletest/test/compatibility_test.php | 97 - tests/simpletest/test/cookies_test.php | 227 --- tests/simpletest/test/detached_test.php | 15 - tests/simpletest/test/dumper_test.php | 88 - tests/simpletest/test/eclipse_test.php | 32 - tests/simpletest/test/encoding_test.php | 213 --- tests/simpletest/test/errors_test.php | 300 --- tests/simpletest/test/exceptions_test.php | 153 -- tests/simpletest/test/expectation_test.php | 245 --- tests/simpletest/test/form_test.php | 323 ---- tests/simpletest/test/frames_test.php | 549 ------ tests/simpletest/test/http_test.php | 427 ----- tests/simpletest/test/interfaces_test.php | 137 -- tests/simpletest/test/live_test.php | 47 - tests/simpletest/test/mock_objects_test.php | 994 ---------- tests/simpletest/test/page_test.php | 903 --------- tests/simpletest/test/parse_error_test.php | 9 - tests/simpletest/test/parser_test.php | 551 ------ .../simpletest/test/reflection_php4_test.php | 61 - .../simpletest/test/reflection_php5_test.php | 271 --- tests/simpletest/test/remote_test.php | 20 - tests/simpletest/test/shell_test.php | 38 - tests/simpletest/test/shell_tester_test.php | 42 - tests/simpletest/test/simpletest_test.php | 58 - tests/simpletest/test/socket_test.php | 25 - .../test/support/collector/collectable.1 | 0 .../test/support/collector/collectable.2 | 0 .../test/support/empty_test_file.php | 3 - tests/simpletest/test/support/latin1_sample | 1 - .../simpletest/test/support/spl_examples.php | 15 - .../support/supplementary_upload_sample.txt | 1 - tests/simpletest/test/support/test1.php | 7 - .../simpletest/test/support/upload_sample.txt | 1 - tests/simpletest/test/tag_test.php | 554 ------ .../simpletest/test/test_with_parse_error.php | 8 - tests/simpletest/test/unit_tester_test.php | 55 - tests/simpletest/test/unit_tests.php | 55 - tests/simpletest/test/url_test.php | 443 ----- tests/simpletest/test/user_agent_test.php | 358 ---- tests/simpletest/test/visual_test.php | 495 ----- tests/simpletest/test/web_tester_test.php | 156 -- tests/simpletest/test/xml_test.php | 187 -- tests/simpletest/test_case.php | 708 ------- tests/simpletest/unit_tester.php | 420 ----- tests/simpletest/url.php | 528 ------ tests/simpletest/user_agent.php | 332 ---- tests/simpletest/web_tester.php | 1541 ---------------- tests/simpletest/xml.php | 647 ------- 145 files changed, 990 insertions(+), 31147 deletions(-) create mode 100644 layouts/user_layout/conf/info.xml create mode 100644 layouts/user_layout/layout.html create mode 100644 layouts/user_layout/user_layout.css create mode 100644 layouts/user_layout/user_layout.js create mode 100644 modules/file/ruleset/deleteChecked.xml create mode 100644 modules/file/ruleset/fileModuleConfig.xml create mode 100644 modules/file/ruleset/insertConfig.xml create mode 100644 modules/trash/conf/info.xml create mode 100644 modules/trash/conf/module.xml create mode 100644 modules/trash/lang/ko.lang.php create mode 100644 modules/trash/model/TrashVO.php create mode 100644 modules/trash/queries/deleteTrash.xml create mode 100644 modules/trash/queries/getTrash.xml create mode 100644 modules/trash/queries/getTrashList.xml create mode 100644 modules/trash/queries/insertTrash.xml create mode 100644 modules/trash/schemas/trash.xml create mode 100644 modules/trash/tpl/filter/emptyTrash.xml create mode 100644 modules/trash/tpl/header.html create mode 100644 modules/trash/tpl/js/trash_admin.js create mode 100644 modules/trash/tpl/trash_list.html create mode 100644 modules/trash/trash.admin.controller.php create mode 100644 modules/trash/trash.admin.view.php create mode 100644 modules/trash/trash.class.php create mode 100644 modules/trash/trash.controller.php create mode 100644 modules/trash/trash.model.php create mode 100644 modules/trash/trash.view.php delete mode 100644 tests/classes/context/Context.test.php create mode 100644 tests/classes/validator/ValidatorTest.php create mode 100644 tests/classes/validator/insertDocument.xml create mode 100644 tests/classes/validator/login.xml delete mode 100644 tests/index.php delete mode 100644 tests/modules/module/module.test.php delete mode 100644 tests/modules/module/opage.test.php delete mode 100644 tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE delete mode 100644 tests/simpletest/LICENSE delete mode 100644 tests/simpletest/README delete mode 100644 tests/simpletest/VERSION delete mode 100644 tests/simpletest/authentication.php delete mode 100644 tests/simpletest/autorun.php delete mode 100644 tests/simpletest/browser.php delete mode 100644 tests/simpletest/collector.php delete mode 100644 tests/simpletest/compatibility.php delete mode 100644 tests/simpletest/cookies.php delete mode 100644 tests/simpletest/default_reporter.php delete mode 100644 tests/simpletest/detached.php delete mode 100644 tests/simpletest/dumper.php delete mode 100644 tests/simpletest/eclipse.php delete mode 100644 tests/simpletest/encoding.php delete mode 100644 tests/simpletest/errors.php delete mode 100644 tests/simpletest/exceptions.php delete mode 100644 tests/simpletest/expectation.php delete mode 100644 tests/simpletest/extensions/pear_test_case.php delete mode 100644 tests/simpletest/extensions/phpunit_test_case.php delete mode 100644 tests/simpletest/extensions/testdox.php delete mode 100644 tests/simpletest/extensions/testdox/test.php delete mode 100644 tests/simpletest/form.php delete mode 100644 tests/simpletest/frames.php delete mode 100644 tests/simpletest/http.php delete mode 100644 tests/simpletest/invoker.php delete mode 100644 tests/simpletest/mock_objects.php delete mode 100644 tests/simpletest/page.php delete mode 100644 tests/simpletest/parser.php delete mode 100644 tests/simpletest/reflection_php4.php delete mode 100644 tests/simpletest/reflection_php5.php delete mode 100644 tests/simpletest/remote.php delete mode 100644 tests/simpletest/reporter.php delete mode 100644 tests/simpletest/scorer.php delete mode 100644 tests/simpletest/selector.php delete mode 100644 tests/simpletest/shell_tester.php delete mode 100644 tests/simpletest/simpletest.php delete mode 100644 tests/simpletest/socket.php delete mode 100644 tests/simpletest/tag.php delete mode 100644 tests/simpletest/test/acceptance_test.php delete mode 100644 tests/simpletest/test/adapter_test.php delete mode 100644 tests/simpletest/test/all_tests.php delete mode 100644 tests/simpletest/test/authentication_test.php delete mode 100644 tests/simpletest/test/autorun_test.php delete mode 100644 tests/simpletest/test/bad_test_suite.php delete mode 100644 tests/simpletest/test/browser_test.php delete mode 100644 tests/simpletest/test/collector_test.php delete mode 100644 tests/simpletest/test/command_line_test.php delete mode 100644 tests/simpletest/test/compatibility_test.php delete mode 100644 tests/simpletest/test/cookies_test.php delete mode 100644 tests/simpletest/test/detached_test.php delete mode 100644 tests/simpletest/test/dumper_test.php delete mode 100644 tests/simpletest/test/eclipse_test.php delete mode 100644 tests/simpletest/test/encoding_test.php delete mode 100644 tests/simpletest/test/errors_test.php delete mode 100644 tests/simpletest/test/exceptions_test.php delete mode 100644 tests/simpletest/test/expectation_test.php delete mode 100644 tests/simpletest/test/form_test.php delete mode 100644 tests/simpletest/test/frames_test.php delete mode 100644 tests/simpletest/test/http_test.php delete mode 100644 tests/simpletest/test/interfaces_test.php delete mode 100644 tests/simpletest/test/live_test.php delete mode 100644 tests/simpletest/test/mock_objects_test.php delete mode 100644 tests/simpletest/test/page_test.php delete mode 100644 tests/simpletest/test/parse_error_test.php delete mode 100644 tests/simpletest/test/parser_test.php delete mode 100644 tests/simpletest/test/reflection_php4_test.php delete mode 100644 tests/simpletest/test/reflection_php5_test.php delete mode 100644 tests/simpletest/test/remote_test.php delete mode 100644 tests/simpletest/test/shell_test.php delete mode 100644 tests/simpletest/test/shell_tester_test.php delete mode 100644 tests/simpletest/test/simpletest_test.php delete mode 100644 tests/simpletest/test/socket_test.php delete mode 100644 tests/simpletest/test/support/collector/collectable.1 delete mode 100644 tests/simpletest/test/support/collector/collectable.2 delete mode 100644 tests/simpletest/test/support/empty_test_file.php delete mode 100644 tests/simpletest/test/support/latin1_sample delete mode 100644 tests/simpletest/test/support/spl_examples.php delete mode 100644 tests/simpletest/test/support/supplementary_upload_sample.txt delete mode 100644 tests/simpletest/test/support/test1.php delete mode 100644 tests/simpletest/test/support/upload_sample.txt delete mode 100644 tests/simpletest/test/tag_test.php delete mode 100644 tests/simpletest/test/test_with_parse_error.php delete mode 100644 tests/simpletest/test/unit_tester_test.php delete mode 100644 tests/simpletest/test/unit_tests.php delete mode 100644 tests/simpletest/test/url_test.php delete mode 100644 tests/simpletest/test/user_agent_test.php delete mode 100644 tests/simpletest/test/visual_test.php delete mode 100644 tests/simpletest/test/web_tester_test.php delete mode 100644 tests/simpletest/test/xml_test.php delete mode 100644 tests/simpletest/test_case.php delete mode 100644 tests/simpletest/unit_tester.php delete mode 100644 tests/simpletest/url.php delete mode 100644 tests/simpletest/user_agent.php delete mode 100644 tests/simpletest/web_tester.php delete mode 100644 tests/simpletest/xml.php diff --git a/addons/blogapi/blogapi.addon.php b/addons/blogapi/blogapi.addon.php index c17ecb9ed..5dfd4c6a2 100644 --- a/addons/blogapi/blogapi.addon.php +++ b/addons/blogapi/blogapi.addon.php @@ -243,7 +243,7 @@ $obj->content = str_replace($uploaded_target_path,sprintf('/files/attach/images/%s/%s%s', $this->module_srl, getNumberingPath($document_srl,3), $filename), $obj->content); $oDocumentController = &getController('document'); - $obj->allow_comment = 'Y'; + $obj->commentStatus = 'ALLOW'; $obj->allow_trackback = 'Y'; $output = $oDocumentController->insertDocument($obj); @@ -403,7 +403,7 @@ $post->publish = 1; $post->userid = $oDocument->get('user_id'); $post->mt_allow_pings = 0; - $post->mt_allow_comments = $oDocument->allowComment()=='Y'?1:0; + $post->mt_allow_comments = $oDocument->allowComment()?1:0; $posts[] = $post; } $content = getXmlRpcResponse($posts); diff --git a/addons/member_extra_info/member_extra_info.lib.php b/addons/member_extra_info/member_extra_info.lib.php index 3cb808e31..fe2edfaf5 100644 --- a/addons/member_extra_info/member_extra_info.lib.php +++ b/addons/member_extra_info/member_extra_info.lib.php @@ -32,7 +32,7 @@ if($image_name_file) $nick_name = sprintf('id: %s', Context::getRequestUri(),$image_name_file, strip_tags($nick_name), strip_tags($nick_name)); if($image_mark_file) $nick_name = sprintf('id: %s%s', Context::getRequestUri(),$image_mark_file, strip_tags($nick_name), strip_tags($nick_name), $nick_name); - if($group_image) $nick_name = sprintf('%s', $group_image->src, $nick_name); + if($group_image) $nick_name = sprintf('%s%s', $group_image->src, $group_image->title, $group_image->description, $nick_name); $orig_text = preg_replace('/'.preg_quote($matches[5],'/').'<\/'.$matches[6].'>$/', '', $matches[0]); diff --git a/addons/point_level_icon/point_level_icon.lib.php b/addons/point_level_icon/point_level_icon.lib.php index 014e31e23..a81829bc4 100644 --- a/addons/point_level_icon/point_level_icon.lib.php +++ b/addons/point_level_icon/point_level_icon.lib.php @@ -6,6 +6,12 @@ $member_srl = $matches[3]; if($member_srl<1) return $matches[0]; + $orig_text = preg_replace('/'.preg_quote($matches[5],'/').'<\/'.$matches[6].'>$/', '', $matches[0]); + + // Check Group Image Mark + $oMemberModel = &getModel('member'); + if($oMemberModel->getGroupImageMark($member_srl)) return $orig_text.$matches[5].''; + if(!isset($GLOBALS['_pointLevelIcon'][$member_srl])) { // Get point configuration if(!$GLOBALS['_pointConfig']) { @@ -40,7 +46,6 @@ } $text = $GLOBALS['_pointLevelIcon'][$member_srl]; - $orig_text = preg_replace('/'.preg_quote($matches[5],'/').'<\/'.$matches[6].'>$/', '', $matches[0]); return $orig_text.$text.$matches[5].''; } ?> diff --git a/config/config.inc.php b/config/config.inc.php index 357e52bfb..858a8769a 100644 --- a/config/config.inc.php +++ b/config/config.inc.php @@ -158,6 +158,7 @@ require(_XE_PATH_.'classes/mail/Mail.class.php'); require(_XE_PATH_.'classes/page/PageHandler.class.php'); require(_XE_PATH_.'classes/mobile/Mobile.class.php'); + require(_XE_PATH_.'classes/validator/Validator.class.php'); if(__DEBUG__) $GLOBALS['__elapsed_class_load__'] = getMicroTime() - __ClassLoadStartTime__; } ?> diff --git a/config/func.inc.php b/config/func.inc.php index 9b3f5fa03..8e606228b 100644 --- a/config/func.inc.php +++ b/config/func.inc.php @@ -820,6 +820,14 @@ return $url; } + /** + * return the requested script path + **/ + function getRequestUriByServerEnviroment() + { + return $_SERVER['REQUEST_URI']; + } + /** * php unescape function of javascript's escape * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8). @@ -972,4 +980,21 @@ } } + function alertScript($msg) + { + if(!$msg) return; + echo ''; + } + + function closePopupScript() + { + echo ''; + } + + function reload($isOpener = false) + { + $reloadScript = $isOpener ? 'window.opener.location.reload()' : 'document.location.reload()'; + + echo ''; + } ?> diff --git a/layouts/user_layout/conf/info.xml b/layouts/user_layout/conf/info.xml new file mode 100644 index 000000000..109143907 --- /dev/null +++ b/layouts/user_layout/conf/info.xml @@ -0,0 +1,19 @@ + + + ì‚¬ìš©ìž ì •ì˜ ë ˆì´ì•„웃 + User defined layout + ユーザー定義ã®ãƒ¬ã‚¤ã‚¢ã‚¦ãƒˆ + ì‚¬ìš©ìž ì •ì˜ ë ˆì´ì•„ì›ƒì— ê´€í•œ 설명 입니다. + Description for user defined layout. + ユーザー定義ã®ãƒ¬ã‚¤ã‚¢ã‚¦ãƒˆã«ã¤ã„ã¦ã®èª¬æ˜Žã§ã™ã€‚ + 1.0 + 2010-12-24 + + User Name + + + + 메뉴 + + + diff --git a/layouts/user_layout/layout.html b/layouts/user_layout/layout.html new file mode 100644 index 000000000..5a3554723 --- /dev/null +++ b/layouts/user_layout/layout.html @@ -0,0 +1,47 @@ + +
+
+

Site Logo

+ +
+
+ .gnb + +
+
+
+
+
+ +
+ .lnb +

{$val1['link']}

+ +
+
+
.content{$content}
+
+
+ +
diff --git a/layouts/user_layout/user_layout.css b/layouts/user_layout/user_layout.css new file mode 100644 index 000000000..23e516620 --- /dev/null +++ b/layouts/user_layout/user_layout.css @@ -0,0 +1,15 @@ +@charset "utf-8"; +/* Layout */ +hr{ display:none;} +form, fieldset{ border:0; margin:0; padding:0;} +.user_layout{ width:960px; margin:0 auto;} +.header{ zoom:1; background:#ddd;} +.header:after{ content:""; display:block; clear:both;} +.header .search{ float:right;} +.gnb{ float:left;} +.body{ margin:20px 0; zoom:1; background:#eee;} +.body:after{ content:""; display:block; clear:both;} +.lnb{ float:left; width:200px; background:#ddd;} +.account{} +.content{ float:right; width:740px; background:#ddd;} +.footer{ background:#ddd;} \ No newline at end of file diff --git a/layouts/user_layout/user_layout.js b/layouts/user_layout/user_layout.js new file mode 100644 index 000000000..19a0de06c --- /dev/null +++ b/layouts/user_layout/user_layout.js @@ -0,0 +1,5 @@ +// diff --git a/modules/counter/tpl/index.html b/modules/counter/tpl/index.html index 69488aa0f..50dffb227 100644 --- a/modules/counter/tpl/index.html +++ b/modules/counter/tpl/index.html @@ -6,7 +6,7 @@ @@ -16,7 +16,7 @@
-
+ diff --git a/modules/file/conf/module.xml b/modules/file/conf/module.xml index 5f74ecf78..524fea82e 100644 --- a/modules/file/conf/module.xml +++ b/modules/file/conf/module.xml @@ -11,8 +11,8 @@ - - - + + + diff --git a/modules/file/file.admin.controller.php b/modules/file/file.admin.controller.php index a98a2bb99..470af17a9 100644 --- a/modules/file/file.admin.controller.php +++ b/modules/file/file.admin.controller.php @@ -53,7 +53,8 @@ // An error appears if no document is selected $cart = Context::get('cart'); if(!$cart) return $this->stop('msg_cart_is_null'); - $file_srl_list= explode('|@|', $cart); + if(!is_array($cart)) $file_srl_list= explode('|@|', $cart); + else $file_srl_list = $cart; $file_count = count($file_srl_list); if(!$file_count) return $this->stop('msg_cart_is_null'); @@ -67,6 +68,11 @@ } $this->setMessage( sprintf(Context::getLang('msg_checked_file_is_deleted'), $file_count) ); + if(!in_array(Context::getRequestMethod(),array('XMLRPC','JSON'))) { + $returnUrl = Context::get('success_return_url') ? Context::get('success_return_url') : getNotEncodedUrl('', 'module', 'admin', 'act', 'dispFileAdminList'); + header('location:'.$returnUrl); + return; + } } /** @@ -76,13 +82,18 @@ // Get configurations (using module model object) $config->allowed_filesize = Context::get('allowed_filesize'); $config->allowed_attach_size = Context::get('allowed_attach_size'); - $config->allowed_filetypes = Context::get('allowed_filetypes'); + $config->allowed_filetypes = str_replace(' ', '', Context::get('allowed_filetypes')); $config->allow_outlink = Context::get('allow_outlink'); $config->allow_outlink_format = Context::get('allow_outlink_format'); $config->allow_outlink_site = Context::get('allow_outlink_site'); // Create module Controller object $oModuleController = &getController('module'); $output = $oModuleController->insertModuleConfig('file',$config); + if($output->toBool() && !in_array(Context::getRequestMethod(),array('XMLRPC','JSON'))) { + $returnUrl = Context::get('success_return_url') ? Context::get('success_return_url') : getNotEncodedUrl('', 'module', 'admin', 'act', 'dispFileAdminConfig'); + header('location:'.$returnUrl); + return; + } return $output; } @@ -96,16 +107,17 @@ if(preg_match('/^([0-9,]+)$/',$module_srl)) $module_srl = explode(',',$module_srl); else $module_srl = array($module_srl); - $download_grant = trim(Context::get('download_grant')); + $download_grant = Context::get('download_grant'); $file_config->allow_outlink = Context::get('allow_outlink'); $file_config->allow_outlink_format = Context::get('allow_outlink_format'); $file_config->allow_outlink_site = Context::get('allow_outlink_site'); $file_config->allowed_filesize = Context::get('allowed_filesize'); $file_config->allowed_attach_size = Context::get('allowed_attach_size'); - $file_config->allowed_filetypes = Context::get('allowed_filetypes'); - if($download_grant) $file_config->download_grant = explode('|@|',$download_grant); - else $file_config->download_grant = array(); + $file_config->allowed_filetypes = str_replace(' ', '', Context::get('allowed_filetypes')); + + if(!is_array($download_grant)) $file_config->download_grant = explode('|@|',$download_grant); + else $file_config->download_grant = $download_grant; //관리ìžê°€ 허용한 첨부파ì¼ì˜ 사ì´ì¦ˆê°€ php.iniì˜ ê°’ë³´ë‹¤ í°ì§€ 확ì¸í•˜ê¸° - by ovclas $userFileAllowSize = $this->_changeBytes($file_config->allowed_filesize.'M'); @@ -126,6 +138,11 @@ $this->setError(-1); $this->setMessage('success_updated'); + if(!in_array(Context::getRequestMethod(),array('XMLRPC','JSON'))) { + $returnUrl = Context::get('success_return_url') ? Context::get('success_return_url') : getNotEncodedUrl('', 'module', 'admin', 'act', 'dispBoardAdminContent'); + header('location:'.$returnUrl); + return; + } } /** diff --git a/modules/file/file.admin.view.php b/modules/file/file.admin.view.php index 7843d7cd5..c65ecbc26 100644 --- a/modules/file/file.admin.view.php +++ b/modules/file/file.admin.view.php @@ -129,9 +129,12 @@ $doc_srls_count = count($doc_srls); if($doc_srls_count) { $document_output = $oDocumentModel->getDocuments($doc_srls); - foreach($document_output as $document) { - $document_list[$document->document_srl] = $document; - } + if(is_array($document_output)) + { + foreach($document_output as $document) { + $document_list[$document->document_srl] = $document; + } + } } // Module List $mod_srls_count = count($mod_srls); diff --git a/modules/file/ruleset/deleteChecked.xml b/modules/file/ruleset/deleteChecked.xml new file mode 100644 index 000000000..28789da2a --- /dev/null +++ b/modules/file/ruleset/deleteChecked.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/modules/file/ruleset/fileModuleConfig.xml b/modules/file/ruleset/fileModuleConfig.xml new file mode 100644 index 000000000..84e40c6c6 --- /dev/null +++ b/modules/file/ruleset/fileModuleConfig.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/modules/file/ruleset/insertConfig.xml b/modules/file/ruleset/insertConfig.xml new file mode 100644 index 000000000..2cf75672f --- /dev/null +++ b/modules/file/ruleset/insertConfig.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/modules/file/tpl/file_config.html b/modules/file/tpl/file_config.html index 59ec81090..0b6e14d59 100644 --- a/modules/file/tpl/file_config.html +++ b/modules/file/tpl/file_config.html @@ -1,7 +1,9 @@ - +

{$XE_VALIDATOR_ERROR}

+ + @@ -55,4 +57,4 @@
{$lang->allow_outlink}
- + diff --git a/modules/file/tpl/file_list.html b/modules/file/tpl/file_list.html index e11061e38..b643ac7a7 100644 --- a/modules/file/tpl/file_list.html +++ b/modules/file/tpl/file_list.html @@ -1,10 +1,10 @@ -
-
+

{$XE_VALIDATOR_ERROR}

+ @@ -29,7 +29,8 @@
-
+ + @@ -91,7 +92,7 @@ {$no} - + {htmlspecialchars($val->source_filename)} {FileHandler::filesize($val->file_size)} diff --git a/modules/file/tpl/file_module_config.html b/modules/file/tpl/file_module_config.html index c8c976f39..c74d37ac6 100644 --- a/modules/file/tpl/file_module_config.html +++ b/modules/file/tpl/file_module_config.html @@ -1,5 +1,6 @@ - - + + +

{$lang->file}

@@ -30,7 +31,7 @@
{$lang->enable_download_group}
- group_srl, $file_config->download_grant))-->checked="checked"/> + group_srl, $file_config->download_grant))-->checked="checked"/>   diff --git a/modules/message/message.view.php b/modules/message/message.view.php index 9251c1fb7..d476f4f50 100644 --- a/modules/message/message.view.php +++ b/modules/message/message.view.php @@ -37,8 +37,7 @@ Context::set('system_message', nl2br($this->getMessage())); $this->setTemplatePath($template_path); - $this->setTemplateFile('system_message'); + $this->setTemplateFile('system_message'); } - } ?> diff --git a/modules/message/tpl/config.html b/modules/message/tpl/config.html index 0aed54c96..c19690298 100644 --- a/modules/message/tpl/config.html +++ b/modules/message/tpl/config.html @@ -1,8 +1,8 @@ - -

{$lang->message} {$lang->cmd_management}

- +

{$XE_VALIDATOR_ERROR}

+ +

{$lang->about_skin}

diff --git a/modules/syndication/queries/getDocumentList.xml b/modules/syndication/queries/getDocumentList.xml index 79c2ea8b4..a5916f0a6 100644 --- a/modules/syndication/queries/getDocumentList.xml +++ b/modules/syndication/queries/getDocumentList.xml @@ -16,7 +16,7 @@ - + diff --git a/modules/syndication/tpl/js/syndication.js b/modules/syndication/tpl/js/syndication.js index 7af234ac8..47c202672 100644 --- a/modules/syndication/tpl/js/syndication.js +++ b/modules/syndication/tpl/js/syndication.js @@ -1,5 +1,5 @@ function insertSelectedModules(id, module_srl, mid, browser_title) { - var sel_obj = xGetElementById('_'+id); + var sel_obj = get_by_id('_'+id); for(var i=0;i + + 휴지통 + trash + 문서, 댓글 ë“±ì„ ì™„ì „ížˆ 삭제하지 않고 복구 가능한 ìƒíƒœë¡œ 만들어 관리하는 모듈입니다. + 0.1 + 2011-05-12 + content + + NHN + NHN + NHN + NHN + NHN + NHN + NHN + NHN + NHN + + diff --git a/modules/trash/conf/module.xml b/modules/trash/conf/module.xml new file mode 100644 index 000000000..2b204cee3 --- /dev/null +++ b/modules/trash/conf/module.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/modules/trash/lang/ko.lang.php b/modules/trash/lang/ko.lang.php new file mode 100644 index 000000000..3f0866fd0 --- /dev/null +++ b/modules/trash/lang/ko.lang.php @@ -0,0 +1,23 @@ +cmd_trash = '휴지통'; + $lang->cmd_restore = 'ë³µì›'; + $lang->cmd_restore_all = 'ëª¨ë‘ ë³µì›'; + $lang->in_trash = '휴지통'; + $lang->trash_nick_name = 'ì‚­ì œìž ë‹‰ë„¤ìž„'; + $lang->trash_date = 'ì‚­ì œ ë‚ ì§œ'; + $lang->trash_description = '설명'; + $lang->trash_type = 'ì›ë³¸ 종류'; + $lang->success_trashed = '휴지통으로 ì´ë™ë˜ì—ˆìŠµë‹ˆë‹¤.'; + $lang->empty_trash_selected = 'ì„ íƒ ë¹„ìš°ê¸°'; + $lang->empty_trash_all = '휴지통 비우기'; + $lang->confirm_restore = 'ë³µì›í•˜ì‹œê² ìŠµë‹ˆê¹Œ?'; + $lang->success_empty = '성공ì ìœ¼ë¡œ 비웠습니다.'; + $lang->fail_empty = '휴지통 ë¹„ìš°ê¸°ì— ì‹¤íŒ¨í•˜ì˜€ìŠµë‹ˆë‹¤.'; + $lang->success_restore = '성공ì ìœ¼ë¡œ ë³µì›í•˜ì˜€ìŠµë‹ˆë‹¤.'; + $lang->fail_restore = 'ë³µì›ì— 실패하였습니다.'; +?> diff --git a/modules/trash/model/TrashVO.php b/modules/trash/model/TrashVO.php new file mode 100644 index 000000000..9061d8b9e --- /dev/null +++ b/modules/trash/model/TrashVO.php @@ -0,0 +1,103 @@ +trashSrl; + } + function setTrashSrl($trashSrl) + { + $this->trashSrl = $trashSrl; + } + function getTitle() + { + if(empty($this->title)) return $lang->untitle; + return $this->title; + } + function setTitle($title) + { + $this->title = $title; + } + function getOriginModule() + { + if(empty($this->originModule)) return 'document'; + return $this->originModule; + } + function setOriginModule($originModule) + { + $this->originModule = $originModule; + } + function getSerializedObject() + { + return $this->serializedObject; + } + function setSerializedObject($serializedObject) + { + $this->serializedObject = $serializedObject; + } + function getDescription() + { + return $this->description; + } + function setDescription($description) + { + $this->description = $description; + } + function getIpaddress() + { + return $this->ipaddress; + } + function setIpaddress($ipaddress) + { + $this->ipaddress = $ipaddress; + } + function getRemoverSrl() + { + return $this->removerSrl; + } + function setRemoverSrl($removerSrl) + { + $this->removerSrl = $removerSrl; + } + function getUserId() + { + return $this->userId; + } + function setUserId($userId) + { + $this->userId = $userId; + } + function getNickName() + { + return $this->nickName; + } + function setNickName($nickName) + { + $this->nickName = $nickName; + } + function getRegdate() + { + if(empty($this->regdate)) return date('YmdHis'); + + return $this->regdate; + } + function setRegdate($regdate) + { + $this->regdate = $regdate; + } +} + +/* End of file Trash.php */ +/* Location: ./modules/trash/model/Trash.php */ diff --git a/modules/trash/queries/deleteTrash.xml b/modules/trash/queries/deleteTrash.xml new file mode 100644 index 000000000..7374de69c --- /dev/null +++ b/modules/trash/queries/deleteTrash.xml @@ -0,0 +1,9 @@ + + +
+ + + + + + diff --git a/modules/trash/queries/getTrash.xml b/modules/trash/queries/getTrash.xml new file mode 100644 index 000000000..0acccabc9 --- /dev/null +++ b/modules/trash/queries/getTrash.xml @@ -0,0 +1,11 @@ + + +
+ + + + + + + + diff --git a/modules/trash/queries/getTrashList.xml b/modules/trash/queries/getTrashList.xml new file mode 100644 index 000000000..78bea0734 --- /dev/null +++ b/modules/trash/queries/getTrashList.xml @@ -0,0 +1,21 @@ + + +
+
+ + + + + + + + + + + + + + + + + diff --git a/modules/trash/queries/insertTrash.xml b/modules/trash/queries/insertTrash.xml new file mode 100644 index 000000000..c8fadb3d6 --- /dev/null +++ b/modules/trash/queries/insertTrash.xml @@ -0,0 +1,15 @@ + + +
+ + + + + + + + + + + + diff --git a/modules/trash/schemas/trash.xml b/modules/trash/schemas/trash.xml new file mode 100644 index 000000000..ee69509da --- /dev/null +++ b/modules/trash/schemas/trash.xml @@ -0,0 +1,10 @@ +
+ + + + + + + + +
diff --git a/modules/trash/tpl/filter/emptyTrash.xml b/modules/trash/tpl/filter/emptyTrash.xml new file mode 100644 index 000000000..6976c489f --- /dev/null +++ b/modules/trash/tpl/filter/emptyTrash.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + +
diff --git a/modules/trash/tpl/header.html b/modules/trash/tpl/header.html new file mode 100644 index 000000000..87a81480c --- /dev/null +++ b/modules/trash/tpl/header.html @@ -0,0 +1,2 @@ + +

{$lang->cmd_trash} {$lang->cmd_management}

diff --git a/modules/trash/tpl/js/trash_admin.js b/modules/trash/tpl/js/trash_admin.js new file mode 100644 index 000000000..376b39989 --- /dev/null +++ b/modules/trash/tpl/js/trash_admin.js @@ -0,0 +1,33 @@ +/** + * @file modules/trash/js/trash_admin.js + * @author NHN (developers@xpressengine.com) + * @brief trash ëª¨ë“ˆì˜ ê´€ë¦¬ìžìš© javascript + **/ + + +/* 휴지통 비우기 후 */ +function completeEmptyTrash(ret_obj) { + var error = ret_obj['error']; + var message = ret_obj['message']; + + alert(message); + if(error == '0') window.location.reload(); +} + +function goRestore(trash_srl) +{ + if(confirm(confirm_restore_msg)) + { + var params = {'trash_srl':trash_srl}; + exec_xml('admin', 'procTrashAdminRestore', params, completeRestore); + } +} + +function completeRestore(ret_obj) +{ + var error = ret_obj['error']; + var message = ret_obj['message']; + + alert(message); + if(error == '0') window.location.reload(); +} diff --git a/modules/trash/tpl/trash_list.html b/modules/trash/tpl/trash_list.html new file mode 100644 index 000000000..8225d0fb1 --- /dev/null +++ b/modules/trash/tpl/trash_list.html @@ -0,0 +1,69 @@ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Total {number_format($total_count)}, Page {number_format($page)}/{number_format($total_page)}
{$lang->no}
{$lang->document} ({$lang->trash_type})
{$lang->trash_nick_name}
{$lang->trash_date}
{$lang->ipaddress}
{$lang->trash_description}
{$lang->cmd_restore}
{$no}
+
+ {$oTrashVO->getTitle()} ( + + {$lang->document} + + {$lang->replies} + + {$lang->etc} + + ) + {htmlspecialchars($oTrashVO->getNickName())}{zdate($oTrashVO->getRegdate(), "Y-m-d H:i:s")}{$oTrashVO->getIpaddress()}{$oTrashVO->getDescription()}{$lang->cmd_restore}
+ +
+ + +
+
+ + + diff --git a/modules/trash/trash.admin.controller.php b/modules/trash/trash.admin.controller.php new file mode 100644 index 000000000..5bf9ae510 --- /dev/null +++ b/modules/trash/trash.admin.controller.php @@ -0,0 +1,140 @@ +setTrashSrl(getNextSequence()); + $oTrashVO->setTitle($obj->title); + $oTrashVO->setOriginModule($obj->trashType); + $oTrashVO->setSerializedObject(serialize($obj->originObject)); + $oTrashVO->setDescription($obj->description); + $oTrashVO->setIpaddress($_SERVER['REMOTE_ADDR']); + $oTrashVO->setRemoverSrl($logged_info->member_srl); + $oTrashVO->setRegdate(date('YmdHis')); + + $output = executeQuery('trash.insertTrash', $oTrashVO); + return $output; + } + return new Object(-1, 'msg_not_permitted'); + } + + /** + * @brief empty trash + * @param trashSrls : trash_srl in array + **/ + function procTrashAdminEmptyTrash() + { + global $lang; + $isAll = Context::get('is_all'); + $trashSrls = explode('|@|', Context::get('trash_srls')); + + $oTrashModel = &getModel('trash'); + if($isAll == 'true') + { + $trashSrls = array(); + + //module relation data delete... + $output = $oTrashModel->getTrashList($args); + if(!$output->toBool()) return new Object(-1, $output->message); + + if(is_array($output->data)) + { + foreach($output->data AS $key=>$oTrashVO) + { + //class file check + $classPath = ModuleHandler::getModulePath($oTrashVO->getOriginModule()); + if(!is_dir(FileHandler::getRealPath($classPath))) return new Object(-1, 'not exist restore module directory'); + + $classFile = sprintf('%s%s.admin.controller.php', $classPath, $oTrashVO->getOriginModule()); + $classFile = FileHandler::getRealPath($classFile); + if(!file_exists($classFile)) return new Object(-1, 'not exist restore module class file'); + + $oAdminController = &getAdminController($oTrashVO->getOriginModule()); + if(!method_exists($oAdminController, 'emptyTrash')) return new Object(-1, 'not exist restore method in module class file'); + + $output = $oAdminController->emptyTrash($oTrashVO->getSerializedObject()); + } + } + } + + if(!$this->_emptyTrash($trashSrls)) + return new Object(-1, $lang->fail_empty); + + return new Object(0, $lang->success_empty); + } + + function procTrashAdminRestore() + { + global $lang; + $trashSrl = Context::get('trash_srl'); + + $oTrashModel = &getModel('trash'); + $output = $oTrashModel->getTrash($trashSrl); + if(!$output->toBool()) return new Object(-1, $output->message); + + //class file check + $classPath = ModuleHandler::getModulePath($output->data->getOriginModule()); + if(!is_dir(FileHandler::getRealPath($classPath))) return new Object(-1, 'not exist restore module directory'); + + $classFile = sprintf('%s%s.admin.controller.php', $classPath, $output->data->getOriginModule()); + $classFile = FileHandler::getRealPath($classFile); + if(!file_exists($classFile)) return new Object(-1, 'not exist restore module class file'); + + $oAdminController = &getAdminController($output->data->getOriginModule()); + if(!method_exists($oAdminController, 'restoreTrash')) return new Object(-1, 'not exist restore method in module class file'); + + // begin transaction + $oDB = &DB::getInstance(); + $oDB->begin(); + + $originObject = unserialize($output->data->getSerializedObject()); + $output = $oAdminController->restoreTrash($originObject); + + if(!$output->toBool()) { + $oDB->rollback(); + return new Object(-1, $output->message); + } + else + { + Context::set('is_all', 'false'); + Context::set('trash_srls', $trashSrl); + $output = $this->procTrashAdminEmptyTrash(); + if(!$output->toBool()) { + $oDB->rollback(); + return new Object(-1, $output->message); + } + } + $oDB->commit(); + return new Object(0, $lang->success_restore); + } + + /** + * @brief empty trash + * @param trashSrls : trash_srl in array + **/ + function _emptyTrash($trashSrls) + { + if(!is_array($trashSrls)) return false; + $args->trashSrls = $trashSrls; + $output = executeQuery('trash.deleteTrash', $args); + if(!$output->toBool()) return false; + + return true; + } +} + +/* End of file trash.controller.php */ +/* Location: ./modules/trash/trash.controller.php */ diff --git a/modules/trash/trash.admin.view.php b/modules/trash/trash.admin.view.php new file mode 100644 index 000000000..2ccc38a85 --- /dev/null +++ b/modules/trash/trash.admin.view.php @@ -0,0 +1,36 @@ +module_path); + $this->setTemplatePath($template_path); + } + + /** + * @brief trash list + **/ + function dispTrashAdminList() { + $oTrashModel = getModel('trash'); + $output = $oTrashModel->getTrashList($args); + + Context::set('trash_list', $output->data); + Context::set('total_count', $output->total_count); + Context::set('total_page', $output->total_page); + Context::set('page', $output->page); + Context::set('page_navigation', $output->page_navigation); + + // 템플릿 íŒŒì¼ ì§€ì • + $this->setTemplateFile('trash_list'); + } +} +?> diff --git a/modules/trash/trash.class.php b/modules/trash/trash.class.php new file mode 100644 index 000000000..067c04079 --- /dev/null +++ b/modules/trash/trash.class.php @@ -0,0 +1,39 @@ + diff --git a/modules/trash/trash.controller.php b/modules/trash/trash.controller.php new file mode 100644 index 000000000..ab78afa50 --- /dev/null +++ b/modules/trash/trash.controller.php @@ -0,0 +1,12 @@ +trashSrl = $trashSrl; + $output = executeQuery('trash.getTrash', $args, $columnList); + + $this->_setTrashObject(&$oTrashVO, $output->data); + $output->data = $oTrashVO; + + return $output; + } + + /** + * @brief get trash object list + **/ + function getTrashList($args, $columnList = array()) + { + $output = executeQueryArray('trash.getTrashList', $args, $columnList); + + if(is_array($output->data)) + { + foreach($output->data AS $key=>$value) + { + $oTrashVO = new TrashVO(); + $this->_setTrashObject(&$oTrashVO, $value); + $output->data[$key] = $oTrashVO; + } + } + return $output; + } + + /** + * @brief set trash object from std object + **/ + function _setTrashObject(&$oTrashVO, $stdObject) + { + $oTrashVO->setTrashSrl($stdObject->trash_srl); + $oTrashVO->setTitle($stdObject->title); + $oTrashVO->setOriginModule($stdObject->origin_module); + $oTrashVO->setSerializedObject($stdObject->serialized_object); + $oTrashVO->setDescription($stdObject->description); + $oTrashVO->setIpaddress($stdObject->ipaddress); + $oTrashVO->setRemoverSrl($stdObject->remover_srl); + $oTrashVO->setUserId($stdObject->user_id); + $oTrashVO->setNickName($stdObject->nick_name); + $oTrashVO->setRegdate($stdObject->regdate); + } +} + diff --git a/modules/trash/trash.view.php b/modules/trash/trash.view.php new file mode 100644 index 000000000..7536c6294 --- /dev/null +++ b/modules/trash/trash.view.php @@ -0,0 +1,16 @@ + diff --git a/tests/classes/context/Context.test.php b/tests/classes/context/Context.test.php deleted file mode 100644 index b8415a044..000000000 --- a/tests/classes/context/Context.test.php +++ /dev/null @@ -1,7 +0,0 @@ -assertTrue(true); - } - } -?> diff --git a/tests/classes/validator/ValidatorTest.php b/tests/classes/validator/ValidatorTest.php new file mode 100644 index 000000000..7b713c3f6 --- /dev/null +++ b/tests/classes/validator/ValidatorTest.php @@ -0,0 +1,117 @@ +addFilter('userid', array('required'=>'true')); + + // given data + $this->assertFalse( $vd->validate(array('no-userid'=>'hello')) ); + $this->assertTrue( $vd->validate(array('userid'=>'myuserid')) ); + $this->assertFalse( $vd->validate(array('userid'=>'')) ); + + // context data + $this->assertFalse( $vd->validate() ); + Context::set('userid', ''); + $this->assertFalse( $vd->validate() ); + Context::set('userid', 'myuserid'); + $this->assertTrue( $vd->validate() ); + $vd->removeFilter('userid'); + $this->assertTrue( $vd->validate() ); + } + + public function testDefault() { + global $mock_vars; + + $vd = new Validator(); + $vd->addFilter('userid', array('default'=>'ididid')); + + // given data + $arr = array('no-userid'=>''); + $vd->validate($arr); + $this->assertEquals( $arr, array('no-userid'=>'') ); + + $arr = array('userid'=>''); + $vd->validate(&$arr); // pass-by-reference + $this->assertEquals( $arr, array('userid'=>'ididid') ); + + $arr = array('userid'=>'ownid'); + $vd->validate(&$arr); + $this->assertEquals( $arr, array('userid'=>'ownid') ); + + // context data + $mock_vars = array(); // empty context variables + $vd->validate(); + $this->assertEquals( 'ididid', Context::get('userid') ); + + $vd->load(dirname(__FILE__).'/login.xml'); + + Context::set('userid', ''); + $vd->validate(); + $this->assertEquals( 'idididid', Context::get('userid') ); + } + + public function testLength() { + $vd = new Validator(); + + $vd->addFilter('field1', array('length'=>'3:')); + $this->assertFalse( $vd->validate(array('field1'=>'ab')) ); + $this->assertTrue( $vd->validate(array('field1'=>'abc')) ); + $this->assertTrue( $vd->validate(array('field1'=>'abcd')) ); + } + + public function testCustomRule() { + } + + public function testJSCompile() { + } +} + +$mock_vars = array(); + +class Context +{ + public function gets() { + global $mock_vars; + + $args = func_get_args(); + $output = new stdClass; + + foreach($args as $name) { + $output->{$name} = $mock_vars[$name]; + } + + return $output; + } + + public function getRequestVars() { + global $mock_vars; + + return $mock_vars; + } + + public function get($name) { + global $mock_vars; + return array_key_exists($name, $mock_vars)?$mock_vars[$name]:''; + } + + public function set($name, $value) { + global $mock_vars; + + $mock_vars[$name] = $value; + } + + public function getLangType() { + return 'en'; + } +} diff --git a/tests/classes/validator/insertDocument.xml b/tests/classes/validator/insertDocument.xml new file mode 100644 index 000000000..56d49d7d1 --- /dev/null +++ b/tests/classes/validator/insertDocument.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/classes/validator/login.xml b/tests/classes/validator/login.xml new file mode 100644 index 000000000..db50002bf --- /dev/null +++ b/tests/classes/validator/login.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/tests/index.php b/tests/index.php deleted file mode 100644 index f2aff25f1..000000000 --- a/tests/index.php +++ /dev/null @@ -1,23 +0,0 @@ -init(); - - $this->TestSuite('Classes Test'); - $this->addFile(dirname(__FILE__).'/classes/context/Context.test.php'); - - $this->TestSuite('Module Test'); - $this->addFile(dirname(__FILE__).'/modules/module/module.test.php'); - $this->addFile(dirname(__FILE__).'/modules/module/opage.test.php'); - } - } - -?> diff --git a/tests/modules/module/module.test.php b/tests/modules/module/module.test.php deleted file mode 100644 index b72a6036c..000000000 --- a/tests/modules/module/module.test.php +++ /dev/null @@ -1,19 +0,0 @@ -assertNotNull($oController); - $output = $oController->lock('lockTest', 60); - $this->assertTrue($output->toBool()); - $deadline = $output->get('deadline'); - $output2 = $oController->lock('lockTest', 60); - $this->assertFalse($output2->toBool()); - $output2 = $oController->unlock('lockTest', $deadline); - $this->assertTrue($output2->toBool()); - $output2 = $oController->lock('lockTest', 60); - $this->assertTrue($output2->toBool()); - $output2 = $oController->unlock('lockTest', $output2->get('deadline')); - $this->assertTrue($output2->toBool()); - } - } -?> diff --git a/tests/modules/module/opage.test.php b/tests/modules/module/opage.test.php deleted file mode 100644 index eb9282ff3..000000000 --- a/tests/modules/module/opage.test.php +++ /dev/null @@ -1,63 +0,0 @@ -assertNotNull($oController); - - $path = 'http://domain.com/test_path/opage.php'; - - $content = 'src="images/foo.jpg"'; - $expected_result = 'src="http://domain.com/test_path/images/foo.jpg"'; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - $content = 'src="/images/foo.jpg"'; - $expected_result = 'src="http://domain.com/images/foo.jpg"'; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - $content = 'src="./images/foo.jpg"'; - $expected_result = 'src="http://domain.com/test_path/images/foo.jpg"'; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - $content = 'src="../images/foo.jpg"'; - $expected_result = 'src="http://domain.com/test_path/../images/foo.jpg"'; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - $content = 'url("./images/foo.jpg")'; - $expected_result = 'url("http://domain.com/test_path/images/foo.jpg")'; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - /* - * 프로토콜 - * http, https, ftp, telnet, mailto, mms - */ - $content = 'href="https://domail.com/"'; - $expected_result = $content; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - $content = 'href="mailto:foo@domain.com"'; - $expected_result = $content; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - $content = 'href="mms://domain.com/bar.wmv"'; - $expected_result = $content; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - // + í¬íŠ¸ë²ˆí˜¸ - $path = 'http://domain.com:123/test_path/opage.php'; - - $content = 'src="./images/foo.jpg"'; - $expected_result = 'src="http://domain.com:123/test_path/images/foo.jpg"'; - $result = $oController->replaceSrc($content, $path); - $this->assertEqual($expected_result, $result); - - } - } -?> \ No newline at end of file diff --git a/tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE deleted file mode 100644 index 8ac9cf2aa..000000000 --- a/tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE +++ /dev/null @@ -1,348 +0,0 @@ -Simple Test interface changes -============================= -Because the SimpleTest tool set is still evolving it is likely that tests -written with earlier versions will fail with the newest ones. The most -dramatic changes are in the alpha releases. Here is a list of possible -problems and their fixes... - -No method getRelativeUrls() or getAbsoluteUrls() ------------------------------------------------- -These methods were always a bit weird anyway, and -the new parsing of the base tag makes them more so. -They have been replaced with getUrls() instead. If -you want the old functionality then simply chop -off the current domain from getUrl(). - -Method setWildcard() removed in mocks -------------------------------------- -Even setWildcard() has been removed in 1.0.1beta now. -If you want to test explicitely for a '*' string, then -simply pass in new IdenticalExpectation('*') instead. - -No method _getTest() on mocks ------------------------------ -This has finally been removed. It was a pretty esoteric -flex point anyway. It was there to allow the mocks to -work with other test tools, but no one does this. - -No method assertError(), assertNoErrors(), swallowErrors() ----------------------------------------------------------- -These have been deprecated in 1.0.1beta in favour of -expectError() and expectException(). assertNoErrors() is -redundant if you use expectError() as failures are now reported -immediately. - -No method TestCase::signal() ----------------------------- -This has been deprecated in favour of triggering an error or -throwing an exception. Deprecated as of 1.0.1beta. - -No method TestCase::sendMessage() ---------------------------------- -This has been deprecated as of 1.0.1beta. - -Failure to connect now emits failures -------------------------------------- -It used to be that you would have to use the -getTransferError() call on the web tester to see if -there was a socket level error in a fetch. This check -is now always carried out by the WebTestCase unless -the fetch is prefaced with WebTestCase::ignoreErrors(). -The ignore directive only lasts for test case fetching -action such as get() and click(). - -No method SimpleTestOptions::ignore() -------------------------------------- -This is deprecated in version 1.0.1beta and has been moved -to SimpleTest::ignore() as that is more readable. In -addition, parent classes are also ignored automatically. -If you are using PHP5 you can skip this directive simply -by marking your test case as abstract. - -No method assertCopy() ----------------------- -This is deprecated in 1.0.1 in favour of assertClone(). -The assertClone() method is slightly different in that -the objects must be identical, but without being a -reference. It is thus not a strict inversion of -assertReference(). - -Constructor wildcard override has no effect in mocks ----------------------------------------------------- -As of 1.0.1beta this is now set with setWildcard() instead -of in the constructor. - -No methods setStubBaseClass()/getStubBaseClass() ------------------------------------------------- -As mocks are now used instead of stubs, these methods -stopped working and are now removed as of the 1.0.1beta -release. The mock objects may be freely used instead. - -No method addPartialMockCode() ------------------------------- -The ability to insert arbitrary partial mock code -has been removed. This was a low value feature -causing needless complications. It was removed -in the 1.0.1beta release. - -No method setMockBaseClass() ----------------------------- -The ability to change the mock base class has been -scheduled for removal and is deprecated since the -1.0.1beta version. This was a rarely used feature -except as a workaround for PHP5 limitations. As -these limitations are being resolved it's hoped -that the bundled mocks can be used directly. - -No class Stub -------------- -Server stubs are deprecated from 1.0.1 as the mocks now -have exactly the same interface. Just use mock objects -instead. - -No class SimpleTestOptions --------------------------- -This was replced by the shorter SimpleTest in 1.0.1beta1 -and is since deprecated. - -No file simple_test.php ------------------------ -This was renamed test_case.php in 1.0.1beta to more accurately -reflect it's purpose. This file should never be directly -included in test suites though, as it's part of the -underlying mechanics and has a tendency to be refactored. - -No class WantedPatternExpectation ---------------------------------- -This was deprecated in 1.0.1alpha in favour of the simpler -name PatternExpectation. - -No class NoUnwantedPatternExpectation -------------------------------------- -This was deprecated in 1.0.1alpha in favour of the simpler -name NoPatternExpectation. - -No method assertNoUnwantedPattern() ------------------------------------ -This has been renamed to assertNoPattern() in 1.0.1alpha and -the old form is deprecated. - -No method assertWantedPattern() -------------------------------- -This has been renamed to assertPattern() in 1.0.1alpha and -the old form is deprecated. - -No method assertExpectation() ------------------------------ -This was renamed as assert() in 1.0.1alpha and the old form -has been deprecated. - -No class WildcardExpectation ----------------------------- -This was a mostly internal class for the mock objects. It was -renamed AnythingExpectation to bring it closer to JMock and -NMock in version 1.0.1alpha. - -Missing UnitTestCase::assertErrorPattern() ------------------------------------------- -This method is deprecated for version 1.0.1 onwards. -This method has been subsumed by assertError() that can now -take an expectation. Simply pass a PatternExpectation -into assertError() to simulate the old behaviour. - -No HTML when matching page elements ------------------------------------ -This behaviour has been switched to using plain text as if it -were seen by the user of the browser. This means that HTML tags -are suppressed, entities are converted and whitespace is -normalised. This should make it easier to match items in forms. -Also images are replaced with their "alt" text so that they -can be matched as well. - -No method SimpleRunner::_getTestCase() --------------------------------------- -This was made public as getTestCase() in 1.0RC2. - -No method restartSession() --------------------------- -This was renamed to restart() in the WebTestCase, SimpleBrowser -and the underlying SimpleUserAgent in 1.0RC2. Because it was -undocumented anyway, no attempt was made at backward -compatibility. - -My custom test case ignored by tally() --------------------------------------- -The _assertTrue method has had it's signature changed due to a bug -in the PHP 5.0.1 release. You must now use getTest() from within -that method to get the test case. Mock compatibility with other -unit testers is now deprecated as of 1.0.1alpha as PEAR::PHPUnit2 -should soon have mock support of it's own. - -Broken code extending SimpleRunner ----------------------------------- -This was replaced with SimpleScorer so that I could use the runner -name in another class. This happened in RC1 development and there -is no easy backward compatibility fix. The solution is simply to -extend SimpleScorer instead. - -Missing method getBaseCookieValue() ------------------------------------ -This was renamed getCurrentCookieValue() in RC1. - -Missing files from the SimpleTest suite ---------------------------------------- -Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant -to point at the SimpleTest folder location before any of the toolset -was loaded. This is no longer documented as it is now unnecessary -for later versions. If you are using an earlier version you may -need this constant. Consult the documentation that was bundled with -the release that you are using or upgrade to Beta6 or later. - -No method SimpleBrowser::getCurrentUrl() --------------------------------------- -This is replaced with the more versatile showRequest() for -debugging. It only existed in this context for version Beta5. -Later versions will have SimpleBrowser::getHistory() for tracking -paths through pages. It is renamed as getUrl() since 1.0RC1. - -No method Stub::setStubBaseClass() ----------------------------------- -This method has finally been removed in 1.0RC1. Use -SimpleTestOptions::setStubBaseClass() instead. - -No class CommandLineReporter ----------------------------- -This was renamed to TextReporter in Beta3 and the deprecated version -was removed in 1.0RC1. - -No method requireReturn() -------------------------- -This was deprecated in Beta3 and is now removed. - -No method expectCookie() ------------------------- -This method was abruptly removed in Beta4 so as to simplify the internals -until another mechanism can replace it. As a workaround it is necessary -to assert that the cookie has changed by setting it before the page -fetch and then assert the desired value. - -No method clickSubmitByFormId() -------------------------------- -This method had an incorrect name as no button was involved. It was -renamed to submitByFormId() in Beta4 and the old version deprecated. -Now removed. - -No method paintStart() or paintEnd() ------------------------------------- -You should only get this error if you have subclassed the lower level -reporting and test runner machinery. These methods have been broken -down into events for test methods, events for test cases and events -for group tests. The new methods are... - -paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart() -paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd() - -This change was made in Beta3, ironically to make it easier to subclass -the inner machinery. Simply duplicating the code you had in the previous -methods should provide a temporary fix. - -No class TestDisplay --------------------- -This has been folded into SimpleReporter in Beta3 and is now deprecated. -It was removed in RC1. - -No method WebTestCase::fetch() ------------------------------- -This was renamed get() in Alpha8. It is removed in Beta3. - -No method submit() ------------------- -This has been renamed clickSubmit() in Beta1. The old method was -removed in Beta2. - -No method clearHistory() ------------------------- -This method is deprecated in Beta2 and removed in RC1. - -No method getCallCount() ------------------------- -This method has been deprecated since Beta1 and has now been -removed. There are now more ways to set expectations on counts -and so this method should be unecessery. Removed in RC1. - -Cannot find file * ------------------- -The following public name changes have occoured... - -simple_html_test.php --> reporter.php -simple_mock.php --> mock_objects.php -simple_unit.php --> unit_tester.php -simple_web.php --> web_tester.php - -The old names were deprecated in Alpha8 and removed in Beta1. - -No method attachObserver() --------------------------- -Prior to the Alpha8 release the old internal observer pattern was -gutted and replaced with a visitor. This is to trade flexibility of -test case expansion against the ease of writing user interfaces. - -Code such as... - -$test = &new MyTestCase(); -$test->attachObserver(new TestHtmlDisplay()); -$test->run(); - -...should be rewritten as... - -$test = &new MyTestCase(); -$test->run(new HtmlReporter()); - -If you previously attached multiple observers then the workaround -is to run the tests twice, once with each, until they can be combined. -For one observer the old method is simulated in Alpha 8, but is -removed in Beta1. - -No class TestHtmlDisplay ------------------------- -This class has been renamed to HtmlReporter in Alpha8. It is supported, -but deprecated in Beta1 and removed in Beta2. If you have subclassed -the display for your own design, then you will have to extend this -class (HtmlReporter) instead. - -If you have accessed the event queue by overriding the notify() method -then I am afraid you are in big trouble :(. The reporter is now -carried around the test suite by the runner classes and the methods -called directly. In the unlikely event that this is a problem and -you don't want to upgrade the test tool then simplest is to write your -own runner class and invoke the tests with... - -$test->accept(new MyRunner(new MyReporter())); - -...rather than the run method. This should be easier to extend -anyway and gives much more control. Even this method is overhauled -in Beta3 where the runner class can be set within the test case. Really -the best thing to do is to upgrade to this version as whatever you were -trying to achieve before should now be very much easier. - -Missing set options method --------------------------- -All test suite options are now in one class called SimpleTestOptions. -This means that options are set differently... - -GroupTest::ignore() --> SimpleTestOptions::ignore() -Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass() - -These changed in Alpha8 and the old versions are now removed in RC1. - -No method setExpected*() ------------------------- -The mock expectations changed their names in Alpha4 and the old names -ceased to be supported in Alpha8. The changes are... - -setExpectedArguments() --> expectArguments() -setExpectedArgumentsSequence() --> expectArgumentsAt() -setExpectedCallCount() --> expectCallCount() -setMaximumCallCount() --> expectMaximumCallCount() - -The parameters remained the same. diff --git a/tests/simpletest/LICENSE b/tests/simpletest/LICENSE deleted file mode 100644 index 09f465ab7..000000000 --- a/tests/simpletest/LICENSE +++ /dev/null @@ -1,502 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/tests/simpletest/README b/tests/simpletest/README deleted file mode 100644 index c52e3f7ed..000000000 --- a/tests/simpletest/README +++ /dev/null @@ -1,108 +0,0 @@ -SimpleTest -========== -You probably got this package from... -http://simpletest.sourceforge.net/projects/simpletest/ - -If there is no licence agreement with this package please download -a version from the location above. You must read and accept that -licence to use this software. The file is titled simply LICENSE. - -What is it? It's a framework for unit testing, web site testing and -mock objects for PHP 4.2.0+ (and PHP 5.0 to 5.3 without E_STRICT). - -If you have used JUnit, you will find this PHP unit testing version very -similar. Also included is a mock objects and server stubs generator. -The stubs can have return values set for different arguments, can have -sequences set also by arguments and can return items by reference. -The mocks inherit all of this functionality and can also have -expectations set, again in sequences and for different arguments. - -A web tester similar in concept to JWebUnit is also included. There is no -JavaScript or tables support, but forms, authentication, cookies and -frames are handled. - -You can see a release schedule at http://www.lastcraft.com/overview.php -which is also copied to the documentation folder with this release. -A full PHPDocumenter API documentation exists at -http://simpletest.sourceforge.net/. - -The user interface is minimal -in the extreme, but a lot of information flows from the test suite. -After version 1.0 we will release a better web UI, but we are leaving XUL -and GTk versions to volunteers as everybody has their own opinion -on a good GUI, and we don't want to discourage development by shipping -one with the toolkit. YOucan download an Eclipse plug-in separately. - -You are looking at a second full release. The unit tests for SimpleTest -itself can be run here... - -simpletest/test/unit_tests.php - -And tests involving live network connections as well are here... - -simpletest/test/all_tests.php - -The full tests will typically overrun the 8Mb limit often allowed -to a PHP process. A workaround is to run the tests on the command -with a custom php.ini file if you do not have access to your server -version. - -You will have to edit the all_tests.php file if you are accesssing -the internet through a proxy server. See the comments in all_tests.php -for instructions. - -The full tests read some test data from the LastCraft site. If the site -is down or has been modified for a later version then you will get -spurious errors. A unit_tests.php failure on the other hand would be -very serious. As far as we know we haven't yet managed to check in any -unit test failures, so please correct us if you find one. - -Even if all of the tests run please verify that your existing test suites -also function as expected. If they don't see the file... - -HELP_MY_TESTS_DONT_WORK_ANYMORE - -This contains information on interface changes. It also points out -deprecated interfaces, so you should read this even if all of -your current tests appear to run. - -There is a documentation folder which contains the core reference information -in English and French, although this information is fairly basic. -You can find a tutorial on... - -http://www.lastcraft.com/first_test_tutorial.php - -...to get you started and this material will eventually become included -with the project documentation. A French translation exists at... - -http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires. - -If you download and use, and possibly even extend this tool, please let us -know. Any feedback, even bad, is always welcome and we will work to get -your suggestions into the next release. Ideally please send your -comments to... - -simpletest-support@lists.sourceforge.net - -...so that others can read them too. We usually try to respond within 48 -hours. - -There is no change log except at Sourceforge. You can visit the -release notes to see the completed TODO list after each cycle and also the -status of any bugs, but if the bug is recent then it will be fixed in SVN only. -The SVN check-ins always have all the tests passing and so SVN snapshots should -be pretty usable, although the code may not look so good internally. - -Oh, yes. It is called "Simple" because it should be simple to -use. We intend to add a complete set of tools for a test first -and "test as you code" type of development. "Simple" does not -mean "Lite" in this context. - -Thanks to everyone who has sent comments and offered suggestions. They -really are invaluable, but sadly you are too many to mention in full. -Thanks to all on the advanced PHP forum on SitePoint, especially Harry -Feucks. Early adopters are always an inspiration. - -Marcus Baker, Jason Sweat, Travis Swicegood, Perrick Penet and Edward Z. Yang. --- -marcus@lastcraft.com diff --git a/tests/simpletest/VERSION b/tests/simpletest/VERSION deleted file mode 100644 index 7f207341d..000000000 --- a/tests/simpletest/VERSION +++ /dev/null @@ -1 +0,0 @@ -1.0.1 \ No newline at end of file diff --git a/tests/simpletest/authentication.php b/tests/simpletest/authentication.php deleted file mode 100644 index c56d11bbb..000000000 --- a/tests/simpletest/authentication.php +++ /dev/null @@ -1,238 +0,0 @@ -_type = $type; - $this->_root = $url->getBasePath(); - $this->_username = false; - $this->_password = false; - } - - /** - * Adds another location to the realm. - * @param SimpleUrl $url Somewhere in realm. - * @access public - */ - function stretch($url) { - $this->_root = $this->_getCommonPath($this->_root, $url->getPath()); - } - - /** - * Finds the common starting path. - * @param string $first Path to compare. - * @param string $second Path to compare. - * @return string Common directories. - * @access private - */ - function _getCommonPath($first, $second) { - $first = explode('/', $first); - $second = explode('/', $second); - for ($i = 0; $i < min(count($first), count($second)); $i++) { - if ($first[$i] != $second[$i]) { - return implode('/', array_slice($first, 0, $i)) . '/'; - } - } - return implode('/', $first) . '/'; - } - - /** - * Sets the identity to try within this realm. - * @param string $username Username in authentication dialog. - * @param string $username Password in authentication dialog. - * @access public - */ - function setIdentity($username, $password) { - $this->_username = $username; - $this->_password = $password; - } - - /** - * Accessor for current identity. - * @return string Last succesful username. - * @access public - */ - function getUsername() { - return $this->_username; - } - - /** - * Accessor for current identity. - * @return string Last succesful password. - * @access public - */ - function getPassword() { - return $this->_password; - } - - /** - * Test to see if the URL is within the directory - * tree of the realm. - * @param SimpleUrl $url URL to test. - * @return boolean True if subpath. - * @access public - */ - function isWithin($url) { - if ($this->_isIn($this->_root, $url->getBasePath())) { - return true; - } - if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) { - return true; - } - return false; - } - - /** - * Tests to see if one string is a substring of - * another. - * @param string $part Small bit. - * @param string $whole Big bit. - * @return boolean True if the small bit is - * in the big bit. - * @access private - */ - function _isIn($part, $whole) { - return strpos($whole, $part) === 0; - } -} - -/** - * Manages security realms. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleAuthenticator { - var $_realms; - - /** - * Clears the realms. - * @access public - */ - function SimpleAuthenticator() { - $this->restartSession(); - } - - /** - * Starts with no realms set up. - * @access public - */ - function restartSession() { - $this->_realms = array(); - } - - /** - * Adds a new realm centered the current URL. - * Browsers vary wildly on their behaviour in this - * regard. Mozilla ignores the realm and presents - * only when challenged, wasting bandwidth. IE - * just carries on presenting until a new challenge - * occours. SimpleTest tries to follow the spirit of - * the original standards committee and treats the - * base URL as the root of a file tree shaped realm. - * @param SimpleUrl $url Base of realm. - * @param string $type Authentication type for this - * realm. Only Basic authentication - * is currently supported. - * @param string $realm Name of realm. - * @access public - */ - function addRealm($url, $type, $realm) { - $this->_realms[$url->getHost()][$realm] = new SimpleRealm($type, $url); - } - - /** - * Sets the current identity to be presented - * against that realm. - * @param string $host Server hosting realm. - * @param string $realm Name of realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @access public - */ - function setIdentityForRealm($host, $realm, $username, $password) { - if (isset($this->_realms[$host][$realm])) { - $this->_realms[$host][$realm]->setIdentity($username, $password); - } - } - - /** - * Finds the name of the realm by comparing URLs. - * @param SimpleUrl $url URL to test. - * @return SimpleRealm Name of realm. - * @access private - */ - function _findRealmFromUrl($url) { - if (! isset($this->_realms[$url->getHost()])) { - return false; - } - foreach ($this->_realms[$url->getHost()] as $name => $realm) { - if ($realm->isWithin($url)) { - return $realm; - } - } - return false; - } - - /** - * Presents the appropriate headers for this location. - * @param SimpleHttpRequest $request Request to modify. - * @param SimpleUrl $url Base of realm. - * @access public - */ - function addHeaders(&$request, $url) { - if ($url->getUsername() && $url->getPassword()) { - $username = $url->getUsername(); - $password = $url->getPassword(); - } elseif ($realm = $this->_findRealmFromUrl($url)) { - $username = $realm->getUsername(); - $password = $realm->getPassword(); - } else { - return; - } - $this->addBasicHeaders($request, $username, $password); - } - - /** - * Presents the appropriate headers for this - * location for basic authentication. - * @param SimpleHttpRequest $request Request to modify. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @access public - * @static - */ - function addBasicHeaders(&$request, $username, $password) { - if ($username && $password) { - $request->addHeaderLine( - 'Authorization: Basic ' . base64_encode("$username:$password")); - } - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/autorun.php b/tests/simpletest/autorun.php deleted file mode 100644 index 7d97d2d7f..000000000 --- a/tests/simpletest/autorun.php +++ /dev/null @@ -1,87 +0,0 @@ -createSuiteFromClasses( - basename(initial_file()), - $loader->selectRunnableTests($candidates)); - $result = $suite->run(new DefaultReporter()); - if (SimpleReporter::inCli()) { - exit($result ? 0 : 1); - } -} - -/** - * Checks the current test context to see if a test has - * ever been run. - * @return boolean True if tests have run. - */ -function tests_have_run() { - if ($context = SimpleTest::getContext()) { - return (boolean)$context->getTest(); - } - return false; -} - -/** - * The first autorun file. - * @return string Filename of first autorun script. - */ -function initial_file() { - static $file = false; - if (! $file) { - $file = reset(get_included_files()); - } - return $file; -} - -/** - * Just the classes from the first autorun script. May - * get a few false positives, as it just does a regex based - * on following the word "class". - * @return array List of all possible classes in first - * autorun script. - */ -function classes_defined_in_initial_file() { - if (preg_match_all('/\bclass\s+(\w+)/i', file_get_contents(initial_file()), $matches)) { - return array_map('strtolower', $matches[1]); - } - return array(); -} - -/** - * Every class since the first autorun include. This - * is safe enough if require_once() is alwyas used. - * @return array Class names. - */ -function capture_new_classes() { - global $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES; - return array_map('strtolower', array_diff(get_declared_classes(), - $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES ? - $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES : array())); -} -?> \ No newline at end of file diff --git a/tests/simpletest/browser.php b/tests/simpletest/browser.php deleted file mode 100644 index e2a1fe1d6..000000000 --- a/tests/simpletest/browser.php +++ /dev/null @@ -1,1098 +0,0 @@ -_sequence = array(); - $this->_position = -1; - } - - /** - * Test for no entries yet. - * @return boolean True if empty. - * @access private - */ - function _isEmpty() { - return ($this->_position == -1); - } - - /** - * Test for being at the beginning. - * @return boolean True if first. - * @access private - */ - function _atBeginning() { - return ($this->_position == 0) && ! $this->_isEmpty(); - } - - /** - * Test for being at the last entry. - * @return boolean True if last. - * @access private - */ - function _atEnd() { - return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty(); - } - - /** - * Adds a successfully fetched page to the history. - * @param SimpleUrl $url URL of fetch. - * @param SimpleEncoding $parameters Any post data with the fetch. - * @access public - */ - function recordEntry($url, $parameters) { - $this->_dropFuture(); - array_push( - $this->_sequence, - array('url' => $url, 'parameters' => $parameters)); - $this->_position++; - } - - /** - * Last fully qualified URL for current history - * position. - * @return SimpleUrl URL for this position. - * @access public - */ - function getUrl() { - if ($this->_isEmpty()) { - return false; - } - return $this->_sequence[$this->_position]['url']; - } - - /** - * Parameters of last fetch from current history - * position. - * @return SimpleFormEncoding Post parameters. - * @access public - */ - function getParameters() { - if ($this->_isEmpty()) { - return false; - } - return $this->_sequence[$this->_position]['parameters']; - } - - /** - * Step back one place in the history. Stops at - * the first page. - * @return boolean True if any previous entries. - * @access public - */ - function back() { - if ($this->_isEmpty() || $this->_atBeginning()) { - return false; - } - $this->_position--; - return true; - } - - /** - * Step forward one place. If already at the - * latest entry then nothing will happen. - * @return boolean True if any future entries. - * @access public - */ - function forward() { - if ($this->_isEmpty() || $this->_atEnd()) { - return false; - } - $this->_position++; - return true; - } - - /** - * Ditches all future entries beyond the current - * point. - * @access private - */ - function _dropFuture() { - if ($this->_isEmpty()) { - return; - } - while (! $this->_atEnd()) { - array_pop($this->_sequence); - } - } -} - -/** - * Simulated web browser. This is an aggregate of - * the user agent, the HTML parsing, request history - * and the last header set. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleBrowser { - var $_user_agent; - var $_page; - var $_history; - var $_ignore_frames; - var $_maximum_nested_frames; - - /** - * Starts with a fresh browser with no - * cookie or any other state information. The - * exception is that a default proxy will be - * set up if specified in the options. - * @access public - */ - function SimpleBrowser() { - $this->_user_agent = &$this->_createUserAgent(); - $this->_user_agent->useProxy( - SimpleTest::getDefaultProxy(), - SimpleTest::getDefaultProxyUsername(), - SimpleTest::getDefaultProxyPassword()); - $this->_page = &new SimplePage(); - $this->_history = &$this->_createHistory(); - $this->_ignore_frames = false; - $this->_maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES; - } - - /** - * Creates the underlying user agent. - * @return SimpleFetcher Content fetcher. - * @access protected - */ - function &_createUserAgent() { - $user_agent = &new SimpleUserAgent(); - return $user_agent; - } - - /** - * Creates a new empty history list. - * @return SimpleBrowserHistory New list. - * @access protected - */ - function &_createHistory() { - $history = &new SimpleBrowserHistory(); - return $history; - } - - /** - * Disables frames support. Frames will not be fetched - * and the frameset page will be used instead. - * @access public - */ - function ignoreFrames() { - $this->_ignore_frames = true; - } - - /** - * Enables frames support. Frames will be fetched from - * now on. - * @access public - */ - function useFrames() { - $this->_ignore_frames = false; - } - - /** - * Switches off cookie sending and recieving. - * @access public - */ - function ignoreCookies() { - $this->_user_agent->ignoreCookies(); - } - - /** - * Switches back on the cookie sending and recieving. - * @access public - */ - function useCookies() { - $this->_user_agent->useCookies(); - } - - /** - * Parses the raw content into a page. Will load further - * frame pages unless frames are disabled. - * @param SimpleHttpResponse $response Response from fetch. - * @param integer $depth Nested frameset depth. - * @return SimplePage Parsed HTML. - * @access private - */ - function &_parse($response, $depth = 0) { - $page = &$this->_buildPage($response); - if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) { - return $page; - } - $frameset = &new SimpleFrameset($page); - foreach ($page->getFrameset() as $key => $url) { - $frame = &$this->_fetch($url, new SimpleGetEncoding(), $depth + 1); - $frameset->addFrame($frame, $key); - } - return $frameset; - } - - /** - * Assembles the parsing machinery and actually parses - * a single page. Frees all of the builder memory and so - * unjams the PHP memory management. - * @param SimpleHttpResponse $response Response from fetch. - * @return SimplePage Parsed top level page. - * @access protected - */ - function &_buildPage($response) { - $builder = &new SimplePageBuilder(); - $page = &$builder->parse($response); - $builder->free(); - unset($builder); - return $page; - } - - /** - * Fetches a page. Jointly recursive with the _parse() - * method as it descends a frameset. - * @param string/SimpleUrl $url Target to fetch. - * @param SimpleEncoding $encoding GET/POST parameters. - * @param integer $depth Nested frameset depth protection. - * @return SimplePage Parsed page. - * @access private - */ - function &_fetch($url, $encoding, $depth = 0) { - $response = &$this->_user_agent->fetchResponse($url, $encoding); - if ($response->isError()) { - $page = &new SimplePage($response); - } else { - $page = &$this->_parse($response, $depth); - } - return $page; - } - - /** - * Fetches a page or a single frame if that is the current - * focus. - * @param SimpleUrl $url Target to fetch. - * @param SimpleEncoding $parameters GET/POST parameters. - * @return string Raw content of page. - * @access private - */ - function _load($url, $parameters) { - $frame = $url->getTarget(); - if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) { - return $this->_loadPage($url, $parameters); - } - return $this->_loadFrame(array($frame), $url, $parameters); - } - - /** - * Fetches a page and makes it the current page/frame. - * @param string/SimpleUrl $url Target to fetch as string. - * @param SimplePostEncoding $parameters POST parameters. - * @return string Raw content of page. - * @access private - */ - function _loadPage($url, $parameters) { - $this->_page = &$this->_fetch($url, $parameters); - $this->_history->recordEntry( - $this->_page->getUrl(), - $this->_page->getRequestData()); - return $this->_page->getRaw(); - } - - /** - * Fetches a frame into the existing frameset replacing the - * original. - * @param array $frames List of names to drill down. - * @param string/SimpleUrl $url Target to fetch as string. - * @param SimpleFormEncoding $parameters POST parameters. - * @return string Raw content of page. - * @access private - */ - function _loadFrame($frames, $url, $parameters) { - $page = &$this->_fetch($url, $parameters); - $this->_page->setFrame($frames, $page); - return $page->getRaw(); - } - - /** - * Removes expired and temporary cookies as if - * the browser was closed and re-opened. - * @param string/integer $date Time when session restarted. - * If omitted then all persistent - * cookies are kept. - * @access public - */ - function restart($date = false) { - $this->_user_agent->restart($date); - } - - /** - * Adds a header to every fetch. - * @param string $header Header line to add to every - * request until cleared. - * @access public - */ - function addHeader($header) { - $this->_user_agent->addHeader($header); - } - - /** - * Ages the cookies by the specified time. - * @param integer $interval Amount in seconds. - * @access public - */ - function ageCookies($interval) { - $this->_user_agent->ageCookies($interval); - } - - /** - * Sets an additional cookie. If a cookie has - * the same name and path it is replaced. - * @param string $name Cookie key. - * @param string $value Value of cookie. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $this->_user_agent->setCookie($name, $value, $host, $path, $expiry); - } - - /** - * Reads the most specific cookie value from the - * browser cookies. - * @param string $host Host to search. - * @param string $path Applicable path. - * @param string $name Name of cookie to read. - * @return string False if not present, else the - * value as a string. - * @access public - */ - function getCookieValue($host, $path, $name) { - return $this->_user_agent->getCookieValue($host, $path, $name); - } - - /** - * Reads the current cookies for the current URL. - * @param string $name Key of cookie to find. - * @return string Null if there is no current URL, false - * if the cookie is not set. - * @access public - */ - function getCurrentCookieValue($name) { - return $this->_user_agent->getBaseCookieValue($name, $this->_page->getUrl()); - } - - /** - * Sets the maximum number of redirects before - * a page will be loaded anyway. - * @param integer $max Most hops allowed. - * @access public - */ - function setMaximumRedirects($max) { - $this->_user_agent->setMaximumRedirects($max); - } - - /** - * Sets the maximum number of nesting of framed pages - * within a framed page to prevent loops. - * @param integer $max Highest depth allowed. - * @access public - */ - function setMaximumNestedFrames($max) { - $this->_maximum_nested_frames = $max; - } - - /** - * Sets the socket timeout for opening a connection. - * @param integer $timeout Maximum time in seconds. - * @access public - */ - function setConnectionTimeout($timeout) { - $this->_user_agent->setConnectionTimeout($timeout); - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set URL - * to false to disable. - * @param string $proxy Proxy URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - * @access public - */ - function useProxy($proxy, $username = false, $password = false) { - $this->_user_agent->useProxy($proxy, $username, $password); - } - - /** - * Fetches the page content with a HEAD request. - * Will affect cookies, but will not change the base URL. - * @param string/SimpleUrl $url Target to fetch as string. - * @param hash/SimpleHeadEncoding $parameters Additional parameters for - * HEAD request. - * @return boolean True if successful. - * @access public - */ - function head($url, $parameters = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - if ($this->getUrl()) { - $url = $url->makeAbsolute($this->getUrl()); - } - $response = &$this->_user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters)); - return ! $response->isError(); - } - - /** - * Fetches the page content with a simple GET request. - * @param string/SimpleUrl $url Target to fetch. - * @param hash/SimpleFormEncoding $parameters Additional parameters for - * GET request. - * @return string Content of page or false. - * @access public - */ - function get($url, $parameters = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - if ($this->getUrl()) { - $url = $url->makeAbsolute($this->getUrl()); - } - return $this->_load($url, new SimpleGetEncoding($parameters)); - } - - /** - * Fetches the page content with a POST request. - * @param string/SimpleUrl $url Target to fetch as string. - * @param hash/SimpleFormEncoding $parameters POST parameters. - * @return string Content of page. - * @access public - */ - function post($url, $parameters = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - if ($this->getUrl()) { - $url = $url->makeAbsolute($this->getUrl()); - } - return $this->_load($url, new SimplePostEncoding($parameters)); - } - - /** - * Equivalent to hitting the retry button on the - * browser. Will attempt to repeat the page fetch. If - * there is no history to repeat it will give false. - * @return string/boolean Content if fetch succeeded - * else false. - * @access public - */ - function retry() { - $frames = $this->_page->getFrameFocus(); - if (count($frames) > 0) { - $this->_loadFrame( - $frames, - $this->_page->getUrl(), - $this->_page->getRequestData()); - return $this->_page->getRaw(); - } - if ($url = $this->_history->getUrl()) { - $this->_page = &$this->_fetch($url, $this->_history->getParameters()); - return $this->_page->getRaw(); - } - return false; - } - - /** - * Equivalent to hitting the back button on the - * browser. The browser history is unchanged on - * failure. The page content is refetched as there - * is no concept of content caching in SimpleTest. - * @return boolean True if history entry and - * fetch succeeded - * @access public - */ - function back() { - if (! $this->_history->back()) { - return false; - } - $content = $this->retry(); - if (! $content) { - $this->_history->forward(); - } - return $content; - } - - /** - * Equivalent to hitting the forward button on the - * browser. The browser history is unchanged on - * failure. The page content is refetched as there - * is no concept of content caching in SimpleTest. - * @return boolean True if history entry and - * fetch succeeded - * @access public - */ - function forward() { - if (! $this->_history->forward()) { - return false; - } - $content = $this->retry(); - if (! $content) { - $this->_history->back(); - } - return $content; - } - - /** - * Retries a request after setting the authentication - * for the current realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @return boolean True if successful fetch. Note - * that authentication may still have - * failed. - * @access public - */ - function authenticate($username, $password) { - if (! $this->_page->getRealm()) { - return false; - } - $url = $this->_page->getUrl(); - if (! $url) { - return false; - } - $this->_user_agent->setIdentity( - $url->getHost(), - $this->_page->getRealm(), - $username, - $password); - return $this->retry(); - } - - /** - * Accessor for a breakdown of the frameset. - * @return array Hash tree of frames by name - * or index if no name. - * @access public - */ - function getFrames() { - return $this->_page->getFrames(); - } - - /** - * Accessor for current frame focus. Will be - * false if no frame has focus. - * @return integer/string/boolean Label if any, otherwise - * the position in the frameset - * or false if none. - * @access public - */ - function getFrameFocus() { - return $this->_page->getFrameFocus(); - } - - /** - * Sets the focus by index. The integer index starts from 1. - * @param integer $choice Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocusByIndex($choice) { - return $this->_page->setFrameFocusByIndex($choice); - } - - /** - * Sets the focus by name. - * @param string $name Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocus($name) { - return $this->_page->setFrameFocus($name); - } - - /** - * Clears the frame focus. All frames will be searched - * for content. - * @access public - */ - function clearFrameFocus() { - return $this->_page->clearFrameFocus(); - } - - /** - * Accessor for last error. - * @return string Error from last response. - * @access public - */ - function getTransportError() { - return $this->_page->getTransportError(); - } - - /** - * Accessor for current MIME type. - * @return string MIME type as string; e.g. 'text/html' - * @access public - */ - function getMimeType() { - return $this->_page->getMimeType(); - } - - /** - * Accessor for last response code. - * @return integer Last HTTP response code received. - * @access public - */ - function getResponseCode() { - return $this->_page->getResponseCode(); - } - - /** - * Accessor for last Authentication type. Only valid - * straight after a challenge (401). - * @return string Description of challenge type. - * @access public - */ - function getAuthentication() { - return $this->_page->getAuthentication(); - } - - /** - * Accessor for last Authentication realm. Only valid - * straight after a challenge (401). - * @return string Name of security realm. - * @access public - */ - function getRealm() { - return $this->_page->getRealm(); - } - - /** - * Accessor for current URL of page or frame if - * focused. - * @return string Location of current page or frame as - * a string. - */ - function getUrl() { - $url = $this->_page->getUrl(); - return $url ? $url->asString() : false; - } - - /** - * Accessor for base URL of page if set via BASE tag - * @return string base URL - */ - function getBaseUrl() { - $url = $this->_page->getBaseUrl(); - return $url ? $url->asString() : false; - } - - /** - * Accessor for raw bytes sent down the wire. - * @return string Original text sent. - * @access public - */ - function getRequest() { - return $this->_page->getRequest(); - } - - /** - * Accessor for raw header information. - * @return string Header block. - * @access public - */ - function getHeaders() { - return $this->_page->getHeaders(); - } - - /** - * Accessor for raw page information. - * @return string Original text content of web page. - * @access public - */ - function getContent() { - return $this->_page->getRaw(); - } - - /** - * Accessor for plain text version of the page. - * @return string Normalised text representation. - * @access public - */ - function getContentAsText() { - return $this->_page->getText(); - } - - /** - * Accessor for parsed title. - * @return string Title or false if no title is present. - * @access public - */ - function getTitle() { - return $this->_page->getTitle(); - } - - /** - * Accessor for a list of all links in current page. - * @return array List of urls with scheme of - * http or https and hostname. - * @access public - */ - function getUrls() { - return $this->_page->getUrls(); - } - - /** - * Sets all form fields with that name. - * @param string $label Name or label of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setField($label, $value, $position=false) { - return $this->_page->setField(new SimpleByLabelOrName($label), $value, $position); - } - - /** - * Sets all form fields with that name. Will use label if - * one is available (not yet implemented). - * @param string $name Name of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldByName($name, $value, $position=false) { - return $this->_page->setField(new SimpleByName($name), $value, $position); - } - - /** - * Sets all form fields with that id attribute. - * @param string/integer $id Id of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldById($id, $value) { - return $this->_page->setField(new SimpleById($id), $value); - } - - /** - * Accessor for a form element value within the page. - * Finds the first match. - * @param string $label Field label. - * @return string/boolean A value if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($label) { - return $this->_page->getField(new SimpleByLabelOrName($label)); - } - - /** - * Accessor for a form element value within the page. - * Finds the first match. - * @param string $name Field name. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getFieldByName($name) { - return $this->_page->getField(new SimpleByName($name)); - } - - /** - * Accessor for a form element value within the page. - * @param string/integer $id Id of field in forms. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getFieldById($id) { - return $this->_page->getField(new SimpleById($id)); - } - - /** - * Clicks the submit button by label. The owning - * form will be submitted by this. - * @param string $label Button label. An unlabeled - * button can be triggered by 'Submit'. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickSubmit($label = 'Submit', $additional = false) { - if (! ($form = &$this->_page->getFormBySubmit(new SimpleByLabel($label)))) { - return false; - } - $success = $this->_load( - $form->getAction(), - $form->submitButton(new SimpleByLabel($label), $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit button by name attribute. The owning - * form will be submitted by this. - * @param string $name Button name. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickSubmitByName($name, $additional = false) { - if (! ($form = &$this->_page->getFormBySubmit(new SimpleByName($name)))) { - return false; - } - $success = $this->_load( - $form->getAction(), - $form->submitButton(new SimpleByName($name), $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit button by ID attribute of the button - * itself. The owning form will be submitted by this. - * @param string $id Button ID. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickSubmitById($id, $additional = false) { - if (! ($form = &$this->_page->getFormBySubmit(new SimpleById($id)))) { - return false; - } - $success = $this->_load( - $form->getAction(), - $form->submitButton(new SimpleById($id), $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Tests to see if a submit button exists with this - * label. - * @param string $label Button label. - * @return boolean True if present. - * @access public - */ - function isSubmit($label) { - return (boolean)$this->_page->getFormBySubmit(new SimpleByLabel($label)); - } - - /** - * Clicks the submit image by some kind of label. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $label ID attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickImage($label, $x = 1, $y = 1, $additional = false) { - if (! ($form = &$this->_page->getFormByImage(new SimpleByLabel($label)))) { - return false; - } - $success = $this->_load( - $form->getAction(), - $form->submitImage(new SimpleByLabel($label), $x, $y, $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit image by the name. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $name Name attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickImageByName($name, $x = 1, $y = 1, $additional = false) { - if (! ($form = &$this->_page->getFormByImage(new SimpleByName($name)))) { - return false; - } - $success = $this->_load( - $form->getAction(), - $form->submitImage(new SimpleByName($name), $x, $y, $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit image by ID attribute. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param integer/string $id ID attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickImageById($id, $x = 1, $y = 1, $additional = false) { - if (! ($form = &$this->_page->getFormByImage(new SimpleById($id)))) { - return false; - } - $success = $this->_load( - $form->getAction(), - $form->submitImage(new SimpleById($id), $x, $y, $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Tests to see if an image exists with this - * title or alt text. - * @param string $label Image text. - * @return boolean True if present. - * @access public - */ - function isImage($label) { - return (boolean)$this->_page->getFormByImage(new SimpleByLabel($label)); - } - - /** - * Submits a form by the ID. - * @param string $id The form ID. No submit button value - * will be sent. - * @return string/boolean Page on success. - * @access public - */ - function submitFormById($id) { - if (! ($form = &$this->_page->getFormById($id))) { - return false; - } - $success = $this->_load( - $form->getAction(), - $form->submit()); - return ($success ? $this->getContent() : $success); - } - - /** - * Finds a URL by label. Will find the first link - * found with this link text by default, or a later - * one if an index is given. The match ignores case and - * white space issues. - * @param string $label Text between the anchor tags. - * @param integer $index Link position counting from zero. - * @return string/boolean URL on success. - * @access public - */ - function getLink($label, $index = 0) { - $urls = $this->_page->getUrlsByLabel($label); - if (count($urls) == 0) { - return false; - } - if (count($urls) < $index + 1) { - return false; - } - return $urls[$index]; - } - - /** - * Follows a link by label. Will click the first link - * found with this link text by default, or a later - * one if an index is given. The match ignores case and - * white space issues. - * @param string $label Text between the anchor tags. - * @param integer $index Link position counting from zero. - * @return string/boolean Page on success. - * @access public - */ - function clickLink($label, $index = 0) { - $url = $this->getLink($label, $index); - if ($url === false) { - return false; - } - $this->_load($url, new SimpleGetEncoding()); - return $this->getContent(); - } - - /** - * Finds a link by id attribute. - * @param string $id ID attribute value. - * @return string/boolean URL on success. - * @access public - */ - function getLinkById($id) { - return $this->_page->getUrlById($id); - } - - /** - * Follows a link by id attribute. - * @param string $id ID attribute value. - * @return string/boolean Page on success. - * @access public - */ - function clickLinkById($id) { - if (! ($url = $this->getLinkById($id))) { - return false; - } - $this->_load($url, new SimpleGetEncoding()); - return $this->getContent(); - } - - /** - * Clicks a visible text item. Will first try buttons, - * then links and then images. - * @param string $label Visible text or alt text. - * @return string/boolean Raw page or false. - * @access public - */ - function click($label) { - $raw = $this->clickSubmit($label); - if (! $raw) { - $raw = $this->clickLink($label); - } - if (! $raw) { - $raw = $this->clickImage($label); - } - return $raw; - } - - /** - * Tests to see if a click target exists. - * @param string $label Visible text or alt text. - * @return boolean True if target present. - * @access public - */ - function isClickable($label) { - return $this->isSubmit($label) || ($this->getLink($label) !== false) || $this->isImage($label); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/collector.php b/tests/simpletest/collector.php deleted file mode 100644 index 5b8255d39..000000000 --- a/tests/simpletest/collector.php +++ /dev/null @@ -1,122 +0,0 @@ - - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: collector.php 1723 2008-04-08 00:34:10Z lastcraft $ - */ - -/** - * The basic collector for {@link GroupTest} - * - * @see collect(), GroupTest::collect() - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleCollector { - - /** - * Strips off any kind of slash at the end so as to normalise the path. - * @param string $path Path to normalise. - * @return string Path without trailing slash. - */ - function _removeTrailingSlash($path) { - if (substr($path, -1) == DIRECTORY_SEPARATOR) { - return substr($path, 0, -1); - } elseif (substr($path, -1) == '/') { - return substr($path, 0, -1); - } else { - return $path; - } - } - - /** - * Scans the directory and adds what it can. - * @param object $test Group test with {@link GroupTest::addTestFile()} method. - * @param string $path Directory to scan. - * @see _attemptToAdd() - */ - function collect(&$test, $path) { - $path = $this->_removeTrailingSlash($path); - if ($handle = opendir($path)) { - while (($entry = readdir($handle)) !== false) { - if ($this->_isHidden($entry)) { - continue; - } - $this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry); - } - closedir($handle); - } - } - - /** - * This method determines what should be done with a given file and adds - * it via {@link GroupTest::addTestFile()} if necessary. - * - * This method should be overriden to provide custom matching criteria, - * such as pattern matching, recursive matching, etc. For an example, see - * {@link SimplePatternCollector::_handle()}. - * - * @param object $test Group test with {@link GroupTest::addTestFile()} method. - * @param string $filename A filename as generated by {@link collect()} - * @see collect() - * @access protected - */ - function _handle(&$test, $file) { - if (is_dir($file)) { - return; - } - $test->addTestFile($file); - } - - /** - * Tests for hidden files so as to skip them. Currently - * only tests for Unix hidden files. - * @param string $filename Plain filename. - * @return boolean True if hidden file. - * @access private - */ - function _isHidden($filename) { - return strncmp($filename, '.', 1) == 0; - } -} - -/** - * An extension to {@link SimpleCollector} that only adds files matching a - * given pattern. - * - * @package SimpleTest - * @subpackage UnitTester - * @see SimpleCollector - */ -class SimplePatternCollector extends SimpleCollector { - var $_pattern; - - /** - * - * @param string $pattern Perl compatible regex to test name against - * See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE} - * for full documentation of valid pattern.s - */ - function SimplePatternCollector($pattern = '/php$/i') { - $this->_pattern = $pattern; - } - - /** - * Attempts to add files that match a given pattern. - * - * @see SimpleCollector::_handle() - * @param object $test Group test with {@link GroupTest::addTestFile()} method. - * @param string $path Directory to scan. - * @access protected - */ - function _handle(&$test, $filename) { - if (preg_match($this->_pattern, $filename)) { - parent::_handle($test, $filename); - } - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/compatibility.php b/tests/simpletest/compatibility.php deleted file mode 100644 index 4e0f78a4b..000000000 --- a/tests/simpletest/compatibility.php +++ /dev/null @@ -1,173 +0,0 @@ -= 0) { - eval('$copy = clone $object;'); - return $copy; - } - return $object; - } - - /** - * Identity test. Drops back to equality + types for PHP5 - * objects as the === operator counts as the - * stronger reference constraint. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if identical. - * @access public - * @static - */ - function isIdentical($first, $second) { - if (version_compare(phpversion(), '5') >= 0) { - return SimpleTestCompatibility::_isIdenticalType($first, $second); - } - if ($first != $second) { - return false; - } - return ($first === $second); - } - - /** - * Recursive type test. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if same type. - * @access private - * @static - */ - function _isIdenticalType($first, $second) { - if (gettype($first) != gettype($second)) { - return false; - } - if (is_object($first) && is_object($second)) { - if (get_class($first) != get_class($second)) { - return false; - } - return SimpleTestCompatibility::_isArrayOfIdenticalTypes( - get_object_vars($first), - get_object_vars($second)); - } - if (is_array($first) && is_array($second)) { - return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second); - } - if ($first !== $second) { - return false; - } - return true; - } - - /** - * Recursive type test for each element of an array. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if identical. - * @access private - * @static - */ - function _isArrayOfIdenticalTypes($first, $second) { - if (array_keys($first) != array_keys($second)) { - return false; - } - foreach (array_keys($first) as $key) { - $is_identical = SimpleTestCompatibility::_isIdenticalType( - $first[$key], - $second[$key]); - if (! $is_identical) { - return false; - } - } - return true; - } - - /** - * Test for two variables being aliases. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if same. - * @access public - * @static - */ - function isReference(&$first, &$second) { - if (version_compare(phpversion(), '5', '>=') && is_object($first)) { - return ($first === $second); - } - if (is_object($first) && is_object($second)) { - $id = uniqid("test"); - $first->$id = true; - $is_ref = isset($second->$id); - unset($first->$id); - return $is_ref; - } - $temp = $first; - $first = uniqid("test"); - $is_ref = ($first === $second); - $first = $temp; - return $is_ref; - } - - /** - * Test to see if an object is a member of a - * class hiearchy. - * @param object $object Object to test. - * @param string $class Root name of hiearchy. - * @return boolean True if class in hiearchy. - * @access public - * @static - */ - function isA($object, $class) { - if (version_compare(phpversion(), '5') >= 0) { - if (! class_exists($class, false)) { - if (function_exists('interface_exists')) { - if (! interface_exists($class, false)) { - return false; - } - } - } - eval("\$is_a = \$object instanceof $class;"); - return $is_a; - } - if (function_exists('is_a')) { - return is_a($object, $class); - } - return ((strtolower($class) == get_class($object)) - or (is_subclass_of($object, $class))); - } - - /** - * Sets a socket timeout for each chunk. - * @param resource $handle Socket handle. - * @param integer $timeout Limit in seconds. - * @access public - * @static - */ - function setTimeout($handle, $timeout) { - if (function_exists('stream_set_timeout')) { - stream_set_timeout($handle, $timeout, 0); - } elseif (function_exists('socket_set_timeout')) { - socket_set_timeout($handle, $timeout, 0); - } elseif (function_exists('set_socket_timeout')) { - set_socket_timeout($handle, $timeout, 0); - } - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/cookies.php b/tests/simpletest/cookies.php deleted file mode 100644 index ed1c025d2..000000000 --- a/tests/simpletest/cookies.php +++ /dev/null @@ -1,380 +0,0 @@ -_host = false; - $this->_name = $name; - $this->_value = $value; - $this->_path = ($path ? $this->_fixPath($path) : "/"); - $this->_expiry = false; - if (is_string($expiry)) { - $this->_expiry = strtotime($expiry); - } elseif (is_integer($expiry)) { - $this->_expiry = $expiry; - } - $this->_is_secure = $is_secure; - } - - /** - * Sets the host. The cookie rules determine - * that the first two parts are taken for - * certain TLDs and three for others. If the - * new host does not match these rules then the - * call will fail. - * @param string $host New hostname. - * @return boolean True if hostname is valid. - * @access public - */ - function setHost($host) { - if ($host = $this->_truncateHost($host)) { - $this->_host = $host; - return true; - } - return false; - } - - /** - * Accessor for the truncated host to which this - * cookie applies. - * @return string Truncated hostname. - * @access public - */ - function getHost() { - return $this->_host; - } - - /** - * Test for a cookie being valid for a host name. - * @param string $host Host to test against. - * @return boolean True if the cookie would be valid - * here. - */ - function isValidHost($host) { - return ($this->_truncateHost($host) === $this->getHost()); - } - - /** - * Extracts just the domain part that determines a - * cookie's host validity. - * @param string $host Host name to truncate. - * @return string Domain or false on a bad host. - * @access private - */ - function _truncateHost($host) { - $tlds = SimpleUrl::getAllTopLevelDomains(); - if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) { - return $matches[0]; - } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) { - return $matches[0]; - } - return false; - } - - /** - * Accessor for name. - * @return string Cookie key. - * @access public - */ - function getName() { - return $this->_name; - } - - /** - * Accessor for value. A deleted cookie will - * have an empty string for this. - * @return string Cookie value. - * @access public - */ - function getValue() { - return $this->_value; - } - - /** - * Accessor for path. - * @return string Valid cookie path. - * @access public - */ - function getPath() { - return $this->_path; - } - - /** - * Tests a path to see if the cookie applies - * there. The test path must be longer or - * equal to the cookie path. - * @param string $path Path to test against. - * @return boolean True if cookie valid here. - * @access public - */ - function isValidPath($path) { - return (strncmp( - $this->_fixPath($path), - $this->getPath(), - strlen($this->getPath())) == 0); - } - - /** - * Accessor for expiry. - * @return string Expiry string. - * @access public - */ - function getExpiry() { - if (! $this->_expiry) { - return false; - } - return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT"; - } - - /** - * Test to see if cookie is expired against - * the cookie format time or timestamp. - * Will give true for a session cookie. - * @param integer/string $now Time to test against. Result - * will be false if this time - * is later than the cookie expiry. - * Can be either a timestamp integer - * or a cookie format date. - * @access public - */ - function isExpired($now) { - if (! $this->_expiry) { - return true; - } - if (is_string($now)) { - $now = strtotime($now); - } - return ($this->_expiry < $now); - } - - /** - * Ages the cookie by the specified number of - * seconds. - * @param integer $interval In seconds. - * @public - */ - function agePrematurely($interval) { - if ($this->_expiry) { - $this->_expiry -= $interval; - } - } - - /** - * Accessor for the secure flag. - * @return boolean True if cookie needs SSL. - * @access public - */ - function isSecure() { - return $this->_is_secure; - } - - /** - * Adds a trailing and leading slash to the path - * if missing. - * @param string $path Path to fix. - * @access private - */ - function _fixPath($path) { - if (substr($path, 0, 1) != '/') { - $path = '/' . $path; - } - if (substr($path, -1, 1) != '/') { - $path .= '/'; - } - return $path; - } -} - -/** - * Repository for cookies. This stuff is a - * tiny bit browser dependent. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleCookieJar { - var $_cookies; - - /** - * Constructor. Jar starts empty. - * @access public - */ - function SimpleCookieJar() { - $this->_cookies = array(); - } - - /** - * Removes expired and temporary cookies as if - * the browser was closed and re-opened. - * @param string/integer $now Time to test expiry against. - * @access public - */ - function restartSession($date = false) { - $surviving_cookies = array(); - for ($i = 0; $i < count($this->_cookies); $i++) { - if (! $this->_cookies[$i]->getValue()) { - continue; - } - if (! $this->_cookies[$i]->getExpiry()) { - continue; - } - if ($date && $this->_cookies[$i]->isExpired($date)) { - continue; - } - $surviving_cookies[] = $this->_cookies[$i]; - } - $this->_cookies = $surviving_cookies; - } - - /** - * Ages all cookies in the cookie jar. - * @param integer $interval The old session is moved - * into the past by this number - * of seconds. Cookies now over - * age will be removed. - * @access public - */ - function agePrematurely($interval) { - for ($i = 0; $i < count($this->_cookies); $i++) { - $this->_cookies[$i]->agePrematurely($interval); - } - } - - /** - * Sets an additional cookie. If a cookie has - * the same name and path it is replaced. - * @param string $name Cookie key. - * @param string $value Value of cookie. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $cookie = new SimpleCookie($name, $value, $path, $expiry); - if ($host) { - $cookie->setHost($host); - } - $this->_cookies[$this->_findFirstMatch($cookie)] = $cookie; - } - - /** - * Finds a matching cookie to write over or the - * first empty slot if none. - * @param SimpleCookie $cookie Cookie to write into jar. - * @return integer Available slot. - * @access private - */ - function _findFirstMatch($cookie) { - for ($i = 0; $i < count($this->_cookies); $i++) { - $is_match = $this->_isMatch( - $cookie, - $this->_cookies[$i]->getHost(), - $this->_cookies[$i]->getPath(), - $this->_cookies[$i]->getName()); - if ($is_match) { - return $i; - } - } - return count($this->_cookies); - } - - /** - * Reads the most specific cookie value from the - * browser cookies. Looks for the longest path that - * matches. - * @param string $host Host to search. - * @param string $path Applicable path. - * @param string $name Name of cookie to read. - * @return string False if not present, else the - * value as a string. - * @access public - */ - function getCookieValue($host, $path, $name) { - $longest_path = ''; - foreach ($this->_cookies as $cookie) { - if ($this->_isMatch($cookie, $host, $path, $name)) { - if (strlen($cookie->getPath()) > strlen($longest_path)) { - $value = $cookie->getValue(); - $longest_path = $cookie->getPath(); - } - } - } - return (isset($value) ? $value : false); - } - - /** - * Tests cookie for matching against search - * criteria. - * @param SimpleTest $cookie Cookie to test. - * @param string $host Host must match. - * @param string $path Cookie path must be shorter than - * this path. - * @param string $name Name must match. - * @return boolean True if matched. - * @access private - */ - function _isMatch($cookie, $host, $path, $name) { - if ($cookie->getName() != $name) { - return false; - } - if ($host && $cookie->getHost() && ! $cookie->isValidHost($host)) { - return false; - } - if (! $cookie->isValidPath($path)) { - return false; - } - return true; - } - - /** - * Uses a URL to sift relevant cookies by host and - * path. Results are list of strings of form "name=value". - * @param SimpleUrl $url Url to select by. - * @return array Valid name and value pairs. - * @access public - */ - function selectAsPairs($url) { - $pairs = array(); - foreach ($this->_cookies as $cookie) { - if ($this->_isMatch($cookie, $url->getHost(), $url->getPath(), $cookie->getName())) { - $pairs[] = $cookie->getName() . '=' . $cookie->getValue(); - } - } - return $pairs; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/default_reporter.php b/tests/simpletest/default_reporter.php deleted file mode 100644 index bd4c6a190..000000000 --- a/tests/simpletest/default_reporter.php +++ /dev/null @@ -1,133 +0,0 @@ - '_case', 'c' => '_case', - 'test' => '_test', 't' => '_test', - 'xml' => '_xml', 'x' => '_xml'); - var $_case = ''; - var $_test = ''; - var $_xml = false; - var $_no_skips = false; - - /** - * Parses raw command line arguments into object properties. - * @param string $arguments Raw commend line arguments. - */ - function SimpleCommandLineParser($arguments) { - if (! is_array($arguments)) { - return; - } - foreach ($arguments as $i => $argument) { - if (preg_match('/^--?(test|case|t|c)=(.+)$/', $argument, $matches)) { - $property = $this->_to_property[$matches[1]]; - $this->$property = $matches[2]; - } elseif (preg_match('/^--?(test|case|t|c)$/', $argument, $matches)) { - $property = $this->_to_property[$matches[1]]; - if (isset($arguments[$i + 1])) { - $this->$property = $arguments[$i + 1]; - } - } elseif (preg_match('/^--?(xml|x)$/', $argument)) { - $this->_xml = true; - } elseif (preg_match('/^--?(no-skip|no-skips|s)$/', $argument)) { - $this->_no_skips = true; - } - } - } - - /** - * Run only this test. - * @return string Test name to run. - * @access public - */ - function getTest() { - return $this->_test; - } - - /** - * Run only this test suite. - * @return string Test class name to run. - * @access public - */ - function getTestCase() { - return $this->_case; - } - - /** - * Output should be XML or not. - * @return boolean True if XML desired. - * @access public - */ - function isXml() { - return $this->_xml; - } - - /** - * Output should suppress skip messages. - * @return boolean True for no skips. - * @access public - */ - function noSkips() { - return $this->_no_skips; - } -} - -/** - * The default reporter used by SimpleTest's autorun - * feature. The actual reporters used are dependency - * injected and can be overridden. - * @package SimpleTest - * @subpackage UnitTester - */ -class DefaultReporter extends SimpleReporterDecorator { - - /** - * Assembles the appopriate reporter for the environment. - */ - function DefaultReporter() { - if (SimpleReporter::inCli()) { - global $argv; - $parser = new SimpleCommandLineParser($argv); - $interfaces = $parser->isXml() ? array('XmlReporter') : array('TextReporter'); - $reporter = &new SelectiveReporter( - SimpleTest::preferred($interfaces), - $parser->getTestCase(), - $parser->getTest()); - if ($parser->noSkips()) { - $reporter = &new NoSkipsReporter($reporter); - } - } else { - $reporter = &new SelectiveReporter( - SimpleTest::preferred('HtmlReporter'), - @$_GET['c'], - @$_GET['t']); - if (@$_GET['skips'] == 'no' || @$_GET['show-skips'] == 'no') { - $reporter = &new NoSkipsReporter($reporter); - } - } - $this->SimpleReporterDecorator($reporter); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/detached.php b/tests/simpletest/detached.php deleted file mode 100644 index e323d8cd5..000000000 --- a/tests/simpletest/detached.php +++ /dev/null @@ -1,96 +0,0 @@ -_command = $command; - $this->_dry_command = $dry_command ? $dry_command : $command; - $this->_size = false; - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->_command; - } - - /** - * Runs the top level test for this class. Currently - * reads the data as a single chunk. I'll fix this - * once I have added iteration to the browser. - * @param SimpleReporter $reporter Target of test results. - * @returns boolean True if no failures. - * @access public - */ - function run(&$reporter) { - $shell = &new SimpleShell(); - $shell->execute($this->_command); - $parser = &$this->_createParser($reporter); - if (! $parser->parse($shell->getOutput())) { - trigger_error('Cannot parse incoming XML from [' . $this->_command . ']'); - return false; - } - return true; - } - - /** - * Accessor for the number of subtests. - * @return integer Number of test cases. - * @access public - */ - function getSize() { - if ($this->_size === false) { - $shell = &new SimpleShell(); - $shell->execute($this->_dry_command); - $reporter = &new SimpleReporter(); - $parser = &$this->_createParser($reporter); - if (! $parser->parse($shell->getOutput())) { - trigger_error('Cannot parse incoming XML from [' . $this->_dry_command . ']'); - return false; - } - $this->_size = $reporter->getTestCaseCount(); - } - return $this->_size; - } - - /** - * Creates the XML parser. - * @param SimpleReporter $reporter Target of test results. - * @return SimpleTestXmlListener XML reader. - * @access protected - */ - function &_createParser(&$reporter) { - return new SimpleTestXmlParser($reporter); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/dumper.php b/tests/simpletest/dumper.php deleted file mode 100644 index 2d75985c0..000000000 --- a/tests/simpletest/dumper.php +++ /dev/null @@ -1,360 +0,0 @@ -getType($value); - switch($type) { - case "Null": - return "NULL"; - case "Boolean": - return "Boolean: " . ($value ? "true" : "false"); - case "Array": - return "Array: " . count($value) . " items"; - case "Object": - return "Object: of " . get_class($value); - case "String": - return "String: " . $this->clipString($value, 200); - default: - return "$type: $value"; - } - return "Unknown"; - } - - /** - * Gets the string representation of a type. - * @param mixed $value Variable to check against. - * @return string Type. - * @access public - */ - function getType($value) { - if (! isset($value)) { - return "Null"; - } elseif (is_bool($value)) { - return "Boolean"; - } elseif (is_string($value)) { - return "String"; - } elseif (is_integer($value)) { - return "Integer"; - } elseif (is_float($value)) { - return "Float"; - } elseif (is_array($value)) { - return "Array"; - } elseif (is_resource($value)) { - return "Resource"; - } elseif (is_object($value)) { - return "Object"; - } - return "Unknown"; - } - - /** - * Creates a human readable description of the - * difference between two variables. Uses a - * dynamic call. - * @param mixed $first First variable. - * @param mixed $second Value to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Description of difference. - * @access public - */ - function describeDifference($first, $second, $identical = false) { - if ($identical) { - if (! $this->_isTypeMatch($first, $second)) { - return "with type mismatch as [" . $this->describeValue($first) . - "] does not match [" . $this->describeValue($second) . "]"; - } - } - $type = $this->getType($first); - if ($type == "Unknown") { - return "with unknown type"; - } - $method = '_describe' . $type . 'Difference'; - return $this->$method($first, $second, $identical); - } - - /** - * Tests to see if types match. - * @param mixed $first First variable. - * @param mixed $second Value to compare with. - * @return boolean True if matches. - * @access private - */ - function _isTypeMatch($first, $second) { - return ($this->getType($first) == $this->getType($second)); - } - - /** - * Clips a string to a maximum length. - * @param string $value String to truncate. - * @param integer $size Minimum string size to show. - * @param integer $position Centre of string section. - * @return string Shortened version. - * @access public - */ - function clipString($value, $size, $position = 0) { - $length = strlen($value); - if ($length <= $size) { - return $value; - } - $position = min($position, $length); - $start = ($size/2 > $position ? 0 : $position - $size/2); - if ($start + $size > $length) { - $start = $length - $size; - } - $value = substr($value, $start, $size); - return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : ""); - } - - /** - * Creates a human readable description of the - * difference between two variables. The minimal - * version. - * @param null $first First value. - * @param mixed $second Value to compare with. - * @return string Human readable description. - * @access private - */ - function _describeGenericDifference($first, $second) { - return "as [" . $this->describeValue($first) . - "] does not match [" . - $this->describeValue($second) . "]"; - } - - /** - * Creates a human readable description of the - * difference between a null and another variable. - * @param null $first First null. - * @param mixed $second Null to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeNullDifference($first, $second, $identical) { - return $this->_describeGenericDifference($first, $second); - } - - /** - * Creates a human readable description of the - * difference between a boolean and another variable. - * @param boolean $first First boolean. - * @param mixed $second Boolean to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeBooleanDifference($first, $second, $identical) { - return $this->_describeGenericDifference($first, $second); - } - - /** - * Creates a human readable description of the - * difference between a string and another variable. - * @param string $first First string. - * @param mixed $second String to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeStringDifference($first, $second, $identical) { - if (is_object($second) || is_array($second)) { - return $this->_describeGenericDifference($first, $second); - } - $position = $this->_stringDiffersAt($first, $second); - $message = "at character $position"; - $message .= " with [" . - $this->clipString($first, 200, $position) . "] and [" . - $this->clipString($second, 200, $position) . "]"; - return $message; - } - - /** - * Creates a human readable description of the - * difference between an integer and another variable. - * @param integer $first First number. - * @param mixed $second Number to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeIntegerDifference($first, $second, $identical) { - if (is_object($second) || is_array($second)) { - return $this->_describeGenericDifference($first, $second); - } - return "because [" . $this->describeValue($first) . - "] differs from [" . - $this->describeValue($second) . "] by " . - abs($first - $second); - } - - /** - * Creates a human readable description of the - * difference between two floating point numbers. - * @param float $first First float. - * @param mixed $second Float to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeFloatDifference($first, $second, $identical) { - if (is_object($second) || is_array($second)) { - return $this->_describeGenericDifference($first, $second); - } - return "because [" . $this->describeValue($first) . - "] differs from [" . - $this->describeValue($second) . "] by " . - abs($first - $second); - } - - /** - * Creates a human readable description of the - * difference between two arrays. - * @param array $first First array. - * @param mixed $second Array to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeArrayDifference($first, $second, $identical) { - if (! is_array($second)) { - return $this->_describeGenericDifference($first, $second); - } - if (! $this->_isMatchingKeys($first, $second, $identical)) { - return "as key list [" . - implode(", ", array_keys($first)) . "] does not match key list [" . - implode(", ", array_keys($second)) . "]"; - } - foreach (array_keys($first) as $key) { - if ($identical && ($first[$key] === $second[$key])) { - continue; - } - if (! $identical && ($first[$key] == $second[$key])) { - continue; - } - return "with member [$key] " . $this->describeDifference( - $first[$key], - $second[$key], - $identical); - } - return ""; - } - - /** - * Compares two arrays to see if their key lists match. - * For an identical match, the ordering and types of the keys - * is significant. - * @param array $first First array. - * @param array $second Array to compare with. - * @param boolean $identical If true then type anomolies count. - * @return boolean True if matching. - * @access private - */ - function _isMatchingKeys($first, $second, $identical) { - $first_keys = array_keys($first); - $second_keys = array_keys($second); - if ($identical) { - return ($first_keys === $second_keys); - } - sort($first_keys); - sort($second_keys); - return ($first_keys == $second_keys); - } - - /** - * Creates a human readable description of the - * difference between a resource and another variable. - * @param resource $first First resource. - * @param mixed $second Resource to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeResourceDifference($first, $second, $identical) { - return $this->_describeGenericDifference($first, $second); - } - - /** - * Creates a human readable description of the - * difference between two objects. - * @param object $first First object. - * @param mixed $second Object to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - function _describeObjectDifference($first, $second, $identical) { - if (! is_object($second)) { - return $this->_describeGenericDifference($first, $second); - } - return $this->_describeArrayDifference( - get_object_vars($first), - get_object_vars($second), - $identical); - } - - /** - * Find the first character position that differs - * in two strings by binary chop. - * @param string $first First string. - * @param string $second String to compare with. - * @return integer Position of first differing - * character. - * @access private - */ - function _stringDiffersAt($first, $second) { - if (! $first || ! $second) { - return 0; - } - if (strlen($first) < strlen($second)) { - list($first, $second) = array($second, $first); - } - $position = 0; - $step = strlen($first); - while ($step > 1) { - $step = (integer)(($step + 1) / 2); - if (strncmp($first, $second, $position + $step) == 0) { - $position += $step; - } - } - return $position; - } - - /** - * Sends a formatted dump of a variable to a string. - * @param mixed $variable Variable to display. - * @return string Output from print_r(). - * @access public - * @static - */ - function dump($variable) { - ob_start(); - print_r($variable); - $formatted = ob_get_contents(); - ob_end_clean(); - return $formatted; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/eclipse.php b/tests/simpletest/eclipse.php deleted file mode 100644 index 0f1a4fcb2..000000000 --- a/tests/simpletest/eclipse.php +++ /dev/null @@ -1,307 +0,0 @@ -_listener = &$listener; - $this->SimpleScorer(); - $this->_case = ""; - $this->_group = ""; - $this->_method = ""; - $this->_cc = $cc; - $this->_error = false; - $this->_fail = false; - } - - /** - * Means to display human readable object comparisons. - * @return SimpleDumper Visual comparer. - */ - function getDumper() { - return new SimpleDumper(); - } - - /** - * Localhost connection from Eclipse. - * @param integer $port Port to connect to Eclipse. - * @param string $host Normally localhost. - * @return SimpleSocket Connection to Eclipse. - */ - function &createListener($port, $host="127.0.0.1"){ - $tmplistener = &new SimpleSocket($host, $port, 5); - return $tmplistener; - } - - /** - * Wraps the test in an output buffer. - * @param SimpleInvoker $invoker Current test runner. - * @return EclipseInvoker Decorator with output buffering. - * @access public - */ - function &createInvoker(&$invoker){ - $eclinvoker = &new EclipseInvoker($invoker, $this->_listener); - return $eclinvoker; - } - - /** - * C style escaping. - * @param string $raw String with backslashes, quotes and whitespace. - * @return string Replaced with C backslashed tokens. - */ - function escapeVal($raw){ - $needle = array("\\","\"","/","\b","\f","\n","\r","\t"); - $replace = array('\\\\','\"','\/','\b','\f','\n','\r','\t'); - return str_replace($needle, $replace, $raw); - } - - /** - * Stash the first passing item. Clicking the test - * item goes to first pass. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintPass($message){ - if (! $this->_pass){ - $this->_message = $this->escapeVal($message); - } - $this->_pass = true; - } - - /** - * Stash the first failing item. Clicking the test - * item goes to first fail. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintFail($message){ - //only get the first failure or error - if (! $this->_fail && ! $this->_error){ - $this->_fail = true; - $this->_message = $this->escapeVal($message); - $this->_listener->write('{status:"fail",message:"'.$this->_message.'",group:"'.$this->_group.'",case:"'.$this->_case.'",method:"'.$this->_method.'"}'); - } - } - - /** - * Stash the first error. Clicking the test - * item goes to first error. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintError($message){ - if (! $this->_fail && ! $this->_error){ - $this->_error = true; - $this->_message = $this->escapeVal($message); - $this->_listener->write('{status:"error",message:"'.$this->_message.'",group:"'.$this->_group.'",case:"'.$this->_case.'",method:"'.$this->_method.'"}'); - } - } - - - /** - * Stash the first exception. Clicking the test - * item goes to first message. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintException($exception){ - if (! $this->_fail && ! $this->_error){ - $this->_error = true; - $message = 'Unexpected exception of type[' . get_class($exception) . - '] with message [' . $exception->getMessage() . '] in [' . - $exception->getFile() .' line '. $exception->getLine() . ']'; - $this->_message = $this->escapeVal($message); - $this->_listener->write( - '{status:"error",message:"' . $this->_message . '",group:"' . - $this->_group . '",case:"' . $this->_case . '",method:"' . $this->_method - . '"}'); - } - } - - - /** - * We don't display any special header. - * @param string $test_name First test top level - * to start. - * @access public - */ - function paintHeader($test_name) { - } - - /** - * We don't display any special footer. - * @param string $test_name The top level test. - * @access public - */ - function paintFooter($test_name) { - } - - /** - * Paints nothing at the start of a test method, but stash - * the method name for later. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintMethodStart($method) { - $this->_pass = false; - $this->_fail = false; - $this->_error = false; - $this->_method = $this->escapeVal($method); - } - - /** - * Only send one message if the test passes, after that - * suppress the message. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintMethodEnd($method){ - if ($this->_fail || $this->_error || ! $this->_pass){ - } else { - $this->_listener->write( - '{status:"pass",message:"' . $this->_message . '",group:"' . - $this->_group . '",case:"' . $this->_case . '",method:"' . - $this->_method . '"}'); - } - } - - /** - * Stashes the test case name for the later failure message. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($case){ - $this->_case = $this->escapeVal($case); - } - - /** - * Drops the name. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($case){ - $this->_case = ""; - } - - /** - * Stashes the name of the test suite. Starts test coverage - * if enabled. - * @param string $group Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($group, $size){ - $this->_group = $this->escapeVal($group); - if ($this->_cc){ - if (extension_loaded('xdebug')){ - xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); - } - } - } - - /** - * Paints coverage report if enabled. - * @param string $group Name of test or other label. - * @access public - */ - function paintGroupEnd($group){ - $this->_group = ""; - $cc = ""; - if ($this->_cc){ - if (extension_loaded('xdebug')){ - $arrfiles = xdebug_get_code_coverage(); - xdebug_stop_code_coverage(); - $thisdir = dirname(__FILE__); - $thisdirlen = strlen($thisdir); - foreach ($arrfiles as $index=>$file){ - if (substr($index, 0, $thisdirlen)===$thisdir){ - continue; - } - $lcnt = 0; - $ccnt = 0; - foreach ($file as $line){ - if ($line == -2){ - continue; - } - $lcnt++; - if ($line==1){ - $ccnt++; - } - } - if ($lcnt > 0){ - $cc .= round(($ccnt/$lcnt) * 100, 2) . '%'; - }else{ - $cc .= "0.00%"; - } - $cc.= "\t". $index . "\n"; - } - } - } - $this->_listener->write('{status:"coverage",message:"' . - EclipseReporter::escapeVal($cc) . '"}'); - } -} - -/** - * Invoker decorator for Eclipse. Captures output until - * the end of the test. - * @package SimpleTest - * @subpackage Eclipse - */ -class EclipseInvoker extends SimpleInvokerDecorator{ - function EclipseInvoker(&$invoker, &$listener) { - $this->_listener = &$listener; - $this->SimpleInvokerDecorator($invoker); - } - - /** - * Starts output buffering. - * @param string $method Test method to call. - * @access public - */ - function before($method){ - ob_start(); - $this->_invoker->before($method); - } - - /** - * Stops output buffering and send the captured output - * to the listener. - * @param string $method Test method to call. - * @access public - */ - function after($method) { - $this->_invoker->after($method); - $output = ob_get_contents(); - ob_end_clean(); - if ($output !== ""){ - $result = $this->_listener->write('{status:"info",message:"' . - EclipseReporter::escapeVal($output) . '"}'); - } - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/encoding.php b/tests/simpletest/encoding.php deleted file mode 100644 index 112fe3304..000000000 --- a/tests/simpletest/encoding.php +++ /dev/null @@ -1,552 +0,0 @@ -_key = $key; - $this->_value = $value; - } - - /** - * The pair as a single string. - * @return string Encoded pair. - * @access public - */ - function asRequest() { - return urlencode($this->_key) . '=' . urlencode($this->_value); - } - - /** - * The MIME part as a string. - * @return string MIME part encoding. - * @access public - */ - function asMime() { - $part = 'Content-Disposition: form-data; '; - $part .= "name=\"" . $this->_key . "\"\r\n"; - $part .= "\r\n" . $this->_value; - return $part; - } - - /** - * Is this the value we are looking for? - * @param string $key Identifier. - * @return boolean True if matched. - * @access public - */ - function isKey($key) { - return $key == $this->_key; - } - - /** - * Is this the value we are looking for? - * @return string Identifier. - * @access public - */ - function getKey() { - return $this->_key; - } - - /** - * Is this the value we are looking for? - * @return string Content. - * @access public - */ - function getValue() { - return $this->_value; - } -} - -/** - * Single post parameter. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleAttachment { - var $_key; - var $_content; - var $_filename; - - /** - * Stashes the data for rendering later. - * @param string $key Key to add value to. - * @param string $content Raw data. - * @param hash $filename Original filename. - */ - function SimpleAttachment($key, $content, $filename) { - $this->_key = $key; - $this->_content = $content; - $this->_filename = $filename; - } - - /** - * The pair as a single string. - * @return string Encoded pair. - * @access public - */ - function asRequest() { - return ''; - } - - /** - * The MIME part as a string. - * @return string MIME part encoding. - * @access public - */ - function asMime() { - $part = 'Content-Disposition: form-data; '; - $part .= 'name="' . $this->_key . '"; '; - $part .= 'filename="' . $this->_filename . '"'; - $part .= "\r\nContent-Type: " . $this->_deduceMimeType(); - $part .= "\r\n\r\n" . $this->_content; - return $part; - } - - /** - * Attempts to figure out the MIME type from the - * file extension and the content. - * @return string MIME type. - * @access private - */ - function _deduceMimeType() { - if ($this->_isOnlyAscii($this->_content)) { - return 'text/plain'; - } - return 'application/octet-stream'; - } - - /** - * Tests each character is in the range 0-127. - * @param string $ascii String to test. - * @access private - */ - function _isOnlyAscii($ascii) { - for ($i = 0, $length = strlen($ascii); $i < $length; $i++) { - if (ord($ascii[$i]) > 127) { - return false; - } - } - return true; - } - - /** - * Is this the value we are looking for? - * @param string $key Identifier. - * @return boolean True if matched. - * @access public - */ - function isKey($key) { - return $key == $this->_key; - } - - /** - * Is this the value we are looking for? - * @return string Identifier. - * @access public - */ - function getKey() { - return $this->_key; - } - - /** - * Is this the value we are looking for? - * @return string Content. - * @access public - */ - function getValue() { - return $this->_filename; - } -} - -/** - * Bundle of GET/POST parameters. Can include - * repeated parameters. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleEncoding { - var $_request; - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function SimpleEncoding($query = false) { - if (! $query) { - $query = array(); - } - $this->clear(); - $this->merge($query); - } - - /** - * Empties the request of parameters. - * @access public - */ - function clear() { - $this->_request = array(); - } - - /** - * Adds a parameter to the query. - * @param string $key Key to add value to. - * @param string/array $value New data. - * @access public - */ - function add($key, $value) { - if ($value === false) { - return; - } - if (is_array($value)) { - foreach ($value as $item) { - $this->_addPair($key, $item); - } - } else { - $this->_addPair($key, $value); - } - } - - /** - * Adds a new value into the request. - * @param string $key Key to add value to. - * @param string/array $value New data. - * @access private - */ - function _addPair($key, $value) { - $this->_request[] = new SimpleEncodedPair($key, $value); - } - - /** - * Adds a MIME part to the query. Does nothing for a - * form encoded packet. - * @param string $key Key to add value to. - * @param string $content Raw data. - * @param hash $filename Original filename. - * @access public - */ - function attach($key, $content, $filename) { - $this->_request[] = new SimpleAttachment($key, $content, $filename); - } - - /** - * Adds a set of parameters to this query. - * @param array/SimpleQueryString $query Multiple values are - * as lists on a single key. - * @access public - */ - function merge($query) { - if (is_object($query)) { - $this->_request = array_merge($this->_request, $query->getAll()); - } elseif (is_array($query)) { - foreach ($query as $key => $value) { - $this->add($key, $value); - } - } - } - - /** - * Accessor for single value. - * @return string/array False if missing, string - * if present and array if - * multiple entries. - * @access public - */ - function getValue($key) { - $values = array(); - foreach ($this->_request as $pair) { - if ($pair->isKey($key)) { - $values[] = $pair->getValue(); - } - } - if (count($values) == 0) { - return false; - } elseif (count($values) == 1) { - return $values[0]; - } else { - return $values; - } - } - - /** - * Accessor for listing of pairs. - * @return array All pair objects. - * @access public - */ - function getAll() { - return $this->_request; - } - - /** - * Renders the query string as a URL encoded - * request part. - * @return string Part of URL. - * @access protected - */ - function _encode() { - $statements = array(); - foreach ($this->_request as $pair) { - if ($statement = $pair->asRequest()) { - $statements[] = $statement; - } - } - return implode('&', $statements); - } -} - -/** - * Bundle of GET parameters. Can include - * repeated parameters. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleGetEncoding extends SimpleEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function SimpleGetEncoding($query = false) { - $this->SimpleEncoding($query); - } - - /** - * HTTP request method. - * @return string Always GET. - * @access public - */ - function getMethod() { - return 'GET'; - } - - /** - * Writes no extra headers. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeHeadersTo(&$socket) { - } - - /** - * No data is sent to the socket as the data is encoded into - * the URL. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeTo(&$socket) { - } - - /** - * Renders the query string as a URL encoded - * request part for attaching to a URL. - * @return string Part of URL. - * @access public - */ - function asUrlRequest() { - return $this->_encode(); - } -} - -/** - * Bundle of URL parameters for a HEAD request. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHeadEncoding extends SimpleGetEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function SimpleHeadEncoding($query = false) { - $this->SimpleGetEncoding($query); - } - - /** - * HTTP request method. - * @return string Always HEAD. - * @access public - */ - function getMethod() { - return 'HEAD'; - } -} - -/** - * Bundle of POST parameters. Can include - * repeated parameters. - * @package SimpleTest - * @subpackage WebTester - */ -class SimplePostEncoding extends SimpleEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function SimplePostEncoding($query = false) { - if (is_array($query) and $this->hasMoreThanOneLevel($query)) { - $query = $this->rewriteArrayWithMultipleLevels($query); - } - $this->SimpleEncoding($query); - } - - function hasMoreThanOneLevel($query) { - foreach ($query as $key => $value) { - if (is_array($value)) { - return true; - } - } - return false; - } - - function rewriteArrayWithMultipleLevels($query) { - $query_ = array(); - foreach ($query as $key => $value) { - if (is_array($value)) { - foreach ($value as $sub_key => $sub_value) { - $query_[$key."[".$sub_key."]"] = $sub_value; - } - } else { - $query_[$key] = $value; - } - } - if ($this->hasMoreThanOneLevel($query_)) { - $query_ = $this->rewriteArrayWithMultipleLevels($query_); - } - - return $query_; - } - - - /** - * HTTP request method. - * @return string Always POST. - * @access public - */ - function getMethod() { - return 'POST'; - } - - /** - * Dispatches the form headers down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeHeadersTo(&$socket) { - $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); - $socket->write("Content-Type: application/x-www-form-urlencoded\r\n"); - } - - /** - * Dispatches the form data down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeTo(&$socket) { - $socket->write($this->_encode()); - } - - /** - * Renders the query string as a URL encoded - * request part for attaching to a URL. - * @return string Part of URL. - * @access public - */ - function asUrlRequest() { - return ''; - } -} - -/** - * Bundle of POST parameters in the multipart - * format. Can include file uploads. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleMultipartEncoding extends SimplePostEncoding { - var $_boundary; - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function SimpleMultipartEncoding($query = false, $boundary = false) { - $this->SimplePostEncoding($query); - $this->_boundary = ($boundary === false ? uniqid('st') : $boundary); - } - - /** - * Dispatches the form headers down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeHeadersTo(&$socket) { - $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); - $socket->write("Content-Type: multipart/form-data, boundary=" . $this->_boundary . "\r\n"); - } - - /** - * Dispatches the form data down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeTo(&$socket) { - $socket->write($this->_encode()); - } - - /** - * Renders the query string as a URL encoded - * request part. - * @return string Part of URL. - * @access public - */ - function _encode() { - $stream = ''; - foreach ($this->_request as $pair) { - $stream .= "--" . $this->_boundary . "\r\n"; - $stream .= $pair->asMime() . "\r\n"; - } - $stream .= "--" . $this->_boundary . "--\r\n"; - return $stream; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/errors.php b/tests/simpletest/errors.php deleted file mode 100644 index 5a0788511..000000000 --- a/tests/simpletest/errors.php +++ /dev/null @@ -1,288 +0,0 @@ -SimpleInvokerDecorator($invoker); - } - - /** - * Invokes a test method and dispatches any - * untrapped errors. Called back from - * the visiting runner. - * @param string $method Test method to call. - * @access public - */ - function invoke($method) { - $queue = &$this->_createErrorQueue(); - set_error_handler('SimpleTestErrorHandler'); - parent::invoke($method); - restore_error_handler(); - $queue->tally(); - } - - /** - * Wires up the error queue for a single test. - * @return SimpleErrorQueue Queue connected to the test. - * @access private - */ - function &_createErrorQueue() { - $context = &SimpleTest::getContext(); - $test = &$this->getTestCase(); - $queue = &$context->get('SimpleErrorQueue'); - $queue->setTestCase($test); - return $queue; - } -} - -/** - * Error queue used to record trapped - * errors. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleErrorQueue { - var $_queue; - var $_expectation_queue; - var $_test; - var $_using_expect_style = false; - - /** - * Starts with an empty queue. - */ - function SimpleErrorQueue() { - $this->clear(); - } - - /** - * Discards the contents of the error queue. - * @access public - */ - function clear() { - $this->_queue = array(); - $this->_expectation_queue = array(); - } - - /** - * Sets the currently running test case. - * @param SimpleTestCase $test Test case to send messages to. - * @access public - */ - function setTestCase(&$test) { - $this->_test = &$test; - } - - /** - * Sets up an expectation of an error. If this is - * not fulfilled at the end of the test, a failure - * will occour. If the error does happen, then this - * will cancel it out and send a pass message. - * @param SimpleExpectation $expected Expected error match. - * @param string $message Message to display. - * @access public - */ - function expectError($expected, $message) { - $this->_using_expect_style = true; - array_push($this->_expectation_queue, array($expected, $message)); - } - - /** - * Adds an error to the front of the queue. - * @param integer $severity PHP error code. - * @param string $content Text of error. - * @param string $filename File error occoured in. - * @param integer $line Line number of error. - * @access public - */ - function add($severity, $content, $filename, $line) { - $content = str_replace('%', '%%', $content); - if ($this->_using_expect_style) { - $this->_testLatestError($severity, $content, $filename, $line); - } else { - array_push( - $this->_queue, - array($severity, $content, $filename, $line)); - } - } - - /** - * Any errors still in the queue are sent to the test - * case. Any unfulfilled expectations trigger failures. - * @access public - */ - function tally() { - while (list($severity, $message, $file, $line) = $this->extract()) { - $severity = $this->getSeverityAsString($severity); - $this->_test->error($severity, $message, $file, $line); - } - while (list($expected, $message) = $this->_extractExpectation()) { - $this->_test->assert($expected, false, "%s -> Expected error not caught"); - } - } - - /** - * Tests the error against the most recent expected - * error. - * @param integer $severity PHP error code. - * @param string $content Text of error. - * @param string $filename File error occoured in. - * @param integer $line Line number of error. - * @access private - */ - function _testLatestError($severity, $content, $filename, $line) { - if ($expectation = $this->_extractExpectation()) { - list($expected, $message) = $expectation; - $this->_test->assert($expected, $content, sprintf( - $message, - "%s -> PHP error [$content] severity [" . - $this->getSeverityAsString($severity) . - "] in [$filename] line [$line]")); - } else { - $this->_test->error($severity, $content, $filename, $line); - } - } - - /** - * Pulls the earliest error from the queue. - * @return mixed False if none, or a list of error - * information. Elements are: severity - * as the PHP error code, the error message, - * the file with the error, the line number - * and a list of PHP super global arrays. - * @access public - */ - function extract() { - if (count($this->_queue)) { - return array_shift($this->_queue); - } - return false; - } - - /** - * Pulls the earliest expectation from the queue. - * @return SimpleExpectation False if none. - * @access private - */ - function _extractExpectation() { - if (count($this->_expectation_queue)) { - return array_shift($this->_expectation_queue); - } - return false; - } - - /** - * @deprecated - */ - function assertNoErrors($message) { - return $this->_test->assert( - new TrueExpectation(), - count($this->_queue) == 0, - sprintf($message, 'Should be no errors')); - } - - /** - * @deprecated - */ - function assertError($expected, $message) { - if (count($this->_queue) == 0) { - $this->_test->fail(sprintf($message, 'Expected error not found')); - return false; - } - list($severity, $content, $file, $line) = $this->extract(); - $severity = $this->getSeverityAsString($severity); - return $this->_test->assert( - $expected, - $content, - sprintf($message, "Expected PHP error [$content] severity [$severity] in [$file] line [$line]")); - } - - /** - * Converts an error code into it's string - * representation. - * @param $severity PHP integer error code. - * @return String version of error code. - * @access public - * @static - */ - function getSeverityAsString($severity) { - static $map = array( - E_STRICT => 'E_STRICT', - E_ERROR => 'E_ERROR', - E_WARNING => 'E_WARNING', - E_PARSE => 'E_PARSE', - E_NOTICE => 'E_NOTICE', - E_CORE_ERROR => 'E_CORE_ERROR', - E_CORE_WARNING => 'E_CORE_WARNING', - E_COMPILE_ERROR => 'E_COMPILE_ERROR', - E_COMPILE_WARNING => 'E_COMPILE_WARNING', - E_USER_ERROR => 'E_USER_ERROR', - E_USER_WARNING => 'E_USER_WARNING', - E_USER_NOTICE => 'E_USER_NOTICE'); - if (defined('E_RECOVERABLE_ERROR')) { - $map[E_RECOVERABLE_ERROR] = 'E_RECOVERABLE_ERROR'; - } - if (defined('E_DEPRECATED')) { - $map[E_DEPRECATED] = 'E_DEPRECATED'; - } - return $map[$severity]; - } -} - -/** - * Error handler that simply stashes any errors into the global - * error queue. Simulates the existing behaviour with respect to - * logging errors, but this feature may be removed in future. - * @param $severity PHP error code. - * @param $message Text of error. - * @param $filename File error occoured in. - * @param $line Line number of error. - * @param $super_globals Hash of PHP super global arrays. - * @static - * @access public - */ -function SimpleTestErrorHandler($severity, $message, $filename = null, $line = null, $super_globals = null, $mask = null) { - $severity = $severity & error_reporting(); - if ($severity) { - restore_error_handler(); - if (ini_get('log_errors')) { - $label = SimpleErrorQueue::getSeverityAsString($severity); - error_log("$label: $message in $filename on line $line"); - } - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - $queue->add($severity, $message, $filename, $line); - set_error_handler('SimpleTestErrorHandler'); - } - return true; -} -?> \ No newline at end of file diff --git a/tests/simpletest/exceptions.php b/tests/simpletest/exceptions.php deleted file mode 100644 index c19a04e3a..000000000 --- a/tests/simpletest/exceptions.php +++ /dev/null @@ -1,198 +0,0 @@ -SimpleInvokerDecorator($invoker); - } - - /** - * Invokes a test method whilst trapping expected - * exceptions. Any left over unthrown exceptions - * are then reported as failures. - * @param string $method Test method to call. - */ - function invoke($method) { - $trap = SimpleTest::getContext()->get('SimpleExceptionTrap'); - $trap->clear(); - try { - $has_thrown = false; - parent::invoke($method); - } catch (Exception $exception) { - $has_thrown = true; - if (! $trap->isExpected($this->getTestCase(), $exception)) { - $this->getTestCase()->exception($exception); - } - $trap->clear(); - } - if ($message = $trap->getOutstanding()) { - $this->getTestCase()->fail($message); - } - if ($has_thrown) { - try { - parent::getTestCase()->tearDown(); - } catch (Exception $e) { } - } - } -} - -/** - * Tests exceptions either by type or the exact - * exception. This could be improved to accept - * a pattern expectation to test the error - * message, but that will have to come later. - * @package SimpleTest - * @subpackage UnitTester - */ -class ExceptionExpectation extends SimpleExpectation { - private $expected; - - /** - * Sets up the conditions to test against. - * If the expected value is a string, then - * it will act as a test of the class name. - * An exception as the comparison will - * trigger an identical match. Writing this - * down now makes it look doubly dumb. I hope - * come up with a better scheme later. - * @param mixed $expected A class name or an actual - * exception to compare with. - * @param string $message Message to display. - */ - function __construct($expected, $message = '%s') { - $this->expected = $expected; - parent::__construct($message); - } - - /** - * Carry out the test. - * @param Exception $compare Value to check. - * @return boolean True if matched. - */ - function test($compare) { - if (is_string($this->expected)) { - return ($compare instanceof $this->expected); - } - if (get_class($compare) != get_class($this->expected)) { - return false; - } - return $compare->getMessage() == $this->expected->getMessage(); - } - - /** - * Create the message to display describing the test. - * @param Exception $compare Exception to match. - * @return string Final message. - */ - function testMessage($compare) { - if (is_string($this->expected)) { - return "Exception [" . $this->describeException($compare) . - "] should be type [" . $this->expected . "]"; - } - return "Exception [" . $this->describeException($compare) . - "] should match [" . - $this->describeException($this->expected) . "]"; - } - - /** - * Summary of an Exception object. - * @param Exception $compare Exception to describe. - * @return string Text description. - */ - protected function describeException($exception) { - return get_class($exception) . ": " . $exception->getMessage(); - } -} - -/** - * Stores expected exceptions for when they - * get thrown. Saves the irritating try...catch - * block. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleExceptionTrap { - private $expected; - private $message; - - /** - * Clears down the queue ready for action. - */ - function __construct() { - $this->clear(); - } - - /** - * Sets up an expectation of an exception. - * This has the effect of intercepting an - * exception that matches. - * @param SimpleExpectation $expected Expected exception to match. - * @param string $message Message to display. - * @access public - */ - function expectException($expected = false, $message = '%s') { - if ($expected === false) { - $expected = new AnythingExpectation(); - } - if (! SimpleExpectation::isExpectation($expected)) { - $expected = new ExceptionExpectation($expected); - } - $this->expected = $expected; - $this->message = $message; - } - - /** - * Compares the expected exception with any - * in the queue. Issues a pass or fail and - * returns the state of the test. - * @param SimpleTestCase $test Test case to send messages to. - * @param Exception $exception Exception to compare. - * @return boolean False on no match. - */ - function isExpected($test, $exception) { - if ($this->expected) { - return $test->assert($this->expected, $exception, $this->message); - } - return false; - } - - /** - * Tests for any left over exception. - * @return string/false The failure message or false if none. - */ - function getOutstanding() { - return sprintf($this->message, 'Failed to trap exception'); - } - - /** - * Discards the contents of the error queue. - */ - function clear() { - $this->expected = false; - $this->message = false; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/expectation.php b/tests/simpletest/expectation.php deleted file mode 100644 index 194afd5c7..000000000 --- a/tests/simpletest/expectation.php +++ /dev/null @@ -1,895 +0,0 @@ -_message = $message; - } - - /** - * Tests the expectation. True if correct. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - * @abstract - */ - function test($compare) { - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - * @abstract - */ - function testMessage($compare) { - } - - /** - * Overlays the generated message onto the stored user - * message. An additional message can be interjected. - * @param mixed $compare Comparison value. - * @param SimpleDumper $dumper For formatting the results. - * @return string Description of success - * or failure. - * @access public - */ - function overlayMessage($compare, $dumper) { - $this->_dumper = $dumper; - return sprintf($this->_message, $this->testMessage($compare)); - } - - /** - * Accessor for the dumper. - * @return SimpleDumper Current value dumper. - * @access protected - */ - function &_getDumper() { - if (! $this->_dumper) { - $dumper = &new SimpleDumper(); - return $dumper; - } - return $this->_dumper; - } - - /** - * Test to see if a value is an expectation object. - * A useful utility method. - * @param mixed $expectation Hopefully an Epectation - * class. - * @return boolean True if descended from - * this class. - * @access public - * @static - */ - function isExpectation($expectation) { - return is_object($expectation) && - SimpleTestCompatibility::isA($expectation, 'SimpleExpectation'); - } -} - -/** - * A wildcard expectation always matches. - * @package SimpleTest - * @subpackage MockObjects - */ -class AnythingExpectation extends SimpleExpectation { - - /** - * Tests the expectation. Always true. - * @param mixed $compare Ignored. - * @return boolean True. - * @access public - */ - function test($compare) { - return true; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - return 'Anything always matches [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * An expectation that never matches. - * @package SimpleTest - * @subpackage MockObjects - */ -class FailedExpectation extends SimpleExpectation { - - /** - * Tests the expectation. Always false. - * @param mixed $compare Ignored. - * @return boolean True. - * @access public - */ - function test($compare) { - return false; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - return 'Failed expectation never matches [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * An expectation that passes on boolean true. - * @package SimpleTest - * @subpackage MockObjects - */ -class TrueExpectation extends SimpleExpectation { - - /** - * Tests the expectation. - * @param mixed $compare Should be true. - * @return boolean True on match. - * @access public - */ - function test($compare) { - return (boolean)$compare; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - return 'Expected true, got [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * An expectation that passes on boolean false. - * @package SimpleTest - * @subpackage MockObjects - */ -class FalseExpectation extends SimpleExpectation { - - /** - * Tests the expectation. - * @param mixed $compare Should be false. - * @return boolean True on match. - * @access public - */ - function test($compare) { - return ! (boolean)$compare; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - return 'Expected false, got [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * Test for equality. - * @package SimpleTest - * @subpackage UnitTester - */ -class EqualExpectation extends SimpleExpectation { - var $_value; - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function EqualExpectation($value, $message = '%s') { - $this->SimpleExpectation($message); - $this->_value = $value; - } - - /** - * Tests the expectation. True if it matches the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (($this->_value == $compare) && ($compare == $this->_value)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]"; - } else { - return "Equal expectation fails " . - $this->_dumper->describeDifference($this->_value, $compare); - } - } - - /** - * Accessor for comparison value. - * @return mixed Held value to compare with. - * @access protected - */ - function _getValue() { - return $this->_value; - } -} - -/** - * Test for inequality. - * @package SimpleTest - * @subpackage UnitTester - */ -class NotEqualExpectation extends EqualExpectation { - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function NotEqualExpectation($value, $message = '%s') { - $this->EqualExpectation($value, $message); - } - - /** - * Tests the expectation. True if it differs from the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - if ($this->test($compare)) { - return "Not equal expectation passes " . - $dumper->describeDifference($this->_getValue(), $compare); - } else { - return "Not equal expectation fails [" . - $dumper->describeValue($this->_getValue()) . - "] matches"; - } - } -} - -/** - * Test for being within a range. - * @package SimpleTest - * @subpackage UnitTester - */ -class WithinMarginExpectation extends SimpleExpectation { - var $_upper; - var $_lower; - - /** - * Sets the value to compare against and the fuzziness of - * the match. Used for comparing floating point values. - * @param mixed $value Test value to match. - * @param mixed $margin Fuzziness of match. - * @param string $message Customised message on failure. - * @access public - */ - function WithinMarginExpectation($value, $margin, $message = '%s') { - $this->SimpleExpectation($message); - $this->_upper = $value + $margin; - $this->_lower = $value - $margin; - } - - /** - * Tests the expectation. True if it matches the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (($compare <= $this->_upper) && ($compare >= $this->_lower)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return $this->_withinMessage($compare); - } else { - return $this->_outsideMessage($compare); - } - } - - /** - * Creates a the message for being within the range. - * @param mixed $compare Value being tested. - * @access private - */ - function _withinMessage($compare) { - return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" . - $this->_dumper->describeValue($this->_upper) . "]"; - } - - /** - * Creates a the message for being within the range. - * @param mixed $compare Value being tested. - * @access private - */ - function _outsideMessage($compare) { - if ($compare > $this->_upper) { - return "Outside expectation " . - $this->_dumper->describeDifference($compare, $this->_upper); - } else { - return "Outside expectation " . - $this->_dumper->describeDifference($compare, $this->_lower); - } - } -} - -/** - * Test for being outside of a range. - * @package SimpleTest - * @subpackage UnitTester - */ -class OutsideMarginExpectation extends WithinMarginExpectation { - - /** - * Sets the value to compare against and the fuzziness of - * the match. Used for comparing floating point values. - * @param mixed $value Test value to not match. - * @param mixed $margin Fuzziness of match. - * @param string $message Customised message on failure. - * @access public - */ - function OutsideMarginExpectation($value, $margin, $message = '%s') { - $this->WithinMarginExpectation($value, $margin, $message); - } - - /** - * Tests the expectation. True if it matches the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if (! $this->test($compare)) { - return $this->_withinMessage($compare); - } else { - return $this->_outsideMessage($compare); - } - } -} - -/** - * Test for reference. - * @package SimpleTest - * @subpackage UnitTester - */ -class ReferenceExpectation extends SimpleExpectation { - var $_value; - - /** - * Sets the reference value to compare against. - * @param mixed $value Test reference to match. - * @param string $message Customised message on failure. - * @access public - */ - function ReferenceExpectation(&$value, $message = '%s') { - $this->SimpleExpectation($message); - $this->_value =& $value; - } - - /** - * Tests the expectation. True if it exactly - * references the held value. - * @param mixed $compare Comparison reference. - * @return boolean True if correct. - * @access public - */ - function test(&$compare) { - return SimpleTestCompatibility::isReference($this->_value, $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return "Reference expectation [" . $this->_dumper->describeValue($this->_value) . "]"; - } else { - return "Reference expectation fails " . - $this->_dumper->describeDifference($this->_value, $compare); - } - } - - function _getValue() { - return $this->_value; - } -} - -/** - * Test for identity. - * @package SimpleTest - * @subpackage UnitTester - */ -class IdenticalExpectation extends EqualExpectation { - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function IdenticalExpectation($value, $message = '%s') { - $this->EqualExpectation($value, $message); - } - - /** - * Tests the expectation. True if it exactly - * matches the held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return SimpleTestCompatibility::isIdentical($this->_getValue(), $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - if ($this->test($compare)) { - return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . "]"; - } else { - return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . - "] fails with [" . - $dumper->describeValue($compare) . "] " . - $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); - } - } -} - -/** - * Test for non-identity. - * @package SimpleTest - * @subpackage UnitTester - */ -class NotIdenticalExpectation extends IdenticalExpectation { - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function NotIdenticalExpectation($value, $message = '%s') { - $this->IdenticalExpectation($value, $message); - } - - /** - * Tests the expectation. True if it differs from the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - if ($this->test($compare)) { - return "Not identical expectation passes " . - $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); - } else { - return "Not identical expectation [" . $dumper->describeValue($this->_getValue()) . "] matches"; - } - } -} - -/** - * Test for a pattern using Perl regex rules. - * @package SimpleTest - * @subpackage UnitTester - */ -class PatternExpectation extends SimpleExpectation { - var $_pattern; - - /** - * Sets the value to compare against. - * @param string $pattern Pattern to search for. - * @param string $message Customised message on failure. - * @access public - */ - function PatternExpectation($pattern, $message = '%s') { - $this->SimpleExpectation($message); - $this->_pattern = $pattern; - } - - /** - * Accessor for the pattern. - * @return string Perl regex as string. - * @access protected - */ - function _getPattern() { - return $this->_pattern; - } - - /** - * Tests the expectation. True if the Perl regex - * matches the comparison value. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (boolean)preg_match($this->_getPattern(), $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return $this->_describePatternMatch($this->_getPattern(), $compare); - } else { - $dumper = &$this->_getDumper(); - return "Pattern [" . $this->_getPattern() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } - } - - /** - * Describes a pattern match including the string - * found and it's position. - * @param string $pattern Regex to match against. - * @param string $subject Subject to search. - * @access protected - */ - function _describePatternMatch($pattern, $subject) { - preg_match($pattern, $subject, $matches); - $position = strpos($subject, $matches[0]); - $dumper = $this->_getDumper(); - return "Pattern [$pattern] detected at character [$position] in [" . - $dumper->describeValue($subject) . "] as [" . - $matches[0] . "] in region [" . - $dumper->clipString($subject, 100, $position) . "]"; - } -} - -/** - * @package SimpleTest - * @subpackage UnitTester - * @deprecated - */ -class WantedPatternExpectation extends PatternExpectation { -} - -/** - * Fail if a pattern is detected within the - * comparison. - * @package SimpleTest - * @subpackage UnitTester - */ -class NoPatternExpectation extends PatternExpectation { - - /** - * Sets the reject pattern - * @param string $pattern Pattern to search for. - * @param string $message Customised message on failure. - * @access public - */ - function NoPatternExpectation($pattern, $message = '%s') { - $this->PatternExpectation($pattern, $message); - } - - /** - * Tests the expectation. False if the Perl regex - * matches the comparison value. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param string $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - $dumper = &$this->_getDumper(); - return "Pattern [" . $this->_getPattern() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } else { - return $this->_describePatternMatch($this->_getPattern(), $compare); - } - } -} - -/** - * @package SimpleTest - * @subpackage UnitTester - * @deprecated - */ -class UnwantedPatternExpectation extends NoPatternExpectation { -} - -/** - * Tests either type or class name if it's an object. - * @package SimpleTest - * @subpackage UnitTester - */ -class IsAExpectation extends SimpleExpectation { - var $_type; - - /** - * Sets the type to compare with. - * @param string $type Type or class name. - * @param string $message Customised message on failure. - * @access public - */ - function IsAExpectation($type, $message = '%s') { - $this->SimpleExpectation($message); - $this->_type = $type; - } - - /** - * Accessor for type to check against. - * @return string Type or class name. - * @access protected - */ - function _getType() { - return $this->_type; - } - - /** - * Tests the expectation. True if the type or - * class matches the string value. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - if (is_object($compare)) { - return SimpleTestCompatibility::isA($compare, $this->_type); - } else { - return (strtolower(gettype($compare)) == $this->_canonicalType($this->_type)); - } - } - - /** - * Coerces type name into a gettype() match. - * @param string $type User type. - * @return string Simpler type. - * @access private - */ - function _canonicalType($type) { - $type = strtolower($type); - $map = array( - 'bool' => 'boolean', - 'float' => 'double', - 'real' => 'double', - 'int' => 'integer'); - if (isset($map[$type])) { - $type = $map[$type]; - } - return $type; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - return "Value [" . $dumper->describeValue($compare) . - "] should be type [" . $this->_type . "]"; - } -} - -/** - * Tests either type or class name if it's an object. - * Will succeed if the type does not match. - * @package SimpleTest - * @subpackage UnitTester - */ -class NotAExpectation extends IsAExpectation { - var $_type; - - /** - * Sets the type to compare with. - * @param string $type Type or class name. - * @param string $message Customised message on failure. - * @access public - */ - function NotAExpectation($type, $message = '%s') { - $this->IsAExpectation($type, $message); - } - - /** - * Tests the expectation. False if the type or - * class matches the string value. - * @param string $compare Comparison value. - * @return boolean True if different. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - return "Value [" . $dumper->describeValue($compare) . - "] should not be type [" . $this->_getType() . "]"; - } -} - -/** - * Tests for existance of a method in an object - * @package SimpleTest - * @subpackage UnitTester - */ -class MethodExistsExpectation extends SimpleExpectation { - var $_method; - - /** - * Sets the value to compare against. - * @param string $method Method to check. - * @param string $message Customised message on failure. - * @access public - * @return void - */ - function MethodExistsExpectation($method, $message = '%s') { - $this->SimpleExpectation($message); - $this->_method = &$method; - } - - /** - * Tests the expectation. True if the method exists in the test object. - * @param string $compare Comparison method name. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (boolean)(is_object($compare) && method_exists($compare, $this->_method)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - if (! is_object($compare)) { - return 'No method on non-object [' . $dumper->describeValue($compare) . ']'; - } - $method = $this->_method; - return "Object [" . $dumper->describeValue($compare) . - "] should contain method [$method]"; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/extensions/pear_test_case.php b/tests/simpletest/extensions/pear_test_case.php deleted file mode 100644 index f5e5a7b85..000000000 --- a/tests/simpletest/extensions/pear_test_case.php +++ /dev/null @@ -1,198 +0,0 @@ -SimpleTestCase($label); - $this->_loosely_typed = false; - } - - /** - * Will test straight equality if set to loose - * typing, or identity if not. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEquals($first, $second, $message = "%s", $delta = 0) { - if ($this->_loosely_typed) { - $expectation = &new EqualExpectation($first); - } else { - $expectation = &new IdenticalExpectation($first); - } - $this->assert($expectation, $second, $message); - } - - /** - * Passes if the value tested is not null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNotNull($value, $message = "%s") { - parent::assert(new TrueExpectation(), isset($value), $message); - } - - /** - * Passes if the value tested is null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNull($value, $message = "%s") { - parent::assert(new TrueExpectation(), !isset($value), $message); - } - - /** - * In PHP5 the identity test tests for the same - * object. This is a reference test in PHP4. - * @param $first First object handle. - * @param $second Hopefully the same handle. - * @param $message Message to display. - * @public - */ - function assertSame(&$first, &$second, $message = "%s") { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should reference the same object"); - return $this->assert( - new TrueExpectation(), - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * In PHP5 the identity test tests for the same - * object. This is a reference test in PHP4. - * @param $first First object handle. - * @param $second Hopefully a different handle. - * @param $message Message to display. - * @public - */ - function assertNotSame(&$first, &$second, $message = "%s") { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should not be the same object"); - return $this->assert( - new falseExpectation(), - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Sends pass if the test condition resolves true, - * a fail otherwise. - * @param $condition Condition to test true. - * @param $message Message to display. - * @public - */ - function assertTrue($condition, $message = "%s") { - parent::assert(new TrueExpectation(), $condition, $message); - } - - /** - * Sends pass if the test condition resolves false, - * a fail otherwise. - * @param $condition Condition to test false. - * @param $message Message to display. - * @public - */ - function assertFalse($condition, $message = "%s") { - parent::assert(new FalseExpectation(), $condition, $message); - } - - /** - * Tests a regex match. Needs refactoring. - * @param $pattern Regex to match. - * @param $subject String to search in. - * @param $message Message to display. - * @public - */ - function assertRegExp($pattern, $subject, $message = "%s") { - $this->assert(new PatternExpectation($pattern), $subject, $message); - } - - /** - * Tests the type of a value. - * @param $value Value to take type of. - * @param $type Hoped for type. - * @param $message Message to display. - * @public - */ - function assertType($value, $type, $message = "%s") { - parent::assert(new TrueExpectation(), gettype($value) == strtolower($type), $message); - } - - /** - * Sets equality operation to act as a simple equal - * comparison only, allowing a broader range of - * matches. - * @param $loosely_typed True for broader comparison. - * @public - */ - function setLooselyTyped($loosely_typed) { - $this->_loosely_typed = $loosely_typed; - } - - /** - * For progress indication during - * a test amongst other things. - * @return Usually one. - * @public - */ - function countTestCases() { - return $this->getSize(); - } - - /** - * Accessor for name, normally just the class - * name. - * @public - */ - function getName() { - return $this->getLabel(); - } - - /** - * Does nothing. For compatibility only. - * @param $name Dummy - * @public - */ - function setName($name) { - } - } -?> diff --git a/tests/simpletest/extensions/phpunit_test_case.php b/tests/simpletest/extensions/phpunit_test_case.php deleted file mode 100644 index e038a4967..000000000 --- a/tests/simpletest/extensions/phpunit_test_case.php +++ /dev/null @@ -1,96 +0,0 @@ -SimpleTestCase($label); - } - - /** - * Sends pass if the test condition resolves true, - * a fail otherwise. - * @param $condition Condition to test true. - * @param $message Message to display. - * @public - */ - function assert($condition, $message = false) { - parent::assert(new TrueExpectation(), $condition, $message); - } - - /** - * Will test straight equality if set to loose - * typing, or identity if not. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEquals($first, $second, $message = false) { - parent::assert(new EqualExpectation($first), $second, $message); - } - - /** - * Simple string equality. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEqualsMultilineStrings($first, $second, $message = false) { - parent::assert(new EqualExpectation($first), $second, $message); - } - - /** - * Tests a regex match. - * @param $pattern Regex to match. - * @param $subject String to search in. - * @param $message Message to display. - * @public - */ - function assertRegexp($pattern, $subject, $message = false) { - parent::assert(new PatternExpectation($pattern), $subject, $message); - } - - /** - * Sends an error which we interpret as a fail - * with a different message for compatibility. - * @param $message Message to display. - * @public - */ - function error($message) { - parent::fail("Error triggered [$message]"); - } - - /** - * Accessor for name. - * @public - */ - function name() { - return $this->getLabel(); - } - } -?> diff --git a/tests/simpletest/extensions/testdox.php b/tests/simpletest/extensions/testdox.php deleted file mode 100644 index 7db7c872c..000000000 --- a/tests/simpletest/extensions/testdox.php +++ /dev/null @@ -1,42 +0,0 @@ -_test_case_pattern = empty($test_case_pattern) ? '/^(.*)$/' : $test_case_pattern; - } - - function paintCaseStart($test_name) { - preg_match($this->_test_case_pattern, $test_name, $matches); - if (!empty($matches[1])) { - echo $matches[1] . "\n"; - } else { - echo $test_name . "\n"; - } - } - - function paintCaseEnd() { - echo "\n"; - } - - function paintMethodStart($test_name) { - if (!preg_match('/^test(.*)$/i', $test_name, $matches)) { - return; - } - $test_name = $matches[1]; - - $test_name = preg_replace('/([A-Z])([A-Z])/', '$1 $2', $test_name); - echo '- ' . strtolower(preg_replace('/([a-zA-Z])([A-Z0-9])/', '$1 $2', $test_name)); - } - - function paintMethodEnd() { - echo "\n"; - } - - function paintFail() { - echo " [FAILED]"; - } -} diff --git a/tests/simpletest/extensions/testdox/test.php b/tests/simpletest/extensions/testdox/test.php deleted file mode 100644 index 82c5b7da8..000000000 --- a/tests/simpletest/extensions/testdox/test.php +++ /dev/null @@ -1,108 +0,0 @@ -assertIsA($dox, 'SimpleScorer'); - $this->assertIsA($dox, 'SimpleReporter'); - } - - function testOutputsNameOfTestCase() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintCaseStart('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertWantedPattern('/^TestDoxReporter/', $buffer); - } - - function testOutputOfTestCaseNameFilteredByConstructParameter() { - $dox = new TestDoxReporter('/^(.*)Test$/'); - ob_start(); - $dox->paintCaseStart('SomeGreatWidgetTest'); - $buffer = ob_get_clean(); - $this->assertWantedPattern('/^SomeGreatWidget/', $buffer); - } - - function testIfTest_case_patternIsEmptyAssumeEverythingMatches() { - $dox = new TestDoxReporter(''); - ob_start(); - $dox->paintCaseStart('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertWantedPattern('/^TestOfTestDoxReporter/', $buffer); - } - - function testEmptyLineInsertedWhenCaseEnds() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintCaseEnd('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertEqual("\n", $buffer); - } - - function testPaintsTestMethodInTestDoxFormat() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('testSomeGreatTestCase'); - $buffer = ob_get_clean(); - $this->assertEqual("- some great test case", $buffer); - unset($buffer); - - $random = rand(100, 200); - ob_start(); - $dox->paintMethodStart("testRandomNumberIs{$random}"); - $buffer = ob_get_clean(); - $this->assertEqual("- random number is {$random}", $buffer); - } - - function testDoesNotOutputAnythingOnNoneTestMethods() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('nonMatchingMethod'); - $buffer = ob_get_clean(); - $this->assertEqual('', $buffer); - } - - function testPaintMethodAddLineBreak() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodEnd('someMethod'); - $buffer = ob_get_clean(); - $this->assertEqual("\n", $buffer); - $this->assertNoErrors(); - } - - function testProperlySpacesSingleLettersInMethodName() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('testAVerySimpleAgainAVerySimpleMethod'); - $buffer = ob_get_clean(); - $this->assertEqual('- a very simple again a very simple method', $buffer); - } - - function testOnFailureThisPrintsFailureNotice() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintFail(); - $buffer = ob_get_clean(); - $this->assertEqual(' [FAILED]', $buffer); - } - - function testWhenMatchingMethodNamesTestPrefixIsCaseInsensitive() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('TESTSupportsAllUppercaseTestPrefixEvenThoughIDoNotKnowWhyYouWouldDoThat'); - $buffer = ob_get_clean(); - $this->assertEqual( - '- supports all uppercase test prefix even though i do not know why you would do that', - $buffer - ); - } -} - diff --git a/tests/simpletest/form.php b/tests/simpletest/form.php deleted file mode 100644 index cbef6636d..000000000 --- a/tests/simpletest/form.php +++ /dev/null @@ -1,355 +0,0 @@ -_method = $tag->getAttribute('method'); - $this->_action = $this->_createAction($tag->getAttribute('action'), $page); - $this->_encoding = $this->_setEncodingClass($tag); - $this->_default_target = false; - $this->_id = $tag->getAttribute('id'); - $this->_buttons = array(); - $this->_images = array(); - $this->_widgets = array(); - $this->_radios = array(); - $this->_checkboxes = array(); - } - - /** - * Creates the request packet to be sent by the form. - * @param SimpleTag $tag Form tag to read. - * @return string Packet class. - * @access private - */ - function _setEncodingClass($tag) { - if (strtolower($tag->getAttribute('method')) == 'post') { - if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') { - return 'SimpleMultipartEncoding'; - } - return 'SimplePostEncoding'; - } - return 'SimpleGetEncoding'; - } - - /** - * Sets the frame target within a frameset. - * @param string $frame Name of frame. - * @access public - */ - function setDefaultTarget($frame) { - $this->_default_target = $frame; - } - - /** - * Accessor for method of form submission. - * @return string Either get or post. - * @access public - */ - function getMethod() { - return ($this->_method ? strtolower($this->_method) : 'get'); - } - - /** - * Combined action attribute with current location - * to get an absolute form target. - * @param string $action Action attribute from form tag. - * @param SimpleUrl $base Page location. - * @return SimpleUrl Absolute form target. - */ - function _createAction($action, &$page) { - if (($action === '') || ($action === false)) { - return $page->expandUrl($page->getUrl()); - } - return $page->expandUrl(new SimpleUrl($action));; - } - - /** - * Absolute URL of the target. - * @return SimpleUrl URL target. - * @access public - */ - function getAction() { - $url = $this->_action; - if ($this->_default_target && ! $url->getTarget()) { - $url->setTarget($this->_default_target); - } - return $url; - } - - /** - * Creates the encoding for the current values in the - * form. - * @return SimpleFormEncoding Request to submit. - * @access private - */ - function _encode() { - $class = $this->_encoding; - $encoding = new $class(); - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - $this->_widgets[$i]->write($encoding); - } - return $encoding; - } - - /** - * ID field of form for unique identification. - * @return string Unique tag ID. - * @access public - */ - function getId() { - return $this->_id; - } - - /** - * Adds a tag contents to the form. - * @param SimpleWidget $tag Input tag to add. - * @access public - */ - function addWidget(&$tag) { - if (strtolower($tag->getAttribute('type')) == 'submit') { - $this->_buttons[] = &$tag; - } elseif (strtolower($tag->getAttribute('type')) == 'image') { - $this->_images[] = &$tag; - } elseif ($tag->getName()) { - $this->_setWidget($tag); - } - } - - /** - * Sets the widget into the form, grouping radio - * buttons if any. - * @param SimpleWidget $tag Incoming form control. - * @access private - */ - function _setWidget(&$tag) { - if (strtolower($tag->getAttribute('type')) == 'radio') { - $this->_addRadioButton($tag); - } elseif (strtolower($tag->getAttribute('type')) == 'checkbox') { - $this->_addCheckbox($tag); - } else { - $this->_widgets[] = &$tag; - } - } - - /** - * Adds a radio button, building a group if necessary. - * @param SimpleRadioButtonTag $tag Incoming form control. - * @access private - */ - function _addRadioButton(&$tag) { - if (! isset($this->_radios[$tag->getName()])) { - $this->_widgets[] = &new SimpleRadioGroup(); - $this->_radios[$tag->getName()] = count($this->_widgets) - 1; - } - $this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag); - } - - /** - * Adds a checkbox, making it a group on a repeated name. - * @param SimpleCheckboxTag $tag Incoming form control. - * @access private - */ - function _addCheckbox(&$tag) { - if (! isset($this->_checkboxes[$tag->getName()])) { - $this->_widgets[] = &$tag; - $this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1; - } else { - $index = $this->_checkboxes[$tag->getName()]; - if (! SimpleTestCompatibility::isA($this->_widgets[$index], 'SimpleCheckboxGroup')) { - $previous = &$this->_widgets[$index]; - $this->_widgets[$index] = &new SimpleCheckboxGroup(); - $this->_widgets[$index]->addWidget($previous); - } - $this->_widgets[$index]->addWidget($tag); - } - } - - /** - * Extracts current value from form. - * @param SimpleSelector $selector Criteria to apply. - * @return string/array Value(s) as string or null - * if not set. - * @access public - */ - function getValue($selector) { - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($selector->isMatch($this->_widgets[$i])) { - return $this->_widgets[$i]->getValue(); - } - } - foreach ($this->_buttons as $button) { - if ($selector->isMatch($button)) { - return $button->getValue(); - } - } - return null; - } - - /** - * Sets a widget value within the form. - * @param SimpleSelector $selector Criteria to apply. - * @param string $value Value to input into the widget. - * @return boolean True if value is legal, false - * otherwise. If the field is not - * present, nothing will be set. - * @access public - */ - function setField($selector, $value, $position=false) { - $success = false; - $_position = 0; - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($selector->isMatch($this->_widgets[$i])) { - $_position++; - if ($position === false or $_position === (int)$position) { - if ($this->_widgets[$i]->setValue($value)) { - $success = true; - } - } - } - } - return $success; - } - - /** - * Used by the page object to set widgets labels to - * external label tags. - * @param SimpleSelector $selector Criteria to apply. - * @access public - */ - function attachLabelBySelector($selector, $label) { - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($selector->isMatch($this->_widgets[$i])) { - if (method_exists($this->_widgets[$i], 'setLabel')) { - $this->_widgets[$i]->setLabel($label); - return; - } - } - } - } - - /** - * Test to see if a form has a submit button. - * @param SimpleSelector $selector Criteria to apply. - * @return boolean True if present. - * @access public - */ - function hasSubmit($selector) { - foreach ($this->_buttons as $button) { - if ($selector->isMatch($button)) { - return true; - } - } - return false; - } - - /** - * Test to see if a form has an image control. - * @param SimpleSelector $selector Criteria to apply. - * @return boolean True if present. - * @access public - */ - function hasImage($selector) { - foreach ($this->_images as $image) { - if ($selector->isMatch($image)) { - return true; - } - } - return false; - } - - /** - * Gets the submit values for a selected button. - * @param SimpleSelector $selector Criteria to apply. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button - * in the form. - * @access public - */ - function submitButton($selector, $additional = false) { - $additional = $additional ? $additional : array(); - foreach ($this->_buttons as $button) { - if ($selector->isMatch($button)) { - $encoding = $this->_encode(); - $button->write($encoding); - if ($additional) { - $encoding->merge($additional); - } - return $encoding; - } - } - return false; - } - - /** - * Gets the submit values for an image. - * @param SimpleSelector $selector Criteria to apply. - * @param integer $x X-coordinate of click. - * @param integer $y Y-coordinate of click. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitImage($selector, $x, $y, $additional = false) { - $additional = $additional ? $additional : array(); - foreach ($this->_images as $image) { - if ($selector->isMatch($image)) { - $encoding = $this->_encode(); - $image->write($encoding, $x, $y); - if ($additional) { - $encoding->merge($additional); - } - return $encoding; - } - } - return false; - } - - /** - * Simply submits the form without the submit button - * value. Used when there is only one button or it - * is unimportant. - * @return hash Submitted values. - * @access public - */ - function submit() { - return $this->_encode(); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/frames.php b/tests/simpletest/frames.php deleted file mode 100644 index ec098df9e..000000000 --- a/tests/simpletest/frames.php +++ /dev/null @@ -1,596 +0,0 @@ -_frameset = &$page; - $this->_frames = array(); - $this->_focus = false; - $this->_names = array(); - } - - /** - * Adds a parsed page to the frameset. - * @param SimplePage $page Frame page. - * @param string $name Name of frame in frameset. - * @access public - */ - function addFrame(&$page, $name = false) { - $this->_frames[] = &$page; - if ($name) { - $this->_names[$name] = count($this->_frames) - 1; - } - } - - /** - * Replaces existing frame with another. If the - * frame is nested, then the call is passed down - * one level. - * @param array $path Path of frame in frameset. - * @param SimplePage $page Frame source. - * @access public - */ - function setFrame($path, &$page) { - $name = array_shift($path); - if (isset($this->_names[$name])) { - $index = $this->_names[$name]; - } else { - $index = $name - 1; - } - if (count($path) == 0) { - $this->_frames[$index] = &$page; - return; - } - $this->_frames[$index]->setFrame($path, $page); - } - - /** - * Accessor for current frame focus. Will be - * false if no frame has focus. Will have the nested - * frame focus if any. - * @return array Labels or indexes of nested frames. - * @access public - */ - function getFrameFocus() { - if ($this->_focus === false) { - return array(); - } - return array_merge( - array($this->_getPublicNameFromIndex($this->_focus)), - $this->_frames[$this->_focus]->getFrameFocus()); - } - - /** - * Turns an internal array index into the frames list - * into a public name, or if none, then a one offset - * index. - * @param integer $subject Internal index. - * @return integer/string Public name. - * @access private - */ - function _getPublicNameFromIndex($subject) { - foreach ($this->_names as $name => $index) { - if ($subject == $index) { - return $name; - } - } - return $subject + 1; - } - - /** - * Sets the focus by index. The integer index starts from 1. - * If already focused and the target frame also has frames, - * then the nested frame will be focused. - * @param integer $choice Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocusByIndex($choice) { - if (is_integer($this->_focus)) { - if ($this->_frames[$this->_focus]->hasFrames()) { - return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice); - } - } - if (($choice < 1) || ($choice > count($this->_frames))) { - return false; - } - $this->_focus = $choice - 1; - return true; - } - - /** - * Sets the focus by name. If already focused and the - * target frame also has frames, then the nested frame - * will be focused. - * @param string $name Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocus($name) { - if (is_integer($this->_focus)) { - if ($this->_frames[$this->_focus]->hasFrames()) { - return $this->_frames[$this->_focus]->setFrameFocus($name); - } - } - if (in_array($name, array_keys($this->_names))) { - $this->_focus = $this->_names[$name]; - return true; - } - return false; - } - - /** - * Clears the frame focus. - * @access public - */ - function clearFrameFocus() { - $this->_focus = false; - $this->_clearNestedFramesFocus(); - } - - /** - * Clears the frame focus for any nested frames. - * @access private - */ - function _clearNestedFramesFocus() { - for ($i = 0; $i < count($this->_frames); $i++) { - $this->_frames[$i]->clearFrameFocus(); - } - } - - /** - * Test for the presence of a frameset. - * @return boolean Always true. - * @access public - */ - function hasFrames() { - return true; - } - - /** - * Accessor for frames information. - * @return array/string Recursive hash of frame URL strings. - * The key is either a numerical - * index or the name attribute. - * @access public - */ - function getFrames() { - $report = array(); - for ($i = 0; $i < count($this->_frames); $i++) { - $report[$this->_getPublicNameFromIndex($i)] = - $this->_frames[$i]->getFrames(); - } - return $report; - } - - /** - * Accessor for raw text of either all the pages or - * the frame in focus. - * @return string Raw unparsed content. - * @access public - */ - function getRaw() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getRaw(); - } - $raw = ''; - for ($i = 0; $i < count($this->_frames); $i++) { - $raw .= $this->_frames[$i]->getRaw(); - } - return $raw; - } - - /** - * Accessor for plain text of either all the pages or - * the frame in focus. - * @return string Plain text content. - * @access public - */ - function getText() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getText(); - } - $raw = ''; - for ($i = 0; $i < count($this->_frames); $i++) { - $raw .= ' ' . $this->_frames[$i]->getText(); - } - return trim($raw); - } - - /** - * Accessor for last error. - * @return string Error from last response. - * @access public - */ - function getTransportError() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getTransportError(); - } - return $this->_frameset->getTransportError(); - } - - /** - * Request method used to fetch this frame. - * @return string GET, POST or HEAD. - * @access public - */ - function getMethod() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getMethod(); - } - return $this->_frameset->getMethod(); - } - - /** - * Original resource name. - * @return SimpleUrl Current url. - * @access public - */ - function getUrl() { - if (is_integer($this->_focus)) { - $url = $this->_frames[$this->_focus]->getUrl(); - $url->setTarget($this->_getPublicNameFromIndex($this->_focus)); - } else { - $url = $this->_frameset->getUrl(); - } - return $url; - } - - /** - * Page base URL. - * @return SimpleUrl Current url. - * @access public - */ - function getBaseUrl() { - if (is_integer($this->_focus)) { - $url = $this->_frames[$this->_focus]->getBaseUrl(); - } else { - $url = $this->_frameset->getBaseUrl(); - } - return $url; - } - - /** - * Expands expandomatic URLs into fully qualified - * URLs for the frameset page. - * @param SimpleUrl $url Relative URL. - * @return SimpleUrl Absolute URL. - * @access public - */ - function expandUrl($url) { - return $this->_frameset->expandUrl($url); - } - - /** - * Original request data. - * @return mixed Sent content. - * @access public - */ - function getRequestData() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getRequestData(); - } - return $this->_frameset->getRequestData(); - } - - /** - * Accessor for current MIME type. - * @return string MIME type as string; e.g. 'text/html' - * @access public - */ - function getMimeType() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getMimeType(); - } - return $this->_frameset->getMimeType(); - } - - /** - * Accessor for last response code. - * @return integer Last HTTP response code received. - * @access public - */ - function getResponseCode() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getResponseCode(); - } - return $this->_frameset->getResponseCode(); - } - - /** - * Accessor for last Authentication type. Only valid - * straight after a challenge (401). - * @return string Description of challenge type. - * @access public - */ - function getAuthentication() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getAuthentication(); - } - return $this->_frameset->getAuthentication(); - } - - /** - * Accessor for last Authentication realm. Only valid - * straight after a challenge (401). - * @return string Name of security realm. - * @access public - */ - function getRealm() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getRealm(); - } - return $this->_frameset->getRealm(); - } - - /** - * Accessor for outgoing header information. - * @return string Header block. - * @access public - */ - function getRequest() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getRequest(); - } - return $this->_frameset->getRequest(); - } - - /** - * Accessor for raw header information. - * @return string Header block. - * @access public - */ - function getHeaders() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getHeaders(); - } - return $this->_frameset->getHeaders(); - } - - /** - * Accessor for parsed title. - * @return string Title or false if no title is present. - * @access public - */ - function getTitle() { - return $this->_frameset->getTitle(); - } - - /** - * Accessor for a list of all fixed links. - * @return array List of urls as strings. - * @access public - */ - function getUrls() { - if (is_integer($this->_focus)) { - return $this->_frames[$this->_focus]->getUrls(); - } - $urls = array(); - foreach ($this->_frames as $frame) { - $urls = array_merge($urls, $frame->getUrls()); - } - return array_values(array_unique($urls)); - } - - /** - * Accessor for URLs by the link label. Label will match - * regardess of whitespace issues and case. - * @param string $label Text of link. - * @return array List of links with that label. - * @access public - */ - function getUrlsByLabel($label) { - if (is_integer($this->_focus)) { - return $this->_tagUrlsWithFrame( - $this->_frames[$this->_focus]->getUrlsByLabel($label), - $this->_focus); - } - $urls = array(); - foreach ($this->_frames as $index => $frame) { - $urls = array_merge( - $urls, - $this->_tagUrlsWithFrame( - $frame->getUrlsByLabel($label), - $index)); - } - return $urls; - } - - /** - * Accessor for a URL by the id attribute. If in a frameset - * then the first link found with that ID attribute is - * returned only. Focus on a frame if you want one from - * a specific part of the frameset. - * @param string $id Id attribute of link. - * @return string URL with that id. - * @access public - */ - function getUrlById($id) { - foreach ($this->_frames as $index => $frame) { - if ($url = $frame->getUrlById($id)) { - if (! $url->gettarget()) { - $url->setTarget($this->_getPublicNameFromIndex($index)); - } - return $url; - } - } - return false; - } - - /** - * Attaches the intended frame index to a list of URLs. - * @param array $urls List of SimpleUrls. - * @param string $frame Name of frame or index. - * @return array List of tagged URLs. - * @access private - */ - function _tagUrlsWithFrame($urls, $frame) { - $tagged = array(); - foreach ($urls as $url) { - if (! $url->getTarget()) { - $url->setTarget($this->_getPublicNameFromIndex($frame)); - } - $tagged[] = $url; - } - return $tagged; - } - - /** - * Finds a held form by button label. Will only - * search correctly built forms. - * @param SimpleSelector $selector Button finder. - * @return SimpleForm Form object containing - * the button. - * @access public - */ - function &getFormBySubmit($selector) { - $form = &$this->_findForm('getFormBySubmit', $selector); - return $form; - } - - /** - * Finds a held form by image using a selector. - * Will only search correctly built forms. The first - * form found either within the focused frame, or - * across frames, will be the one returned. - * @param SimpleSelector $selector Image finder. - * @return SimpleForm Form object containing - * the image. - * @access public - */ - function &getFormByImage($selector) { - $form = &$this->_findForm('getFormByImage', $selector); - return $form; - } - - /** - * Finds a held form by the form ID. A way of - * identifying a specific form when we have control - * of the HTML code. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $id Form label. - * @return SimpleForm Form object containing the matching ID. - * @access public - */ - function &getFormById($id) { - $form = &$this->_findForm('getFormById', $id); - return $form; - } - - /** - * General form finder. Will search all the frames or - * just the one in focus. - * @param string $method Method to use to find in a page. - * @param string $attribute Label, name or ID. - * @return SimpleForm Form object containing the matching ID. - * @access private - */ - function &_findForm($method, $attribute) { - if (is_integer($this->_focus)) { - $form = &$this->_findFormInFrame( - $this->_frames[$this->_focus], - $this->_focus, - $method, - $attribute); - return $form; - } - for ($i = 0; $i < count($this->_frames); $i++) { - $form = &$this->_findFormInFrame( - $this->_frames[$i], - $i, - $method, - $attribute); - if ($form) { - return $form; - } - } - $null = null; - return $null; - } - - /** - * Finds a form in a page using a form finding method. Will - * also tag the form with the frame name it belongs in. - * @param SimplePage $page Page content of frame. - * @param integer $index Internal frame representation. - * @param string $method Method to use to find in a page. - * @param string $attribute Label, name or ID. - * @return SimpleForm Form object containing the matching ID. - * @access private - */ - function &_findFormInFrame(&$page, $index, $method, $attribute) { - $form = &$this->_frames[$index]->$method($attribute); - if (isset($form)) { - $form->setDefaultTarget($this->_getPublicNameFromIndex($index)); - } - return $form; - } - - /** - * Sets a field on each form in which the field is - * available. - * @param SimpleSelector $selector Field finder. - * @param string $value Value to set field to. - * @return boolean True if value is valid. - * @access public - */ - function setField($selector, $value) { - if (is_integer($this->_focus)) { - $this->_frames[$this->_focus]->setField($selector, $value); - } else { - for ($i = 0; $i < count($this->_frames); $i++) { - $this->_frames[$i]->setField($selector, $value); - } - } - } - - /** - * Accessor for a form element value within a page. - * @param SimpleSelector $selector Field finder. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($selector) { - for ($i = 0; $i < count($this->_frames); $i++) { - $value = $this->_frames[$i]->getField($selector); - if (isset($value)) { - return $value; - } - } - return null; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/http.php b/tests/simpletest/http.php deleted file mode 100644 index e6c6e89da..000000000 --- a/tests/simpletest/http.php +++ /dev/null @@ -1,624 +0,0 @@ -_url = $url; - } - - /** - * Resource name. - * @return SimpleUrl Current url. - * @access protected - */ - function getUrl() { - return $this->_url; - } - - /** - * Creates the first line which is the actual request. - * @param string $method HTTP request method, usually GET. - * @return string Request line content. - * @access protected - */ - function _getRequestLine($method) { - return $method . ' ' . $this->_url->getPath() . - $this->_url->getEncodedRequest() . ' HTTP/1.0'; - } - - /** - * Creates the host part of the request. - * @return string Host line content. - * @access protected - */ - function _getHostLine() { - $line = 'Host: ' . $this->_url->getHost(); - if ($this->_url->getPort()) { - $line .= ':' . $this->_url->getPort(); - } - return $line; - } - - /** - * Opens a socket to the route. - * @param string $method HTTP request method, usually GET. - * @param integer $timeout Connection timeout. - * @return SimpleSocket New socket. - * @access public - */ - function &createConnection($method, $timeout) { - $default_port = ('https' == $this->_url->getScheme()) ? 443 : 80; - $socket = &$this->_createSocket( - $this->_url->getScheme() ? $this->_url->getScheme() : 'http', - $this->_url->getHost(), - $this->_url->getPort() ? $this->_url->getPort() : $default_port, - $timeout); - if (! $socket->isError()) { - $socket->write($this->_getRequestLine($method) . "\r\n"); - $socket->write($this->_getHostLine() . "\r\n"); - $socket->write("Connection: close\r\n"); - } - return $socket; - } - - /** - * Factory for socket. - * @param string $scheme Protocol to use. - * @param string $host Hostname to connect to. - * @param integer $port Remote port. - * @param integer $timeout Connection timeout. - * @return SimpleSocket/SimpleSecureSocket New socket. - * @access protected - */ - function &_createSocket($scheme, $host, $port, $timeout) { - if (in_array($scheme, array('https'))) { - $socket = &new SimpleSecureSocket($host, $port, $timeout); - } else { - $socket = &new SimpleSocket($host, $port, $timeout); - } - return $socket; - } -} - -/** - * Creates HTTP headers for the end point of - * a HTTP request via a proxy server. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleProxyRoute extends SimpleRoute { - var $_proxy; - var $_username; - var $_password; - - /** - * Stashes the proxy address. - * @param SimpleUrl $url URL as object. - * @param string $proxy Proxy URL. - * @param string $username Username for autentication. - * @param string $password Password for autentication. - * @access public - */ - function SimpleProxyRoute($url, $proxy, $username = false, $password = false) { - $this->SimpleRoute($url); - $this->_proxy = $proxy; - $this->_username = $username; - $this->_password = $password; - } - - /** - * Creates the first line which is the actual request. - * @param string $method HTTP request method, usually GET. - * @param SimpleUrl $url URL as object. - * @return string Request line content. - * @access protected - */ - function _getRequestLine($method) { - $url = $this->getUrl(); - $scheme = $url->getScheme() ? $url->getScheme() : 'http'; - $port = $url->getPort() ? ':' . $url->getPort() : ''; - return $method . ' ' . $scheme . '://' . $url->getHost() . $port . - $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0'; - } - - /** - * Creates the host part of the request. - * @param SimpleUrl $url URL as object. - * @return string Host line content. - * @access protected - */ - function _getHostLine() { - $host = 'Host: ' . $this->_proxy->getHost(); - $port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080; - return "$host:$port"; - } - - /** - * Opens a socket to the route. - * @param string $method HTTP request method, usually GET. - * @param integer $timeout Connection timeout. - * @return SimpleSocket New socket. - * @access public - */ - function &createConnection($method, $timeout) { - $socket = &$this->_createSocket( - $this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http', - $this->_proxy->getHost(), - $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080, - $timeout); - if ($socket->isError()) { - return $socket; - } - $socket->write($this->_getRequestLine($method) . "\r\n"); - $socket->write($this->_getHostLine() . "\r\n"); - if ($this->_username && $this->_password) { - $socket->write('Proxy-Authorization: Basic ' . - base64_encode($this->_username . ':' . $this->_password) . - "\r\n"); - } - $socket->write("Connection: close\r\n"); - return $socket; - } -} - -/** - * HTTP request for a web page. Factory for - * HttpResponse object. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHttpRequest { - var $_route; - var $_encoding; - var $_headers; - var $_cookies; - - /** - * Builds the socket request from the different pieces. - * These include proxy information, URL, cookies, headers, - * request method and choice of encoding. - * @param SimpleRoute $route Request route. - * @param SimpleFormEncoding $encoding Content to send with - * request. - * @access public - */ - function SimpleHttpRequest(&$route, $encoding) { - $this->_route = &$route; - $this->_encoding = $encoding; - $this->_headers = array(); - $this->_cookies = array(); - } - - /** - * Dispatches the content to the route's socket. - * @param integer $timeout Connection timeout. - * @return SimpleHttpResponse A response which may only have - * an error, but hopefully has a - * complete web page. - * @access public - */ - function &fetch($timeout) { - $socket = &$this->_route->createConnection($this->_encoding->getMethod(), $timeout); - if (! $socket->isError()) { - $this->_dispatchRequest($socket, $this->_encoding); - } - $response = &$this->_createResponse($socket); - return $response; - } - - /** - * Sends the headers. - * @param SimpleSocket $socket Open socket. - * @param string $method HTTP request method, - * usually GET. - * @param SimpleFormEncoding $encoding Content to send with request. - * @access private - */ - function _dispatchRequest(&$socket, $encoding) { - foreach ($this->_headers as $header_line) { - $socket->write($header_line . "\r\n"); - } - if (count($this->_cookies) > 0) { - $socket->write("Cookie: " . implode(";", $this->_cookies) . "\r\n"); - } - $encoding->writeHeadersTo($socket); - $socket->write("\r\n"); - $encoding->writeTo($socket); - } - - /** - * Adds a header line to the request. - * @param string $header_line Text of full header line. - * @access public - */ - function addHeaderLine($header_line) { - $this->_headers[] = $header_line; - } - - /** - * Reads all the relevant cookies from the - * cookie jar. - * @param SimpleCookieJar $jar Jar to read - * @param SimpleUrl $url Url to use for scope. - * @access public - */ - function readCookiesFromJar($jar, $url) { - $this->_cookies = $jar->selectAsPairs($url); - } - - /** - * Wraps the socket in a response parser. - * @param SimpleSocket $socket Responding socket. - * @return SimpleHttpResponse Parsed response object. - * @access protected - */ - function &_createResponse(&$socket) { - $response = &new SimpleHttpResponse( - $socket, - $this->_route->getUrl(), - $this->_encoding); - return $response; - } -} - -/** - * Collection of header lines in the response. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHttpHeaders { - var $_raw_headers; - var $_response_code; - var $_http_version; - var $_mime_type; - var $_location; - var $_cookies; - var $_authentication; - var $_realm; - - /** - * Parses the incoming header block. - * @param string $headers Header block. - * @access public - */ - function SimpleHttpHeaders($headers) { - $this->_raw_headers = $headers; - $this->_response_code = false; - $this->_http_version = false; - $this->_mime_type = ''; - $this->_location = false; - $this->_cookies = array(); - $this->_authentication = false; - $this->_realm = false; - foreach (split("\r\n", $headers) as $header_line) { - $this->_parseHeaderLine($header_line); - } - } - - /** - * Accessor for parsed HTTP protocol version. - * @return integer HTTP error code. - * @access public - */ - function getHttpVersion() { - return $this->_http_version; - } - - /** - * Accessor for raw header block. - * @return string All headers as raw string. - * @access public - */ - function getRaw() { - return $this->_raw_headers; - } - - /** - * Accessor for parsed HTTP error code. - * @return integer HTTP error code. - * @access public - */ - function getResponseCode() { - return (integer)$this->_response_code; - } - - /** - * Returns the redirected URL or false if - * no redirection. - * @return string URL or false for none. - * @access public - */ - function getLocation() { - return $this->_location; - } - - /** - * Test to see if the response is a valid redirect. - * @return boolean True if valid redirect. - * @access public - */ - function isRedirect() { - return in_array($this->_response_code, array(301, 302, 303, 307)) && - (boolean)$this->getLocation(); - } - - /** - * Test to see if the response is an authentication - * challenge. - * @return boolean True if challenge. - * @access public - */ - function isChallenge() { - return ($this->_response_code == 401) && - (boolean)$this->_authentication && - (boolean)$this->_realm; - } - - /** - * Accessor for MIME type header information. - * @return string MIME type. - * @access public - */ - function getMimeType() { - return $this->_mime_type; - } - - /** - * Accessor for authentication type. - * @return string Type. - * @access public - */ - function getAuthentication() { - return $this->_authentication; - } - - /** - * Accessor for security realm. - * @return string Realm. - * @access public - */ - function getRealm() { - return $this->_realm; - } - - /** - * Writes new cookies to the cookie jar. - * @param SimpleCookieJar $jar Jar to write to. - * @param SimpleUrl $url Host and path to write under. - * @access public - */ - function writeCookiesToJar(&$jar, $url) { - foreach ($this->_cookies as $cookie) { - $jar->setCookie( - $cookie->getName(), - $cookie->getValue(), - $url->getHost(), - $cookie->getPath(), - $cookie->getExpiry()); - } - } - - /** - * Called on each header line to accumulate the held - * data within the class. - * @param string $header_line One line of header. - * @access protected - */ - function _parseHeaderLine($header_line) { - if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) { - $this->_http_version = $matches[1]; - $this->_response_code = $matches[2]; - } - if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) { - $this->_mime_type = trim($matches[1]); - } - if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) { - $this->_location = trim($matches[1]); - } - if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) { - $this->_cookies[] = $this->_parseCookie($matches[1]); - } - if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) { - $this->_authentication = $matches[1]; - $this->_realm = trim($matches[2]); - } - } - - /** - * Parse the Set-cookie content. - * @param string $cookie_line Text after "Set-cookie:" - * @return SimpleCookie New cookie object. - * @access private - */ - function _parseCookie($cookie_line) { - $parts = split(";", $cookie_line); - $cookie = array(); - preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie); - foreach ($parts as $part) { - if (preg_match('/\s*(.*?)\s*=(.*)/', $part, $matches)) { - $cookie[$matches[1]] = trim($matches[2]); - } - } - return new SimpleCookie( - $cookie[1], - trim($cookie[2]), - isset($cookie["path"]) ? $cookie["path"] : "", - isset($cookie["expires"]) ? $cookie["expires"] : false); - } -} - -/** - * Basic HTTP response. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHttpResponse extends SimpleStickyError { - var $_url; - var $_encoding; - var $_sent; - var $_content; - var $_headers; - - /** - * Constructor. Reads and parses the incoming - * content and headers. - * @param SimpleSocket $socket Network connection to fetch - * response text from. - * @param SimpleUrl $url Resource name. - * @param mixed $encoding Record of content sent. - * @access public - */ - function SimpleHttpResponse(&$socket, $url, $encoding) { - $this->SimpleStickyError(); - $this->_url = $url; - $this->_encoding = $encoding; - $this->_sent = $socket->getSent(); - $this->_content = false; - $raw = $this->_readAll($socket); - if ($socket->isError()) { - $this->_setError('Error reading socket [' . $socket->getError() . ']'); - return; - } - $this->_parse($raw); - } - - /** - * Splits up the headers and the rest of the content. - * @param string $raw Content to parse. - * @access private - */ - function _parse($raw) { - if (! $raw) { - $this->_setError('Nothing fetched'); - $this->_headers = &new SimpleHttpHeaders(''); - } elseif (! strstr($raw, "\r\n\r\n")) { - $this->_setError('Could not split headers from content'); - $this->_headers = &new SimpleHttpHeaders($raw); - } else { - list($headers, $this->_content) = split("\r\n\r\n", $raw, 2); - $this->_headers = &new SimpleHttpHeaders($headers); - } - } - - /** - * Original request method. - * @return string GET, POST or HEAD. - * @access public - */ - function getMethod() { - return $this->_encoding->getMethod(); - } - - /** - * Resource name. - * @return SimpleUrl Current url. - * @access public - */ - function getUrl() { - return $this->_url; - } - - /** - * Original request data. - * @return mixed Sent content. - * @access public - */ - function getRequestData() { - return $this->_encoding; - } - - /** - * Raw request that was sent down the wire. - * @return string Bytes actually sent. - * @access public - */ - function getSent() { - return $this->_sent; - } - - /** - * Accessor for the content after the last - * header line. - * @return string All content. - * @access public - */ - function getContent() { - return $this->_content; - } - - /** - * Accessor for header block. The response is the - * combination of this and the content. - * @return SimpleHeaders Wrapped header block. - * @access public - */ - function getHeaders() { - return $this->_headers; - } - - /** - * Accessor for any new cookies. - * @return array List of new cookies. - * @access public - */ - function getNewCookies() { - return $this->_headers->getNewCookies(); - } - - /** - * Reads the whole of the socket output into a - * single string. - * @param SimpleSocket $socket Unread socket. - * @return string Raw output if successful - * else false. - * @access private - */ - function _readAll(&$socket) { - $all = ''; - while (! $this->_isLastPacket($next = $socket->read())) { - $all .= $next; - } - return $all; - } - - /** - * Test to see if the packet from the socket is the - * last one. - * @param string $packet Chunk to interpret. - * @return boolean True if empty or EOF. - * @access private - */ - function _isLastPacket($packet) { - if (is_string($packet)) { - return $packet === ''; - } - return ! $packet; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/invoker.php b/tests/simpletest/invoker.php deleted file mode 100644 index e2730013e..000000000 --- a/tests/simpletest/invoker.php +++ /dev/null @@ -1,139 +0,0 @@ -_test_case = &$test_case; - } - - /** - * Accessor for test case being run. - * @return SimpleTestCase Test case. - * @access public - */ - function &getTestCase() { - return $this->_test_case; - } - - /** - * Runs test level set up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function before($method) { - $this->_test_case->before($method); - } - - /** - * Invokes a test method and buffered with setUp() - * and tearDown() calls. - * @param string $method Test method to call. - * @access public - */ - function invoke($method) { - $this->_test_case->setUp(); - $this->_test_case->$method(); - $this->_test_case->tearDown(); - } - - /** - * Runs test level clean up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function after($method) { - $this->_test_case->after($method); - } -} - -/** - * Do nothing decorator. Just passes the invocation - * straight through. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleInvokerDecorator { - var $_invoker; - - /** - * Stores the invoker to wrap. - * @param SimpleInvoker $invoker Test method runner. - */ - function SimpleInvokerDecorator(&$invoker) { - $this->_invoker = &$invoker; - } - - /** - * Accessor for test case being run. - * @return SimpleTestCase Test case. - * @access public - */ - function &getTestCase() { - return $this->_invoker->getTestCase(); - } - - /** - * Runs test level set up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function before($method) { - $this->_invoker->before($method); - } - - /** - * Invokes a test method and buffered with setUp() - * and tearDown() calls. - * @param string $method Test method to call. - * @access public - */ - function invoke($method) { - $this->_invoker->invoke($method); - } - - /** - * Runs test level clean up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function after($method) { - $this->_invoker->after($method); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/mock_objects.php b/tests/simpletest/mock_objects.php deleted file mode 100644 index 5ef15751d..000000000 --- a/tests/simpletest/mock_objects.php +++ /dev/null @@ -1,1581 +0,0 @@ -= 0) { - require_once(dirname(__FILE__) . '/reflection_php5.php'); -} else { - require_once(dirname(__FILE__) . '/reflection_php4.php'); -} -/**#@-*/ - -/** - * Default character simpletest will substitute for any value - */ -if (! defined('MOCK_ANYTHING')) { - define('MOCK_ANYTHING', '*'); -} - -/** - * Parameter comparison assertion. - * @package SimpleTest - * @subpackage MockObjects - */ -class ParametersExpectation extends SimpleExpectation { - var $_expected; - - /** - * Sets the expected parameter list. - * @param array $parameters Array of parameters including - * those that are wildcarded. - * If the value is not an array - * then it is considered to match any. - * @param string $message Customised message on failure. - * @access public - */ - function ParametersExpectation($expected = false, $message = '%s') { - $this->SimpleExpectation($message); - $this->_expected = $expected; - } - - /** - * Tests the assertion. True if correct. - * @param array $parameters Comparison values. - * @return boolean True if correct. - * @access public - */ - function test($parameters) { - if (! is_array($this->_expected)) { - return true; - } - if (count($this->_expected) != count($parameters)) { - return false; - } - for ($i = 0; $i < count($this->_expected); $i++) { - if (! $this->_testParameter($parameters[$i], $this->_expected[$i])) { - return false; - } - } - return true; - } - - /** - * Tests an individual parameter. - * @param mixed $parameter Value to test. - * @param mixed $expected Comparison value. - * @return boolean True if expectation - * fulfilled. - * @access private - */ - function _testParameter($parameter, $expected) { - $comparison = $this->_coerceToExpectation($expected); - return $comparison->test($parameter); - } - - /** - * Returns a human readable test message. - * @param array $comparison Incoming parameter list. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($parameters) { - if ($this->test($parameters)) { - return "Expectation of " . count($this->_expected) . - " arguments of [" . $this->_renderArguments($this->_expected) . - "] is correct"; - } else { - return $this->_describeDifference($this->_expected, $parameters); - } - } - - /** - * Message to display if expectation differs from - * the parameters actually received. - * @param array $expected Expected parameters as list. - * @param array $parameters Actual parameters received. - * @return string Description of difference. - * @access private - */ - function _describeDifference($expected, $parameters) { - if (count($expected) != count($parameters)) { - return "Expected " . count($expected) . - " arguments of [" . $this->_renderArguments($expected) . - "] but got " . count($parameters) . - " arguments of [" . $this->_renderArguments($parameters) . "]"; - } - $messages = array(); - for ($i = 0; $i < count($expected); $i++) { - $comparison = $this->_coerceToExpectation($expected[$i]); - if (! $comparison->test($parameters[$i])) { - $messages[] = "parameter " . ($i + 1) . " with [" . - $comparison->overlayMessage($parameters[$i], $this->_getDumper()) . "]"; - } - } - return "Parameter expectation differs at " . implode(" and ", $messages); - } - - /** - * Creates an identical expectation if the - * object/value is not already some type - * of expectation. - * @param mixed $expected Expected value. - * @return SimpleExpectation Expectation object. - * @access private - */ - function _coerceToExpectation($expected) { - if (SimpleExpectation::isExpectation($expected)) { - return $expected; - } - return new IdenticalExpectation($expected); - } - - /** - * Renders the argument list as a string for - * messages. - * @param array $args Incoming arguments. - * @return string Simple description of type and value. - * @access private - */ - function _renderArguments($args) { - $descriptions = array(); - if (is_array($args)) { - foreach ($args as $arg) { - $dumper = &new SimpleDumper(); - $descriptions[] = $dumper->describeValue($arg); - } - } - return implode(', ', $descriptions); - } -} - -/** - * Confirms that the number of calls on a method is as expected. - * @package SimpleTest - * @subpackage MockObjects - */ -class CallCountExpectation extends SimpleExpectation { - var $_method; - var $_count; - - /** - * Stashes the method and expected count for later - * reporting. - * @param string $method Name of method to confirm against. - * @param integer $count Expected number of calls. - * @param string $message Custom error message. - */ - function CallCountExpectation($method, $count, $message = '%s') { - $this->_method = $method; - $this->_count = $count; - $this->SimpleExpectation($message); - } - - /** - * Tests the assertion. True if correct. - * @param integer $compare Measured call count. - * @return boolean True if expected. - * @access public - */ - function test($compare) { - return ($this->_count == $compare); - } - - /** - * Reports the comparison. - * @param integer $compare Measured call count. - * @return string Message to show. - * @access public - */ - function testMessage($compare) { - return 'Expected call count for [' . $this->_method . - '] was [' . $this->_count . - '] got [' . $compare . ']'; - } -} - -/** - * Confirms that the number of calls on a method is as expected. - * @package SimpleTest - * @subpackage MockObjects - */ -class MinimumCallCountExpectation extends SimpleExpectation { - var $_method; - var $_count; - - /** - * Stashes the method and expected count for later - * reporting. - * @param string $method Name of method to confirm against. - * @param integer $count Minimum number of calls. - * @param string $message Custom error message. - */ - function MinimumCallCountExpectation($method, $count, $message = '%s') { - $this->_method = $method; - $this->_count = $count; - $this->SimpleExpectation($message); - } - - /** - * Tests the assertion. True if correct. - * @param integer $compare Measured call count. - * @return boolean True if enough. - * @access public - */ - function test($compare) { - return ($this->_count <= $compare); - } - - /** - * Reports the comparison. - * @param integer $compare Measured call count. - * @return string Message to show. - * @access public - */ - function testMessage($compare) { - return 'Minimum call count for [' . $this->_method . - '] was [' . $this->_count . - '] got [' . $compare . ']'; - } -} - -/** - * Confirms that the number of calls on a method is as expected. - * @package SimpleTest - * @subpackage MockObjects - */ -class MaximumCallCountExpectation extends SimpleExpectation { - var $_method; - var $_count; - - /** - * Stashes the method and expected count for later - * reporting. - * @param string $method Name of method to confirm against. - * @param integer $count Minimum number of calls. - * @param string $message Custom error message. - */ - function MaximumCallCountExpectation($method, $count, $message = '%s') { - $this->_method = $method; - $this->_count = $count; - $this->SimpleExpectation($message); - } - - /** - * Tests the assertion. True if correct. - * @param integer $compare Measured call count. - * @return boolean True if not over. - * @access public - */ - function test($compare) { - return ($this->_count >= $compare); - } - - /** - * Reports the comparison. - * @param integer $compare Measured call count. - * @return string Message to show. - * @access public - */ - function testMessage($compare) { - return 'Maximum call count for [' . $this->_method . - '] was [' . $this->_count . - '] got [' . $compare . ']'; - } -} - -/** - * Retrieves method actions by searching the - * parameter lists until an expected match is found. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleSignatureMap { - var $_map; - - /** - * Creates an empty call map. - * @access public - */ - function SimpleSignatureMap() { - $this->_map = array(); - } - - /** - * Stashes a reference against a method call. - * @param array $parameters Array of arguments (including wildcards). - * @param mixed $action Reference placed in the map. - * @access public - */ - function add($parameters, &$action) { - $place = count($this->_map); - $this->_map[$place] = array(); - $this->_map[$place]['params'] = new ParametersExpectation($parameters); - $this->_map[$place]['content'] = &$action; - } - - /** - * Searches the call list for a matching parameter - * set. Returned by reference. - * @param array $parameters Parameters to search by - * without wildcards. - * @return object Object held in the first matching - * slot, otherwise null. - * @access public - */ - function &findFirstAction($parameters) { - $slot = $this->_findFirstSlot($parameters); - if (isset($slot) && isset($slot['content'])) { - return $slot['content']; - } - $null = null; - return $null; - } - - /** - * Searches the call list for a matching parameter - * set. True if successful. - * @param array $parameters Parameters to search by - * without wildcards. - * @return boolean True if a match is present. - * @access public - */ - function isMatch($parameters) { - return ($this->_findFirstSlot($parameters) != null); - } - - /** - * Compares the incoming parameters with the - * internal expectation. Uses the incoming $test - * to dispatch the test message. - * @param SimpleTestCase $test Test to dispatch to. - * @param array $parameters The actual calling arguments. - * @param string $message The message to overlay. - * @access public - */ - function test(&$test, $parameters, $message) { - } - - /** - * Searches the map for a matching item. - * @param array $parameters Parameters to search by - * without wildcards. - * @return array Reference to slot or null. - * @access private - */ - function &_findFirstSlot($parameters) { - $count = count($this->_map); - for ($i = 0; $i < $count; $i++) { - if ($this->_map[$i]["params"]->test($parameters)) { - return $this->_map[$i]; - } - } - $null = null; - return $null; - } -} - -/** - * Allows setting of actions against call signatures either - * at a specific time, or always. Specific time settings - * trump lasting ones, otherwise the most recently added - * will mask an earlier match. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleCallSchedule { - var $_wildcard = MOCK_ANYTHING; - var $_always; - var $_at; - - /** - * Sets up an empty response schedule. - * Creates an empty call map. - */ - function SimpleCallSchedule() { - $this->_always = array(); - $this->_at = array(); - } - - /** - * Stores an action against a signature that - * will always fire unless masked by a time - * specific one. - * @param string $method Method name. - * @param array $args Calling parameters. - * @param SimpleAction $action Actually simpleByValue, etc. - * @access public - */ - function register($method, $args, &$action) { - $args = $this->_replaceWildcards($args); - $method = strtolower($method); - if (! isset($this->_always[$method])) { - $this->_always[$method] = new SimpleSignatureMap(); - } - $this->_always[$method]->add($args, $action); - } - - /** - * Stores an action against a signature that - * will fire at a specific time in the future. - * @param integer $step delay of calls to this method, - * 0 is next. - * @param string $method Method name. - * @param array $args Calling parameters. - * @param SimpleAction $action Actually SimpleByValue, etc. - * @access public - */ - function registerAt($step, $method, $args, &$action) { - $args = $this->_replaceWildcards($args); - $method = strtolower($method); - if (! isset($this->_at[$method])) { - $this->_at[$method] = array(); - } - if (! isset($this->_at[$method][$step])) { - $this->_at[$method][$step] = new SimpleSignatureMap(); - } - $this->_at[$method][$step]->add($args, $action); - } - - function expectArguments($method, $args, $message) { - $args = $this->_replaceWildcards($args); - $message .= Mock::getExpectationLine(); - $this->_expected_args[strtolower($method)] = - new ParametersExpectation($args, $message); - - } - - /** - * Actually carry out the action stored previously, - * if the parameters match. - * @param integer $step Time of call. - * @param string $method Method name. - * @param array $args The parameters making up the - * rest of the call. - * @return mixed The result of the action. - * @access public. - */ - function &respond($step, $method, $args) { - $method = strtolower($method); - if (isset($this->_at[$method][$step])) { - if ($this->_at[$method][$step]->isMatch($args)) { - $action = &$this->_at[$method][$step]->findFirstAction($args); - if (isset($action)) { - return $action->act(); - } - } - } - if (isset($this->_always[$method])) { - $action = &$this->_always[$method]->findFirstAction($args); - if (isset($action)) { - return $action->act(); - } - } - $null = null; - return $null; - } - - /** - * Replaces wildcard matches with wildcard - * expectations in the argument list. - * @param array $args Raw argument list. - * @return array Argument list with - * expectations. - * @access private - */ - function _replaceWildcards($args) { - if ($args === false) { - return false; - } - for ($i = 0; $i < count($args); $i++) { - if ($args[$i] === $this->_wildcard) { - $args[$i] = new AnythingExpectation(); - } - } - return $args; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes a reference for returning later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleByReference { - var $_reference; - - /** - * Stashes it for later. - * @param mixed $reference Actual PHP4 style reference. - * @access public - */ - function SimpleByReference(&$reference) { - $this->_reference = &$reference; - } - - /** - * Returns the reference stored earlier. - * @return mixed Whatever was stashed. - * @access public - */ - function &act() { - return $this->_reference; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes a value for returning later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleByValue { - var $_value; - - /** - * Stashes it for later. - * @param mixed $value You need to clone objects - * if you want copy semantics - * for these. - * @access public - */ - function SimpleByValue($value) { - $this->_value = $value; - } - - /** - * Returns the value stored earlier. - * @return mixed Whatever was stashed. - * @access public - */ - function &act() { - $dummy = $this->_value; - return $dummy; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes an exception for throwing later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleThrower { - var $_exception; - - /** - * Stashes it for later. - * @param Exception $exception The exception object to throw. - * @access public - */ - function SimpleThrower($exception) { - $this->_exception = $exception; - } - - /** - * Throws the exceptins stashed earlier. - * @access public - */ - function act() { - eval('throw $this->_exception;'); - } -} - -/** - * A type of SimpleMethodAction. - * Stashes an error for emitting later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleErrorThrower { - var $_error; - var $_severity; - - /** - * Stashes an error to throw later. - * @param string $error Error message. - * @param integer $severity PHP error constant, e.g E_USER_ERROR. - * @access public - */ - function SimpleErrorThrower($error, $severity) { - $this->_error = $error; - $this->_severity = $severity; - } - - /** - * Triggers the stashed error. - * @return null The usual PHP4.4 shenanigans are needed here. - * @access public - */ - function &act() { - trigger_error($this->_error, $this->_severity); - $null = null; - return $null; - } -} - -/** - * A base class or delegate that extends an - * empty collection of methods that can have their - * return values set and expectations made of the - * calls upon them. The mock will assert the - * expectations against it's attached test case in - * addition to the server stub behaviour or returning - * preprogrammed responses. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleMock { - var $_actions; - var $_wildcard = MOCK_ANYTHING; - var $_is_strict = true; - var $_call_counts; - var $_expected_counts; - var $_max_counts; - var $_expected_args; - var $_expected_args_at; - - /** - * Creates an empty action list and expectation list. - * All call counts are set to zero. - * @access public - */ - function SimpleMock() { - $this->_actions = &new SimpleCallSchedule(); - $this->_expectations = &new SimpleCallSchedule(); - $this->_call_counts = array(); - $this->_expected_counts = array(); - $this->_max_counts = array(); - $this->_expected_args = array(); - $this->_expected_args_at = array(); - $test = &$this->_getCurrentTestCase(); - $test->tell($this); - } - - /** - * Disables a name check when setting expectations. - * This hack is needed for the partial mocks. - * @access public - */ - function disableExpectationNameChecks() { - $this->_is_strict = false; - } - - /** - * Finds currently running test. - * @return SimpeTestCase Current test case. - * @access protected - */ - function &_getCurrentTestCase() { - $context = &SimpleTest::getContext(); - return $context->getTest(); - } - - /** - * Die if bad arguments array is passed. - * @param mixed $args The arguments value to be checked. - * @param string $task Description of task attempt. - * @return boolean Valid arguments - * @access private - */ - function _checkArgumentsIsArray($args, $task) { - if (! is_array($args)) { - trigger_error( - "Cannot $task as \$args parameter is not an array", - E_USER_ERROR); - } - } - - /** - * Triggers a PHP error if the method is not part - * of this object. - * @param string $method Name of method. - * @param string $task Description of task attempt. - * @access protected - */ - function _dieOnNoMethod($method, $task) { - if ($this->_is_strict && ! method_exists($this, $method)) { - trigger_error( - "Cannot $task as no ${method}() in class " . get_class($this), - E_USER_ERROR); - } - } - - /** - * Replaces wildcard matches with wildcard - * expectations in the argument list. - * @param array $args Raw argument list. - * @return array Argument list with - * expectations. - * @access private - */ - function _replaceWildcards($args) { - if ($args === false) { - return false; - } - for ($i = 0; $i < count($args); $i++) { - if ($args[$i] === $this->_wildcard) { - $args[$i] = new AnythingExpectation(); - } - } - return $args; - } - - /** - * Adds one to the call count of a method. - * @param string $method Method called. - * @param array $args Arguments as an array. - * @access protected - */ - function _addCall($method, $args) { - if (! isset($this->_call_counts[$method])) { - $this->_call_counts[$method] = 0; - } - $this->_call_counts[$method]++; - } - - /** - * Fetches the call count of a method so far. - * @param string $method Method name called. - * @return integer Number of calls so far. - * @access public - */ - function getCallCount($method) { - $this->_dieOnNoMethod($method, "get call count"); - $method = strtolower($method); - if (! isset($this->_call_counts[$method])) { - return 0; - } - return $this->_call_counts[$method]; - } - - /** - * Sets a return for a parameter list that will - * be passed by value for all calls to this method. - * @param string $method Method name. - * @param mixed $value Result of call passed by value. - * @param array $args List of parameters to match - * including wildcards. - * @access public - */ - function setReturnValue($method, $value, $args = false) { - $this->_dieOnNoMethod($method, "set return value"); - $this->_actions->register($method, $args, new SimpleByValue($value)); - } - - /** - * Sets a return for a parameter list that will - * be passed by value only when the required call count - * is reached. - * @param integer $timing Number of calls in the future - * to which the result applies. If - * not set then all calls will return - * the value. - * @param string $method Method name. - * @param mixed $value Result of call passed by value. - * @param array $args List of parameters to match - * including wildcards. - * @access public - */ - function setReturnValueAt($timing, $method, $value, $args = false) { - $this->_dieOnNoMethod($method, "set return value sequence"); - $this->_actions->registerAt($timing, $method, $args, new SimpleByValue($value)); - } - - /** - * Sets a return for a parameter list that will - * be passed by reference for all calls. - * @param string $method Method name. - * @param mixed $reference Result of the call will be this object. - * @param array $args List of parameters to match - * including wildcards. - * @access public - */ - function setReturnReference($method, &$reference, $args = false) { - $this->_dieOnNoMethod($method, "set return reference"); - $this->_actions->register($method, $args, new SimpleByReference($reference)); - } - - /** - * Sets a return for a parameter list that will - * be passed by value only when the required call count - * is reached. - * @param integer $timing Number of calls in the future - * to which the result applies. If - * not set then all calls will return - * the value. - * @param string $method Method name. - * @param mixed $reference Result of the call will be this object. - * @param array $args List of parameters to match - * including wildcards. - * @access public - */ - function setReturnReferenceAt($timing, $method, &$reference, $args = false) { - $this->_dieOnNoMethod($method, "set return reference sequence"); - $this->_actions->registerAt($timing, $method, $args, new SimpleByReference($reference)); - } - - /** - * Sets up an expected call with a set of - * expected parameters in that call. All - * calls will be compared to these expectations - * regardless of when the call is made. - * @param string $method Method call to test. - * @param array $args Expected parameters for the call - * including wildcards. - * @param string $message Overridden message. - * @access public - */ - function expect($method, $args, $message = '%s') { - $this->_dieOnNoMethod($method, 'set expected arguments'); - $this->_checkArgumentsIsArray($args, 'set expected arguments'); - $this->_expectations->expectArguments($method, $args, $message); - $args = $this->_replaceWildcards($args); - $message .= Mock::getExpectationLine(); - $this->_expected_args[strtolower($method)] = - new ParametersExpectation($args, $message); - } - - /** - * @deprecated - */ - function expectArguments($method, $args, $message = '%s') { - return $this->expect($method, $args, $message); - } - - /** - * Sets up an expected call with a set of - * expected parameters in that call. The - * expected call count will be adjusted if it - * is set too low to reach this call. - * @param integer $timing Number of calls in the future at - * which to test. Next call is 0. - * @param string $method Method call to test. - * @param array $args Expected parameters for the call - * including wildcards. - * @param string $message Overridden message. - * @access public - */ - function expectAt($timing, $method, $args, $message = '%s') { - $this->_dieOnNoMethod($method, 'set expected arguments at time'); - $this->_checkArgumentsIsArray($args, 'set expected arguments at time'); - $args = $this->_replaceWildcards($args); - if (! isset($this->_expected_args_at[$timing])) { - $this->_expected_args_at[$timing] = array(); - } - $method = strtolower($method); - $message .= Mock::getExpectationLine(); - $this->_expected_args_at[$timing][$method] = - new ParametersExpectation($args, $message); - } - - /** - * @deprecated - */ - function expectArgumentsAt($timing, $method, $args, $message = '%s') { - return $this->expectAt($timing, $method, $args, $message); - } - - /** - * Sets an expectation for the number of times - * a method will be called. The tally method - * is used to check this. - * @param string $method Method call to test. - * @param integer $count Number of times it should - * have been called at tally. - * @param string $message Overridden message. - * @access public - */ - function expectCallCount($method, $count, $message = '%s') { - $this->_dieOnNoMethod($method, 'set expected call count'); - $message .= Mock::getExpectationLine(); - $this->_expected_counts[strtolower($method)] = - new CallCountExpectation($method, $count, $message); - } - - /** - * Sets the number of times a method may be called - * before a test failure is triggered. - * @param string $method Method call to test. - * @param integer $count Most number of times it should - * have been called. - * @param string $message Overridden message. - * @access public - */ - function expectMaximumCallCount($method, $count, $message = '%s') { - $this->_dieOnNoMethod($method, 'set maximum call count'); - $message .= Mock::getExpectationLine(); - $this->_max_counts[strtolower($method)] = - new MaximumCallCountExpectation($method, $count, $message); - } - - /** - * Sets the number of times to call a method to prevent - * a failure on the tally. - * @param string $method Method call to test. - * @param integer $count Least number of times it should - * have been called. - * @param string $message Overridden message. - * @access public - */ - function expectMinimumCallCount($method, $count, $message = '%s') { - $this->_dieOnNoMethod($method, 'set minimum call count'); - $message .= Mock::getExpectationLine(); - $this->_expected_counts[strtolower($method)] = - new MinimumCallCountExpectation($method, $count, $message); - } - - /** - * Convenience method for barring a method - * call. - * @param string $method Method call to ban. - * @param string $message Overridden message. - * @access public - */ - function expectNever($method, $message = '%s') { - $this->expectMaximumCallCount($method, 0, $message); - } - - /** - * Convenience method for a single method - * call. - * @param string $method Method call to track. - * @param array $args Expected argument list or - * false for any arguments. - * @param string $message Overridden message. - * @access public - */ - function expectOnce($method, $args = false, $message = '%s') { - $this->expectCallCount($method, 1, $message); - if ($args !== false) { - $this->expect($method, $args, $message); - } - } - - /** - * Convenience method for requiring a method - * call. - * @param string $method Method call to track. - * @param array $args Expected argument list or - * false for any arguments. - * @param string $message Overridden message. - * @access public - */ - function expectAtLeastOnce($method, $args = false, $message = '%s') { - $this->expectMinimumCallCount($method, 1, $message); - if ($args !== false) { - $this->expect($method, $args, $message); - } - } - - /** - * Sets up a trigger to throw an exception upon the - * method call. - * @param string $method Method name to throw on. - */ - function throwOn($method, $exception = false, $args = false) { - $this->_dieOnNoMethod($method, "throw on"); - $this->_actions->register($method, $args, - new SimpleThrower($exception ? $exception : new Exception())); - } - - /** - * Sets up a trigger to throw an exception upon the - * method call. - */ - function throwAt($timing, $method, $exception = false, $args = false) { - $this->_dieOnNoMethod($method, "throw at"); - $this->_actions->registerAt($timing, $method, $args, - new SimpleThrower($exception ? $exception : new Exception())); - } - - /** - * Sets up a trigger to throw an error upon the - * method call. - */ - function errorOn($method, $error = 'A mock error', $args = false, $severity = E_USER_ERROR) { - $this->_dieOnNoMethod($method, "error on"); - $this->_actions->register($method, $args, new SimpleErrorThrower($error, $severity)); - } - - /** - * Sets up a trigger to throw an error upon the - * method call. - */ - function errorAt($timing, $method, $error = 'A mock error', $args = false, $severity = E_USER_ERROR) { - $this->_dieOnNoMethod($method, "error at"); - $this->_actions->registerAt($timing, $method, $args, new SimpleErrorThrower($error, $severity)); - } - - /** - * @deprecated - */ - function tally() { - } - - /** - * Receives event from unit test that the current - * test method has finished. Totals up the call - * counts and triggers a test assertion if a test - * is present for expected call counts. - * @param string $test_method Current method name. - * @param SimpleTestCase $test Test to send message to. - * @access public - */ - function atTestEnd($test_method, &$test) { - foreach ($this->_expected_counts as $method => $expectation) { - $test->assert($expectation, $this->getCallCount($method)); - } - foreach ($this->_max_counts as $method => $expectation) { - if ($expectation->test($this->getCallCount($method))) { - $test->assert($expectation, $this->getCallCount($method)); - } - } - } - - /** - * Returns the expected value for the method name - * and checks expectations. Will generate any - * test assertions as a result of expectations - * if there is a test present. - * @param string $method Name of method to simulate. - * @param array $args Arguments as an array. - * @return mixed Stored return. - * @access private - */ - function &_invoke($method, $args) { - $method = strtolower($method); - $step = $this->getCallCount($method); - $this->_addCall($method, $args); - $this->_checkExpectations($method, $args, $step); - $result = &$this->_emulateCall($method, $args, $step); - return $result; - } - - /** - * Finds the return value matching the incoming - * arguments. If there is no matching value found - * then an error is triggered. - * @param string $method Method name. - * @param array $args Calling arguments. - * @param integer $step Current position in the - * call history. - * @return mixed Stored return or other action. - * @access protected - */ - function &_emulateCall($method, $args, $step) { - return $this->_actions->respond($step, $method, $args); - } - - /** - * Tests the arguments against expectations. - * @param string $method Method to check. - * @param array $args Argument list to match. - * @param integer $timing The position of this call - * in the call history. - * @access private - */ - function _checkExpectations($method, $args, $timing) { - $test = &$this->_getCurrentTestCase(); - if (isset($this->_max_counts[$method])) { - if (! $this->_max_counts[$method]->test($timing + 1)) { - $test->assert($this->_max_counts[$method], $timing + 1); - } - } - if (isset($this->_expected_args_at[$timing][$method])) { - $test->assert( - $this->_expected_args_at[$timing][$method], - $args, - "Mock method [$method] at [$timing] -> %s"); - } elseif (isset($this->_expected_args[$method])) { - $test->assert( - $this->_expected_args[$method], - $args, - "Mock method [$method] -> %s"); - } - } -} - -/** - * Static methods only service class for code generation of - * mock objects. - * @package SimpleTest - * @subpackage MockObjects - */ -class Mock { - - /** - * Factory for mock object classes. - * @access public - */ - function Mock() { - trigger_error('Mock factory methods are static.'); - } - - /** - * Clones a class' interface and creates a mock version - * that can have return values and expectations set. - * @param string $class Class to clone. - * @param string $mock_class New class name. Default is - * the old name with "Mock" - * prepended. - * @param array $methods Additional methods to add beyond - * those in the cloned class. Use this - * to emulate the dynamic addition of - * methods in the cloned class or when - * the class hasn't been written yet. - * @static - * @access public - */ - function generate($class, $mock_class = false, $methods = false) { - $generator = new MockGenerator($class, $mock_class); - return $generator->generateSubclass($methods); - } - - /** - * Generates a version of a class with selected - * methods mocked only. Inherits the old class - * and chains the mock methods of an aggregated - * mock object. - * @param string $class Class to clone. - * @param string $mock_class New class name. - * @param array $methods Methods to be overridden - * with mock versions. - * @static - * @access public - */ - function generatePartial($class, $mock_class, $methods) { - $generator = new MockGenerator($class, $mock_class); - return $generator->generatePartial($methods); - } - - /** - * Uses a stack trace to find the line of an assertion. - * @access public - * @static - */ - function getExpectationLine() { - $trace = new SimpleStackTrace(array('expect')); - return $trace->traceMethod(); - } -} - -/** - * @package SimpleTest - * @subpackage MockObjects - * @deprecated - */ -class Stub extends Mock { -} - -/** - * Service class for code generation of mock objects. - * @package SimpleTest - * @subpackage MockObjects - */ -class MockGenerator { - var $_class; - var $_mock_class; - var $_mock_base; - var $_reflection; - - /** - * Builds initial reflection object. - * @param string $class Class to be mocked. - * @param string $mock_class New class with identical interface, - * but no behaviour. - */ - function MockGenerator($class, $mock_class) { - $this->_class = $class; - $this->_mock_class = $mock_class; - if (! $this->_mock_class) { - $this->_mock_class = 'Mock' . $this->_class; - } - $this->_mock_base = SimpleTest::getMockBaseClass(); - $this->_reflection = new SimpleReflection($this->_class); - } - - /** - * Clones a class' interface and creates a mock version - * that can have return values and expectations set. - * @param array $methods Additional methods to add beyond - * those in th cloned class. Use this - * to emulate the dynamic addition of - * methods in the cloned class or when - * the class hasn't been written yet. - * @access public - */ - function generate($methods) { - if (! $this->_reflection->classOrInterfaceExists()) { - return false; - } - $mock_reflection = new SimpleReflection($this->_mock_class); - if ($mock_reflection->classExistsSansAutoload()) { - return false; - } - $code = $this->_createClassCode($methods ? $methods : array()); - return eval("$code return \$code;"); - } - - /** - * Subclasses a class and overrides every method with a mock one - * that can have return values and expectations set. Chains - * to an aggregated SimpleMock. - * @param array $methods Additional methods to add beyond - * those in the cloned class. Use this - * to emulate the dynamic addition of - * methods in the cloned class or when - * the class hasn't been written yet. - * @access public - */ - function generateSubclass($methods) { - if (! $this->_reflection->classOrInterfaceExists()) { - return false; - } - $mock_reflection = new SimpleReflection($this->_mock_class); - if ($mock_reflection->classExistsSansAutoload()) { - return false; - } - if ($this->_reflection->isInterface() || $this->_reflection->hasFinal()) { - $code = $this->_createClassCode($methods ? $methods : array()); - return eval("$code return \$code;"); - } else { - $code = $this->_createSubclassCode($methods ? $methods : array()); - return eval("$code return \$code;"); - } - } - - /** - * Generates a version of a class with selected - * methods mocked only. Inherits the old class - * and chains the mock methods of an aggregated - * mock object. - * @param array $methods Methods to be overridden - * with mock versions. - * @access public - */ - function generatePartial($methods) { - if (! $this->_reflection->classExists($this->_class)) { - return false; - } - $mock_reflection = new SimpleReflection($this->_mock_class); - if ($mock_reflection->classExistsSansAutoload()) { - trigger_error('Partial mock class [' . $this->_mock_class . '] already exists'); - return false; - } - $code = $this->_extendClassCode($methods); - return eval("$code return \$code;"); - } - - /** - * The new mock class code as a string. - * @param array $methods Additional methods. - * @return string Code for new mock class. - * @access private - */ - function _createClassCode($methods) { - $implements = ''; - $interfaces = $this->_reflection->getInterfaces(); - if (function_exists('spl_classes')) { - $interfaces = array_diff($interfaces, array('Traversable')); - } - if (count($interfaces) > 0) { - $implements = 'implements ' . implode(', ', $interfaces); - } - $code = "class " . $this->_mock_class . " extends " . $this->_mock_base . " $implements {\n"; - $code .= " function " . $this->_mock_class . "() {\n"; - $code .= " \$this->" . $this->_mock_base . "();\n"; - $code .= " }\n"; - if (in_array('__construct', $this->_reflection->getMethods())) { - $code .= " " . $this->_reflection->getSignature('__construct') . " {\n"; - $code .= " \$this->" . $this->_mock_base . "();\n"; - $code .= " }\n"; - } - $code .= $this->_createHandlerCode($methods); - $code .= "}\n"; - return $code; - } - - /** - * The new mock class code as a string. The mock will - * be a subclass of the original mocked class. - * @param array $methods Additional methods. - * @return string Code for new mock class. - * @access private - */ - function _createSubclassCode($methods) { - $code = "class " . $this->_mock_class . " extends " . $this->_class . " {\n"; - $code .= " var \$_mock;\n"; - $code .= $this->_addMethodList(array_merge($methods, $this->_reflection->getMethods())); - $code .= "\n"; - $code .= " function " . $this->_mock_class . "() {\n"; - $code .= " \$this->_mock = &new " . $this->_mock_base . "();\n"; - $code .= " \$this->_mock->disableExpectationNameChecks();\n"; - $code .= " }\n"; - $code .= $this->_chainMockReturns(); - $code .= $this->_chainMockExpectations(); - $code .= $this->_chainThrowMethods(); - $code .= $this->_overrideMethods($this->_reflection->getMethods()); - $code .= $this->_createNewMethodCode($methods); - $code .= "}\n"; - return $code; - } - - /** - * The extension class code as a string. The class - * composites a mock object and chains mocked methods - * to it. - * @param array $methods Mocked methods. - * @return string Code for a new class. - * @access private - */ - function _extendClassCode($methods) { - $code = "class " . $this->_mock_class . " extends " . $this->_class . " {\n"; - $code .= " var \$_mock;\n"; - $code .= $this->_addMethodList($methods); - $code .= "\n"; - $code .= " function " . $this->_mock_class . "() {\n"; - $code .= " \$this->_mock = &new " . $this->_mock_base . "();\n"; - $code .= " \$this->_mock->disableExpectationNameChecks();\n"; - $code .= " }\n"; - $code .= $this->_chainMockReturns(); - $code .= $this->_chainMockExpectations(); - $code .= $this->_chainThrowMethods(); - $code .= $this->_overrideMethods($methods); - $code .= "}\n"; - return $code; - } - - /** - * Creates code within a class to generate replaced - * methods. All methods call the _invoke() handler - * with the method name and the arguments in an - * array. - * @param array $methods Additional methods. - * @access private - */ - function _createHandlerCode($methods) { - $code = ''; - $methods = array_merge($methods, $this->_reflection->getMethods()); - foreach ($methods as $method) { - if ($this->_isConstructor($method)) { - continue; - } - $mock_reflection = new SimpleReflection($this->_mock_base); - if (in_array($method, $mock_reflection->getMethods())) { - continue; - } - $code .= " " . $this->_reflection->getSignature($method) . " {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " \$result = &\$this->_invoke(\"$method\", \$args);\n"; - $code .= " return \$result;\n"; - $code .= " }\n"; - } - return $code; - } - - /** - * Creates code within a class to generate a new - * methods. All methods call the _invoke() handler - * on the internal mock with the method name and - * the arguments in an array. - * @param array $methods Additional methods. - * @access private - */ - function _createNewMethodCode($methods) { - $code = ''; - foreach ($methods as $method) { - if ($this->_isConstructor($method)) { - continue; - } - $mock_reflection = new SimpleReflection($this->_mock_base); - if (in_array($method, $mock_reflection->getMethods())) { - continue; - } - $code .= " " . $this->_reflection->getSignature($method) . " {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " \$result = &\$this->_mock->_invoke(\"$method\", \$args);\n"; - $code .= " return \$result;\n"; - $code .= " }\n"; - } - return $code; - } - - /** - * Tests to see if a special PHP method is about to - * be stubbed by mistake. - * @param string $method Method name. - * @return boolean True if special. - * @access private - */ - function _isConstructor($method) { - return in_array( - strtolower($method), - array('__construct', '__destruct')); - } - - /** - * Creates a list of mocked methods for error checking. - * @param array $methods Mocked methods. - * @return string Code for a method list. - * @access private - */ - function _addMethodList($methods) { - return " var \$_mocked_methods = array('" . - implode("', '", array_map('strtolower', $methods)) . - "');\n"; - } - - /** - * Creates code to abandon the expectation if not mocked. - * @param string $alias Parameter name of method name. - * @return string Code for bail out. - * @access private - */ - function _bailOutIfNotMocked($alias) { - $code = " if (! in_array(strtolower($alias), \$this->_mocked_methods)) {\n"; - $code .= " trigger_error(\"Method [$alias] is not mocked\");\n"; - $code .= " \$null = null;\n"; - $code .= " return \$null;\n"; - $code .= " }\n"; - return $code; - } - - /** - * Creates source code for chaining to the composited - * mock object. - * @return string Code for mock set up. - * @access private - */ - function _chainMockReturns() { - $code = " function setReturnValue(\$method, \$value, \$args = false) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n"; - $code .= " }\n"; - $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n"; - $code .= " }\n"; - return $code; - } - - /** - * Creates source code for chaining to an aggregated - * mock object. - * @return string Code for expectations. - * @access private - */ - function _chainMockExpectations() { - $code = " function expect(\$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expect(\$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectArguments(\$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectArguments(\$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectAt(\$timing, \$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectArgumentsAt(\$timing, \$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectCallCount(\$method, \$count) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectCallCount(\$method, \$count, \$msg = '%s');\n"; - $code .= " }\n"; - $code .= " function expectMaximumCallCount(\$method, \$count, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count, \$msg = '%s');\n"; - $code .= " }\n"; - $code .= " function expectMinimumCallCount(\$method, \$count, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count, \$msg = '%s');\n"; - $code .= " }\n"; - $code .= " function expectNever(\$method) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectNever(\$method);\n"; - $code .= " }\n"; - $code .= " function expectOnce(\$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectOnce(\$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectAtLeastOnce(\$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function tally() {\n"; - $code .= " }\n"; - return $code; - } - - /** - * Adds code for chaining the throw methods. - * @return string Code for chains. - * @access private - */ - function _chainThrowMethods() { - $code = " function throwOn(\$method, \$exception = false, \$args = false) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->throwOn(\$method, \$exception, \$args);\n"; - $code .= " }\n"; - $code .= " function throwAt(\$timing, \$method, \$exception = false, \$args = false) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->throwAt(\$timing, \$method, \$exception, \$args);\n"; - $code .= " }\n"; - $code .= " function errorOn(\$method, \$error = 'A mock error', \$args = false, \$severity = E_USER_ERROR) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->errorOn(\$method, \$error, \$args, \$severity);\n"; - $code .= " }\n"; - $code .= " function errorAt(\$timing, \$method, \$error = 'A mock error', \$args = false, \$severity = E_USER_ERROR) {\n"; - $code .= $this->_bailOutIfNotMocked("\$method"); - $code .= " \$this->_mock->errorAt(\$timing, \$method, \$error, \$args, \$severity);\n"; - $code .= " }\n"; - return $code; - } - - /** - * Creates source code to override a list of methods - * with mock versions. - * @param array $methods Methods to be overridden - * with mock versions. - * @return string Code for overridden chains. - * @access private - */ - function _overrideMethods($methods) { - $code = ""; - foreach ($methods as $method) { - if ($this->_isConstructor($method)) { - continue; - } - $code .= " " . $this->_reflection->getSignature($method) . " {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " \$result = &\$this->_mock->_invoke(\"$method\", \$args);\n"; - $code .= " return \$result;\n"; - $code .= " }\n"; - } - return $code; - } -} -?> diff --git a/tests/simpletest/page.php b/tests/simpletest/page.php deleted file mode 100644 index 08e5649dc..000000000 --- a/tests/simpletest/page.php +++ /dev/null @@ -1,983 +0,0 @@ - 'SimpleAnchorTag', - 'title' => 'SimpleTitleTag', - 'base' => 'SimpleBaseTag', - 'button' => 'SimpleButtonTag', - 'textarea' => 'SimpleTextAreaTag', - 'option' => 'SimpleOptionTag', - 'label' => 'SimpleLabelTag', - 'form' => 'SimpleFormTag', - 'frame' => 'SimpleFrameTag'); - $attributes = $this->_keysToLowerCase($attributes); - if (array_key_exists($name, $map)) { - $tag_class = $map[$name]; - return new $tag_class($attributes); - } elseif ($name == 'select') { - return $this->_createSelectionTag($attributes); - } elseif ($name == 'input') { - return $this->_createInputTag($attributes); - } - return new SimpleTag($name, $attributes); - } - - /** - * Factory for selection fields. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access protected - */ - function _createSelectionTag($attributes) { - if (isset($attributes['multiple'])) { - return new MultipleSelectionTag($attributes); - } - return new SimpleSelectionTag($attributes); - } - - /** - * Factory for input tags. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access protected - */ - function _createInputTag($attributes) { - if (! isset($attributes['type'])) { - return new SimpleTextTag($attributes); - } - $type = strtolower(trim($attributes['type'])); - $map = array( - 'submit' => 'SimpleSubmitTag', - 'image' => 'SimpleImageSubmitTag', - 'checkbox' => 'SimpleCheckboxTag', - 'radio' => 'SimpleRadioButtonTag', - 'text' => 'SimpleTextTag', - 'hidden' => 'SimpleTextTag', - 'password' => 'SimpleTextTag', - 'file' => 'SimpleUploadTag'); - if (array_key_exists($type, $map)) { - $tag_class = $map[$type]; - return new $tag_class($attributes); - } - return false; - } - - /** - * Make the keys lower case for case insensitive look-ups. - * @param hash $map Hash to convert. - * @return hash Unchanged values, but keys lower case. - * @access private - */ - function _keysToLowerCase($map) { - $lower = array(); - foreach ($map as $key => $value) { - $lower[strtolower($key)] = $value; - } - return $lower; - } -} - -/** - * SAX event handler. Maintains a list of - * open tags and dispatches them as they close. - * @package SimpleTest - * @subpackage WebTester - */ -class SimplePageBuilder extends SimpleSaxListener { - var $_tags; - var $_page; - var $_private_content_tag; - - /** - * Sets the builder up empty. - * @access public - */ - function SimplePageBuilder() { - $this->SimpleSaxListener(); - } - - /** - * Frees up any references so as to allow the PHP garbage - * collection from unset() to work. - * @access public - */ - function free() { - unset($this->_tags); - unset($this->_page); - unset($this->_private_content_tags); - } - - /** - * Reads the raw content and send events - * into the page to be built. - * @param $response SimpleHttpResponse Fetched response. - * @return SimplePage Newly parsed page. - * @access public - */ - function &parse($response) { - $this->_tags = array(); - $this->_page = &$this->_createPage($response); - $parser = &$this->_createParser($this); - $parser->parse($response->getContent()); - $this->_page->acceptPageEnd(); - return $this->_page; - } - - /** - * Creates an empty page. - * @return SimplePage New unparsed page. - * @access protected - */ - function &_createPage($response) { - $page = &new SimplePage($response); - return $page; - } - - /** - * Creates the parser used with the builder. - * @param $listener SimpleSaxListener Target of parser. - * @return SimpleSaxParser Parser to generate - * events for the builder. - * @access protected - */ - function &_createParser(&$listener) { - $parser = &new SimpleHtmlSaxParser($listener); - return $parser; - } - - /** - * Start of element event. Opens a new tag. - * @param string $name Element name. - * @param hash $attributes Attributes without content - * are marked as true. - * @return boolean False on parse error. - * @access public - */ - function startElement($name, $attributes) { - $factory = &new SimpleTagBuilder(); - $tag = $factory->createTag($name, $attributes); - if (! $tag) { - return true; - } - if ($tag->getTagName() == 'label') { - $this->_page->acceptLabelStart($tag); - $this->_openTag($tag); - return true; - } - if ($tag->getTagName() == 'form') { - $this->_page->acceptFormStart($tag); - return true; - } - if ($tag->getTagName() == 'frameset') { - $this->_page->acceptFramesetStart($tag); - return true; - } - if ($tag->getTagName() == 'frame') { - $this->_page->acceptFrame($tag); - return true; - } - if ($tag->isPrivateContent() && ! isset($this->_private_content_tag)) { - $this->_private_content_tag = &$tag; - } - if ($tag->expectEndTag()) { - $this->_openTag($tag); - return true; - } - $this->_page->acceptTag($tag); - return true; - } - - /** - * End of element event. - * @param string $name Element name. - * @return boolean False on parse error. - * @access public - */ - function endElement($name) { - if ($name == 'label') { - $this->_page->acceptLabelEnd(); - return true; - } - if ($name == 'form') { - $this->_page->acceptFormEnd(); - return true; - } - if ($name == 'frameset') { - $this->_page->acceptFramesetEnd(); - return true; - } - if ($this->_hasNamedTagOnOpenTagStack($name)) { - $tag = array_pop($this->_tags[$name]); - if ($tag->isPrivateContent() && $this->_private_content_tag->getTagName() == $name) { - unset($this->_private_content_tag); - } - $this->_addContentTagToOpenTags($tag); - $this->_page->acceptTag($tag); - return true; - } - return true; - } - - /** - * Test to see if there are any open tags awaiting - * closure that match the tag name. - * @param string $name Element name. - * @return boolean True if any are still open. - * @access private - */ - function _hasNamedTagOnOpenTagStack($name) { - return isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0); - } - - /** - * Unparsed, but relevant data. The data is added - * to every open tag. - * @param string $text May include unparsed tags. - * @return boolean False on parse error. - * @access public - */ - function addContent($text) { - if (isset($this->_private_content_tag)) { - $this->_private_content_tag->addContent($text); - } else { - $this->_addContentToAllOpenTags($text); - } - return true; - } - - /** - * Any content fills all currently open tags unless it - * is part of an option tag. - * @param string $text May include unparsed tags. - * @access private - */ - function _addContentToAllOpenTags($text) { - foreach (array_keys($this->_tags) as $name) { - for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) { - $this->_tags[$name][$i]->addContent($text); - } - } - } - - /** - * Parsed data in tag form. The parsed tag is added - * to every open tag. Used for adding options to select - * fields only. - * @param SimpleTag $tag Option tags only. - * @access private - */ - function _addContentTagToOpenTags(&$tag) { - if ($tag->getTagName() != 'option') { - return; - } - foreach (array_keys($this->_tags) as $name) { - for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) { - $this->_tags[$name][$i]->addTag($tag); - } - } - } - - /** - * Opens a tag for receiving content. Multiple tags - * will be receiving input at the same time. - * @param SimpleTag $tag New content tag. - * @access private - */ - function _openTag(&$tag) { - $name = $tag->getTagName(); - if (! in_array($name, array_keys($this->_tags))) { - $this->_tags[$name] = array(); - } - $this->_tags[$name][] = &$tag; - } -} - -/** - * A wrapper for a web page. - * @package SimpleTest - * @subpackage WebTester - */ -class SimplePage { - var $_links; - var $_title; - var $_last_widget; - var $_label; - var $_left_over_labels; - var $_open_forms; - var $_complete_forms; - var $_frameset; - var $_frames; - var $_frameset_nesting_level; - var $_transport_error; - var $_raw; - var $_text; - var $_sent; - var $_headers; - var $_method; - var $_url; - var $_base = false; - var $_request_data; - - /** - * Parses a page ready to access it's contents. - * @param SimpleHttpResponse $response Result of HTTP fetch. - * @access public - */ - function SimplePage($response = false) { - $this->_links = array(); - $this->_title = false; - $this->_left_over_labels = array(); - $this->_open_forms = array(); - $this->_complete_forms = array(); - $this->_frameset = false; - $this->_frames = array(); - $this->_frameset_nesting_level = 0; - $this->_text = false; - if ($response) { - $this->_extractResponse($response); - } else { - $this->_noResponse(); - } - } - - /** - * Extracts all of the response information. - * @param SimpleHttpResponse $response Response being parsed. - * @access private - */ - function _extractResponse($response) { - $this->_transport_error = $response->getError(); - $this->_raw = $response->getContent(); - $this->_sent = $response->getSent(); - $this->_headers = $response->getHeaders(); - $this->_method = $response->getMethod(); - $this->_url = $response->getUrl(); - $this->_request_data = $response->getRequestData(); - } - - /** - * Sets up a missing response. - * @access private - */ - function _noResponse() { - $this->_transport_error = 'No page fetched yet'; - $this->_raw = false; - $this->_sent = false; - $this->_headers = false; - $this->_method = 'GET'; - $this->_url = false; - $this->_request_data = false; - } - - /** - * Original request as bytes sent down the wire. - * @return mixed Sent content. - * @access public - */ - function getRequest() { - return $this->_sent; - } - - /** - * Accessor for raw text of page. - * @return string Raw unparsed content. - * @access public - */ - function getRaw() { - return $this->_raw; - } - - /** - * Accessor for plain text of page as a text browser - * would see it. - * @return string Plain text of page. - * @access public - */ - function getText() { - if (! $this->_text) { - $this->_text = SimpleHtmlSaxParser::normalise($this->_raw); - } - return $this->_text; - } - - /** - * Accessor for raw headers of page. - * @return string Header block as text. - * @access public - */ - function getHeaders() { - if ($this->_headers) { - return $this->_headers->getRaw(); - } - return false; - } - - /** - * Original request method. - * @return string GET, POST or HEAD. - * @access public - */ - function getMethod() { - return $this->_method; - } - - /** - * Original resource name. - * @return SimpleUrl Current url. - * @access public - */ - function getUrl() { - return $this->_url; - } - - /** - * Base URL if set via BASE tag page url otherwise - * @return SimpleUrl Base url. - * @access public - */ - function getBaseUrl() { - return $this->_base; - } - - /** - * Original request data. - * @return mixed Sent content. - * @access public - */ - function getRequestData() { - return $this->_request_data; - } - - /** - * Accessor for last error. - * @return string Error from last response. - * @access public - */ - function getTransportError() { - return $this->_transport_error; - } - - /** - * Accessor for current MIME type. - * @return string MIME type as string; e.g. 'text/html' - * @access public - */ - function getMimeType() { - if ($this->_headers) { - return $this->_headers->getMimeType(); - } - return false; - } - - /** - * Accessor for HTTP response code. - * @return integer HTTP response code received. - * @access public - */ - function getResponseCode() { - if ($this->_headers) { - return $this->_headers->getResponseCode(); - } - return false; - } - - /** - * Accessor for last Authentication type. Only valid - * straight after a challenge (401). - * @return string Description of challenge type. - * @access public - */ - function getAuthentication() { - if ($this->_headers) { - return $this->_headers->getAuthentication(); - } - return false; - } - - /** - * Accessor for last Authentication realm. Only valid - * straight after a challenge (401). - * @return string Name of security realm. - * @access public - */ - function getRealm() { - if ($this->_headers) { - return $this->_headers->getRealm(); - } - return false; - } - - /** - * Accessor for current frame focus. Will be - * false as no frames. - * @return array Always empty. - * @access public - */ - function getFrameFocus() { - return array(); - } - - /** - * Sets the focus by index. The integer index starts from 1. - * @param integer $choice Chosen frame. - * @return boolean Always false. - * @access public - */ - function setFrameFocusByIndex($choice) { - return false; - } - - /** - * Sets the focus by name. Always fails for a leaf page. - * @param string $name Chosen frame. - * @return boolean False as no frames. - * @access public - */ - function setFrameFocus($name) { - return false; - } - - /** - * Clears the frame focus. Does nothing for a leaf page. - * @access public - */ - function clearFrameFocus() { - } - - /** - * Adds a tag to the page. - * @param SimpleTag $tag Tag to accept. - * @access public - */ - function acceptTag(&$tag) { - if ($tag->getTagName() == "a") { - $this->_addLink($tag); - } elseif ($tag->getTagName() == "base") { - $this->_setBase($tag); - } elseif ($tag->getTagName() == "title") { - $this->_setTitle($tag); - } elseif ($this->_isFormElement($tag->getTagName())) { - for ($i = 0; $i < count($this->_open_forms); $i++) { - $this->_open_forms[$i]->addWidget($tag); - } - $this->_last_widget = &$tag; - } - } - - /** - * Opens a label for a described widget. - * @param SimpleFormTag $tag Tag to accept. - * @access public - */ - function acceptLabelStart(&$tag) { - $this->_label = &$tag; - unset($this->_last_widget); - } - - /** - * Closes the most recently opened label. - * @access public - */ - function acceptLabelEnd() { - if (isset($this->_label)) { - if (isset($this->_last_widget)) { - $this->_last_widget->setLabel($this->_label->getText()); - unset($this->_last_widget); - } else { - $this->_left_over_labels[] = SimpleTestCompatibility::copy($this->_label); - } - unset($this->_label); - } - } - - /** - * Tests to see if a tag is a possible form - * element. - * @param string $name HTML element name. - * @return boolean True if form element. - * @access private - */ - function _isFormElement($name) { - return in_array($name, array('input', 'button', 'textarea', 'select')); - } - - /** - * Opens a form. New widgets go here. - * @param SimpleFormTag $tag Tag to accept. - * @access public - */ - function acceptFormStart(&$tag) { - $this->_open_forms[] = &new SimpleForm($tag, $this); - } - - /** - * Closes the most recently opened form. - * @access public - */ - function acceptFormEnd() { - if (count($this->_open_forms)) { - $this->_complete_forms[] = array_pop($this->_open_forms); - } - } - - /** - * Opens a frameset. A frameset may contain nested - * frameset tags. - * @param SimpleFramesetTag $tag Tag to accept. - * @access public - */ - function acceptFramesetStart(&$tag) { - if (! $this->_isLoadingFrames()) { - $this->_frameset = &$tag; - } - $this->_frameset_nesting_level++; - } - - /** - * Closes the most recently opened frameset. - * @access public - */ - function acceptFramesetEnd() { - if ($this->_isLoadingFrames()) { - $this->_frameset_nesting_level--; - } - } - - /** - * Takes a single frame tag and stashes it in - * the current frame set. - * @param SimpleFrameTag $tag Tag to accept. - * @access public - */ - function acceptFrame(&$tag) { - if ($this->_isLoadingFrames()) { - if ($tag->getAttribute('src')) { - $this->_frames[] = &$tag; - } - } - } - - /** - * Test to see if in the middle of reading - * a frameset. - * @return boolean True if inframeset. - * @access private - */ - function _isLoadingFrames() { - if (! $this->_frameset) { - return false; - } - return ($this->_frameset_nesting_level > 0); - } - - /** - * Test to see if link is an absolute one. - * @param string $url Url to test. - * @return boolean True if absolute. - * @access protected - */ - function _linkIsAbsolute($url) { - $parsed = new SimpleUrl($url); - return (boolean)($parsed->getScheme() && $parsed->getHost()); - } - - /** - * Adds a link to the page. - * @param SimpleAnchorTag $tag Link to accept. - * @access protected - */ - function _addLink($tag) { - $this->_links[] = $tag; - } - - /** - * Marker for end of complete page. Any work in - * progress can now be closed. - * @access public - */ - function acceptPageEnd() { - while (count($this->_open_forms)) { - $this->_complete_forms[] = array_pop($this->_open_forms); - } - foreach ($this->_left_over_labels as $label) { - for ($i = 0, $count = count($this->_complete_forms); $i < $count; $i++) { - $this->_complete_forms[$i]->attachLabelBySelector( - new SimpleById($label->getFor()), - $label->getText()); - } - } - } - - /** - * Test for the presence of a frameset. - * @return boolean True if frameset. - * @access public - */ - function hasFrames() { - return (boolean)$this->_frameset; - } - - /** - * Accessor for frame name and source URL for every frame that - * will need to be loaded. Immediate children only. - * @return boolean/array False if no frameset or - * otherwise a hash of frame URLs. - * The key is either a numerical - * base one index or the name attribute. - * @access public - */ - function getFrameset() { - if (! $this->_frameset) { - return false; - } - $urls = array(); - for ($i = 0; $i < count($this->_frames); $i++) { - $name = $this->_frames[$i]->getAttribute('name'); - $url = new SimpleUrl($this->_frames[$i]->getAttribute('src')); - $urls[$name ? $name : $i + 1] = $this->expandUrl($url); - } - return $urls; - } - - /** - * Fetches a list of loaded frames. - * @return array/string Just the URL for a single page. - * @access public - */ - function getFrames() { - $url = $this->expandUrl($this->getUrl()); - return $url->asString(); - } - - /** - * Accessor for a list of all links. - * @return array List of urls with scheme of - * http or https and hostname. - * @access public - */ - function getUrls() { - $all = array(); - foreach ($this->_links as $link) { - $url = $this->_getUrlFromLink($link); - $all[] = $url->asString(); - } - return $all; - } - - /** - * Accessor for URLs by the link label. Label will match - * regardess of whitespace issues and case. - * @param string $label Text of link. - * @return array List of links with that label. - * @access public - */ - function getUrlsByLabel($label) { - $matches = array(); - foreach ($this->_links as $link) { - if ($link->getText() == $label) { - $matches[] = $this->_getUrlFromLink($link); - } - } - return $matches; - } - - /** - * Accessor for a URL by the id attribute. - * @param string $id Id attribute of link. - * @return SimpleUrl URL with that id of false if none. - * @access public - */ - function getUrlById($id) { - foreach ($this->_links as $link) { - if ($link->getAttribute('id') === (string)$id) { - return $this->_getUrlFromLink($link); - } - } - return false; - } - - /** - * Converts a link tag into a target URL. - * @param SimpleAnchor $link Parsed link. - * @return SimpleUrl URL with frame target if any. - * @access private - */ - function _getUrlFromLink($link) { - $url = $this->expandUrl($link->getHref()); - if ($link->getAttribute('target')) { - $url->setTarget($link->getAttribute('target')); - } - return $url; - } - - /** - * Expands expandomatic URLs into fully qualified - * URLs. - * @param SimpleUrl $url Relative URL. - * @return SimpleUrl Absolute URL. - * @access public - */ - function expandUrl($url) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - $location = $this->getBaseUrl() ? $this->getBaseUrl() : new SimpleUrl(); - return $url->makeAbsolute($location->makeAbsolute($this->getUrl())); - } - - /** - * Sets the base url for the page. - * @param SimpleTag $tag Base URL for page. - * @access protected - */ - function _setBase(&$tag) { - $url = $tag->getAttribute('href'); - $this->_base = new SimpleUrl($url); - } - - /** - * Sets the title tag contents. - * @param SimpleTitleTag $tag Title of page. - * @access protected - */ - function _setTitle(&$tag) { - $this->_title = &$tag; - } - - /** - * Accessor for parsed title. - * @return string Title or false if no title is present. - * @access public - */ - function getTitle() { - if ($this->_title) { - return $this->_title->getText(); - } - return false; - } - - /** - * Finds a held form by button label. Will only - * search correctly built forms. - * @param SimpleSelector $selector Button finder. - * @return SimpleForm Form object containing - * the button. - * @access public - */ - function &getFormBySubmit($selector) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasSubmit($selector)) { - return $this->_complete_forms[$i]; - } - } - $null = null; - return $null; - } - - /** - * Finds a held form by image using a selector. - * Will only search correctly built forms. - * @param SimpleSelector $selector Image finder. - * @return SimpleForm Form object containing - * the image. - * @access public - */ - function &getFormByImage($selector) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasImage($selector)) { - return $this->_complete_forms[$i]; - } - } - $null = null; - return $null; - } - - /** - * Finds a held form by the form ID. A way of - * identifying a specific form when we have control - * of the HTML code. - * @param string $id Form label. - * @return SimpleForm Form object containing the matching ID. - * @access public - */ - function &getFormById($id) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->getId() == $id) { - return $this->_complete_forms[$i]; - } - } - $null = null; - return $null; - } - - /** - * Sets a field on each form in which the field is - * available. - * @param SimpleSelector $selector Field finder. - * @param string $value Value to set field to. - * @return boolean True if value is valid. - * @access public - */ - function setField($selector, $value, $position=false) { - $is_set = false; - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->setField($selector, $value, $position)) { - $is_set = true; - } - } - return $is_set; - } - - /** - * Accessor for a form element value within a page. - * @param SimpleSelector $selector Field finder. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($selector) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - $value = $this->_complete_forms[$i]->getValue($selector); - if (isset($value)) { - return $value; - } - } - return null; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/parser.php b/tests/simpletest/parser.php deleted file mode 100644 index 3f3b37b83..000000000 --- a/tests/simpletest/parser.php +++ /dev/null @@ -1,764 +0,0 @@ - $constant) { - if (! defined($constant)) { - define($constant, $i + 1); - } -} -/**#@-*/ - -/** - * Compounded regular expression. Any of - * the contained patterns could match and - * when one does, it's label is returned. - * @package SimpleTest - * @subpackage WebTester - */ -class ParallelRegex { - var $_patterns; - var $_labels; - var $_regex; - var $_case; - - /** - * Constructor. Starts with no patterns. - * @param boolean $case True for case sensitive, false - * for insensitive. - * @access public - */ - function ParallelRegex($case) { - $this->_case = $case; - $this->_patterns = array(); - $this->_labels = array(); - $this->_regex = null; - } - - /** - * Adds a pattern with an optional label. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $label Label of regex to be returned - * on a match. - * @access public - */ - function addPattern($pattern, $label = true) { - $count = count($this->_patterns); - $this->_patterns[$count] = $pattern; - $this->_labels[$count] = $label; - $this->_regex = null; - } - - /** - * Attempts to match all patterns at once against - * a string. - * @param string $subject String to match against. - * @param string $match First matched portion of - * subject. - * @return boolean True on success. - * @access public - */ - function match($subject, &$match) { - if (count($this->_patterns) == 0) { - return false; - } - if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) { - $match = ''; - return false; - } - $match = $matches[0]; - for ($i = 1; $i < count($matches); $i++) { - if ($matches[$i]) { - return $this->_labels[$i - 1]; - } - } - return true; - } - - /** - * Compounds the patterns into a single - * regular expression separated with the - * "or" operator. Caches the regex. - * Will automatically escape (, ) and / tokens. - * @param array $patterns List of patterns in order. - * @access private - */ - function _getCompoundedRegex() { - if ($this->_regex == null) { - for ($i = 0, $count = count($this->_patterns); $i < $count; $i++) { - $this->_patterns[$i] = '(' . str_replace( - array('/', '(', ')'), - array('\/', '\(', '\)'), - $this->_patterns[$i]) . ')'; - } - $this->_regex = "/" . implode("|", $this->_patterns) . "/" . $this->_getPerlMatchingFlags(); - } - return $this->_regex; - } - - /** - * Accessor for perl regex mode flags to use. - * @return string Perl regex flags. - * @access private - */ - function _getPerlMatchingFlags() { - return ($this->_case ? "msS" : "msSi"); - } -} - -/** - * States for a stack machine. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleStateStack { - var $_stack; - - /** - * Constructor. Starts in named state. - * @param string $start Starting state name. - * @access public - */ - function SimpleStateStack($start) { - $this->_stack = array($start); - } - - /** - * Accessor for current state. - * @return string State. - * @access public - */ - function getCurrent() { - return $this->_stack[count($this->_stack) - 1]; - } - - /** - * Adds a state to the stack and sets it - * to be the current state. - * @param string $state New state. - * @access public - */ - function enter($state) { - array_push($this->_stack, $state); - } - - /** - * Leaves the current state and reverts - * to the previous one. - * @return boolean False if we drop off - * the bottom of the list. - * @access public - */ - function leave() { - if (count($this->_stack) == 1) { - return false; - } - array_pop($this->_stack); - return true; - } -} - -/** - * Accepts text and breaks it into tokens. - * Some optimisation to make the sure the - * content is only scanned by the PHP regex - * parser once. Lexer modes must not start - * with leading underscores. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleLexer { - var $_regexes; - var $_parser; - var $_mode; - var $_mode_handlers; - var $_case; - - /** - * Sets up the lexer in case insensitive matching - * by default. - * @param SimpleSaxParser $parser Handling strategy by - * reference. - * @param string $start Starting handler. - * @param boolean $case True for case sensitive. - * @access public - */ - function SimpleLexer(&$parser, $start = "accept", $case = false) { - $this->_case = $case; - $this->_regexes = array(); - $this->_parser = &$parser; - $this->_mode = &new SimpleStateStack($start); - $this->_mode_handlers = array($start => $start); - } - - /** - * Adds a token search pattern for a particular - * parsing mode. The pattern does not change the - * current mode. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @access public - */ - function addPattern($pattern, $mode = "accept") { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new ParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern); - if (! isset($this->_mode_handlers[$mode])) { - $this->_mode_handlers[$mode] = $mode; - } - } - - /** - * Adds a pattern that will enter a new parsing - * mode. Useful for entering parenthesis, strings, - * tags, etc. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @param string $new_mode Change parsing to this new - * nested mode. - * @access public - */ - function addEntryPattern($pattern, $mode, $new_mode) { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new ParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern, $new_mode); - if (! isset($this->_mode_handlers[$new_mode])) { - $this->_mode_handlers[$new_mode] = $new_mode; - } - } - - /** - * Adds a pattern that will exit the current mode - * and re-enter the previous one. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Mode to leave. - * @access public - */ - function addExitPattern($pattern, $mode) { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new ParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern, "__exit"); - if (! isset($this->_mode_handlers[$mode])) { - $this->_mode_handlers[$mode] = $mode; - } - } - - /** - * Adds a pattern that has a special mode. Acts as an entry - * and exit pattern in one go, effectively calling a special - * parser handler for this token only. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @param string $special Use this mode for this one token. - * @access public - */ - function addSpecialPattern($pattern, $mode, $special) { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new ParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern, "_$special"); - if (! isset($this->_mode_handlers[$special])) { - $this->_mode_handlers[$special] = $special; - } - } - - /** - * Adds a mapping from a mode to another handler. - * @param string $mode Mode to be remapped. - * @param string $handler New target handler. - * @access public - */ - function mapHandler($mode, $handler) { - $this->_mode_handlers[$mode] = $handler; - } - - /** - * Splits the page text into tokens. Will fail - * if the handlers report an error or if no - * content is consumed. If successful then each - * unparsed and parsed token invokes a call to the - * held listener. - * @param string $raw Raw HTML text. - * @return boolean True on success, else false. - * @access public - */ - function parse($raw) { - if (! isset($this->_parser)) { - return false; - } - $length = strlen($raw); - while (is_array($parsed = $this->_reduce($raw))) { - list($raw, $unmatched, $matched, $mode) = $parsed; - if (! $this->_dispatchTokens($unmatched, $matched, $mode)) { - return false; - } - if ($raw === '') { - return true; - } - if (strlen($raw) == $length) { - return false; - } - $length = strlen($raw); - } - if (! $parsed) { - return false; - } - return $this->_invokeParser($raw, LEXER_UNMATCHED); - } - - /** - * Sends the matched token and any leading unmatched - * text to the parser changing the lexer to a new - * mode if one is listed. - * @param string $unmatched Unmatched leading portion. - * @param string $matched Actual token match. - * @param string $mode Mode after match. A boolean - * false mode causes no change. - * @return boolean False if there was any error - * from the parser. - * @access private - */ - function _dispatchTokens($unmatched, $matched, $mode = false) { - if (! $this->_invokeParser($unmatched, LEXER_UNMATCHED)) { - return false; - } - if (is_bool($mode)) { - return $this->_invokeParser($matched, LEXER_MATCHED); - } - if ($this->_isModeEnd($mode)) { - if (! $this->_invokeParser($matched, LEXER_EXIT)) { - return false; - } - return $this->_mode->leave(); - } - if ($this->_isSpecialMode($mode)) { - $this->_mode->enter($this->_decodeSpecial($mode)); - if (! $this->_invokeParser($matched, LEXER_SPECIAL)) { - return false; - } - return $this->_mode->leave(); - } - $this->_mode->enter($mode); - return $this->_invokeParser($matched, LEXER_ENTER); - } - - /** - * Tests to see if the new mode is actually to leave - * the current mode and pop an item from the matching - * mode stack. - * @param string $mode Mode to test. - * @return boolean True if this is the exit mode. - * @access private - */ - function _isModeEnd($mode) { - return ($mode === "__exit"); - } - - /** - * Test to see if the mode is one where this mode - * is entered for this token only and automatically - * leaves immediately afterwoods. - * @param string $mode Mode to test. - * @return boolean True if this is the exit mode. - * @access private - */ - function _isSpecialMode($mode) { - return (strncmp($mode, "_", 1) == 0); - } - - /** - * Strips the magic underscore marking single token - * modes. - * @param string $mode Mode to decode. - * @return string Underlying mode name. - * @access private - */ - function _decodeSpecial($mode) { - return substr($mode, 1); - } - - /** - * Calls the parser method named after the current - * mode. Empty content will be ignored. The lexer - * has a parser handler for each mode in the lexer. - * @param string $content Text parsed. - * @param boolean $is_match Token is recognised rather - * than unparsed data. - * @access private - */ - function _invokeParser($content, $is_match) { - if (($content === '') || ($content === false)) { - return true; - } - $handler = $this->_mode_handlers[$this->_mode->getCurrent()]; - return $this->_parser->$handler($content, $is_match); - } - - /** - * Tries to match a chunk of text and if successful - * removes the recognised chunk and any leading - * unparsed data. Empty strings will not be matched. - * @param string $raw The subject to parse. This is the - * content that will be eaten. - * @return array/boolean Three item list of unparsed - * content followed by the - * recognised token and finally the - * action the parser is to take. - * True if no match, false if there - * is a parsing error. - * @access private - */ - function _reduce($raw) { - if ($action = $this->_regexes[$this->_mode->getCurrent()]->match($raw, $match)) { - $unparsed_character_count = strpos($raw, $match); - $unparsed = substr($raw, 0, $unparsed_character_count); - $raw = substr($raw, $unparsed_character_count + strlen($match)); - return array($raw, $unparsed, $match, $action); - } - return true; - } -} - -/** - * Breaks HTML into SAX events. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHtmlLexer extends SimpleLexer { - - /** - * Sets up the lexer with case insensitive matching - * and adds the HTML handlers. - * @param SimpleSaxParser $parser Handling strategy by - * reference. - * @access public - */ - function SimpleHtmlLexer(&$parser) { - $this->SimpleLexer($parser, 'text'); - $this->mapHandler('text', 'acceptTextToken'); - $this->_addSkipping(); - foreach ($this->_getParsedTags() as $tag) { - $this->_addTag($tag); - } - $this->_addInTagTokens(); - } - - /** - * List of parsed tags. Others are ignored. - * @return array List of searched for tags. - * @access private - */ - function _getParsedTags() { - return array('a', 'base', 'title', 'form', 'input', 'button', 'textarea', 'select', - 'option', 'frameset', 'frame', 'label'); - } - - /** - * The lexer has to skip certain sections such - * as server code, client code and styles. - * @access private - */ - function _addSkipping() { - $this->mapHandler('css', 'ignore'); - $this->addEntryPattern('addExitPattern('', 'css'); - $this->mapHandler('js', 'ignore'); - $this->addEntryPattern('addExitPattern('', 'js'); - $this->mapHandler('comment', 'ignore'); - $this->addEntryPattern('', 'comment'); - } - - /** - * Pattern matches to start and end a tag. - * @param string $tag Name of tag to scan for. - * @access private - */ - function _addTag($tag) { - $this->addSpecialPattern("", 'text', 'acceptEndToken'); - $this->addEntryPattern("<$tag", 'text', 'tag'); - } - - /** - * Pattern matches to parse the inside of a tag - * including the attributes and their quoting. - * @access private - */ - function _addInTagTokens() { - $this->mapHandler('tag', 'acceptStartToken'); - $this->addSpecialPattern('\s+', 'tag', 'ignore'); - $this->_addAttributeTokens(); - $this->addExitPattern('/>', 'tag'); - $this->addExitPattern('>', 'tag'); - } - - /** - * Matches attributes that are either single quoted, - * double quoted or unquoted. - * @access private - */ - function _addAttributeTokens() { - $this->mapHandler('dq_attribute', 'acceptAttributeToken'); - $this->addEntryPattern('=\s*"', 'tag', 'dq_attribute'); - $this->addPattern("\\\\\"", 'dq_attribute'); - $this->addExitPattern('"', 'dq_attribute'); - $this->mapHandler('sq_attribute', 'acceptAttributeToken'); - $this->addEntryPattern("=\s*'", 'tag', 'sq_attribute'); - $this->addPattern("\\\\'", 'sq_attribute'); - $this->addExitPattern("'", 'sq_attribute'); - $this->mapHandler('uq_attribute', 'acceptAttributeToken'); - $this->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute'); - } -} - -/** - * Converts HTML tokens into selected SAX events. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHtmlSaxParser { - var $_lexer; - var $_listener; - var $_tag; - var $_attributes; - var $_current_attribute; - - /** - * Sets the listener. - * @param SimpleSaxListener $listener SAX event handler. - * @access public - */ - function SimpleHtmlSaxParser(&$listener) { - $this->_listener = &$listener; - $this->_lexer = &$this->createLexer($this); - $this->_tag = ''; - $this->_attributes = array(); - $this->_current_attribute = ''; - } - - /** - * Runs the content through the lexer which - * should call back to the acceptors. - * @param string $raw Page text to parse. - * @return boolean False if parse error. - * @access public - */ - function parse($raw) { - return $this->_lexer->parse($raw); - } - - /** - * Sets up the matching lexer. Starts in 'text' mode. - * @param SimpleSaxParser $parser Event generator, usually $self. - * @return SimpleLexer Lexer suitable for this parser. - * @access public - * @static - */ - function &createLexer(&$parser) { - $lexer = &new SimpleHtmlLexer($parser); - return $lexer; - } - - /** - * Accepts a token from the tag mode. If the - * starting element completes then the element - * is dispatched and the current attributes - * set back to empty. The element or attribute - * name is converted to lower case. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptStartToken($token, $event) { - if ($event == LEXER_ENTER) { - $this->_tag = strtolower(substr($token, 1)); - return true; - } - if ($event == LEXER_EXIT) { - $success = $this->_listener->startElement( - $this->_tag, - $this->_attributes); - $this->_tag = ''; - $this->_attributes = array(); - return $success; - } - if ($token != '=') { - $this->_current_attribute = strtolower(SimpleHtmlSaxParser::decodeHtml($token)); - $this->_attributes[$this->_current_attribute] = ''; - } - return true; - } - - /** - * Accepts a token from the end tag mode. - * The element name is converted to lower case. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptEndToken($token, $event) { - if (! preg_match('/<\/(.*)>/', $token, $matches)) { - return false; - } - return $this->_listener->endElement(strtolower($matches[1])); - } - - /** - * Part of the tag data. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptAttributeToken($token, $event) { - if ($this->_current_attribute) { - if ($event == LEXER_UNMATCHED) { - $this->_attributes[$this->_current_attribute] .= - SimpleHtmlSaxParser::decodeHtml($token); - } - if ($event == LEXER_SPECIAL) { - $this->_attributes[$this->_current_attribute] .= - preg_replace('/^=\s*/' , '', SimpleHtmlSaxParser::decodeHtml($token)); - } - } - return true; - } - - /** - * A character entity. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptEntityToken($token, $event) { - } - - /** - * Character data between tags regarded as - * important. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptTextToken($token, $event) { - return $this->_listener->addContent($token); - } - - /** - * Incoming data to be ignored. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function ignore($token, $event) { - return true; - } - - /** - * Decodes any HTML entities. - * @param string $html Incoming HTML. - * @return string Outgoing plain text. - * @access public - * @static - */ - function decodeHtml($html) { - return html_entity_decode($html, ENT_QUOTES); - } - - /** - * Turns HTML into text browser visible text. Images - * are converted to their alt text and tags are supressed. - * Entities are converted to their visible representation. - * @param string $html HTML to convert. - * @return string Plain text. - * @access public - * @static - */ - function normalise($html) { - $text = preg_replace('||', '', $html); - $text = preg_replace('|]*>.*?|', '', $text); - $text = preg_replace('|]*alt\s*=\s*"([^"]*)"[^>]*>|', ' \1 ', $text); - $text = preg_replace('|]*alt\s*=\s*\'([^\']*)\'[^>]*>|', ' \1 ', $text); - $text = preg_replace('|]*alt\s*=\s*([a-zA-Z_]+)[^>]*>|', ' \1 ', $text); - $text = preg_replace('|<[^>]*>|', '', $text); - $text = SimpleHtmlSaxParser::decodeHtml($text); - $text = preg_replace('|\s+|', ' ', $text); - return trim(trim($text), "\xA0"); // TODO: The \xAO is a  . Add a test for this. - } -} - -/** - * SAX event handler. - * @package SimpleTest - * @subpackage WebTester - * @abstract - */ -class SimpleSaxListener { - - /** - * Sets the document to write to. - * @access public - */ - function SimpleSaxListener() { - } - - /** - * Start of element event. - * @param string $name Element name. - * @param hash $attributes Name value pairs. - * Attributes without content - * are marked as true. - * @return boolean False on parse error. - * @access public - */ - function startElement($name, $attributes) { - } - - /** - * End of element event. - * @param string $name Element name. - * @return boolean False on parse error. - * @access public - */ - function endElement($name) { - } - - /** - * Unparsed, but relevant data. - * @param string $text May include unparsed tags. - * @return boolean False on parse error. - * @access public - */ - function addContent($text) { - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/reflection_php4.php b/tests/simpletest/reflection_php4.php deleted file mode 100644 index 6c93915af..000000000 --- a/tests/simpletest/reflection_php4.php +++ /dev/null @@ -1,136 +0,0 @@ -_interface = $interface; - } - - /** - * Checks that a class has been declared. - * @return boolean True if defined. - * @access public - */ - function classExists() { - return class_exists($this->_interface); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classExistsSansAutoload() { - return class_exists($this->_interface); - } - - /** - * Checks that a class or interface has been - * declared. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExists() { - return class_exists($this->_interface); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExistsSansAutoload() { - return class_exists($this->_interface); - } - - /** - * Gets the list of methods on a class or - * interface. - * @returns array List of method names. - * @access public - */ - function getMethods() { - return get_class_methods($this->_interface); - } - - /** - * Gets the list of interfaces from a class. If the - * class name is actually an interface then just that - * interface is returned. - * @returns array List of interfaces. - * @access public - */ - function getInterfaces() { - return array(); - } - - /** - * Finds the parent class name. - * @returns string Parent class name. - * @access public - */ - function getParent() { - return strtolower(get_parent_class($this->_interface)); - } - - /** - * Determines if the class is abstract, which for PHP 4 - * will never be the case. - * @returns boolean True if abstract. - * @access public - */ - function isAbstract() { - return false; - } - - /** - * Determines if the the entity is an interface, which for PHP 4 - * will never be the case. - * @returns boolean True if interface. - * @access public - */ - function isInterface() { - return false; - } - - /** - * Scans for final methods, but as it's PHP 4 there - * aren't any. - * @returns boolean True if the class has a final method. - * @access public - */ - function hasFinal() { - return false; - } - - /** - * Gets the source code matching the declaration - * of a method. - * @param string $method Method name. - * @access public - */ - function getSignature($method) { - return "function &$method()"; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/reflection_php5.php b/tests/simpletest/reflection_php5.php deleted file mode 100644 index 8383bccd3..000000000 --- a/tests/simpletest/reflection_php5.php +++ /dev/null @@ -1,380 +0,0 @@ -_interface = $interface; - } - - /** - * Checks that a class has been declared. Versions - * before PHP5.0.2 need a check that it's not really - * an interface. - * @return boolean True if defined. - * @access public - */ - function classExists() { - if (! class_exists($this->_interface)) { - return false; - } - $reflection = new ReflectionClass($this->_interface); - return ! $reflection->isInterface(); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classExistsSansAutoload() { - return class_exists($this->_interface, false); - } - - /** - * Checks that a class or interface has been - * declared. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExists() { - return $this->_classOrInterfaceExistsWithAutoload($this->_interface, true); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExistsSansAutoload() { - return $this->_classOrInterfaceExistsWithAutoload($this->_interface, false); - } - - /** - * Needed to select the autoload feature in PHP5 - * for classes created dynamically. - * @param string $interface Class or interface name. - * @param boolean $autoload True totriggerautoload. - * @return boolean True if interface defined. - * @access private - */ - function _classOrInterfaceExistsWithAutoload($interface, $autoload) { - if (function_exists('interface_exists')) { - if (interface_exists($this->_interface, $autoload)) { - return true; - } - } - return class_exists($this->_interface, $autoload); - } - - /** - * Gets the list of methods on a class or - * interface. - * @returns array List of method names. - * @access public - */ - function getMethods() { - return array_unique(get_class_methods($this->_interface)); - } - - /** - * Gets the list of interfaces from a class. If the - * class name is actually an interface then just that - * interface is returned. - * @returns array List of interfaces. - * @access public - */ - function getInterfaces() { - $reflection = new ReflectionClass($this->_interface); - if ($reflection->isInterface()) { - return array($this->_interface); - } - return $this->_onlyParents($reflection->getInterfaces()); - } - - /** - * Gets the list of methods for the implemented - * interfaces only. - * @returns array List of enforced method signatures. - * @access public - */ - function getInterfaceMethods() { - $methods = array(); - foreach ($this->getInterfaces() as $interface) { - $methods = array_merge($methods, get_class_methods($interface)); - } - return array_unique($methods); - } - - /** - * Checks to see if the method signature has to be tightly - * specified. - * @param string $method Method name. - * @returns boolean True if enforced. - * @access private - */ - function _isInterfaceMethod($method) { - return in_array($method, $this->getInterfaceMethods()); - } - - /** - * Finds the parent class name. - * @returns string Parent class name. - * @access public - */ - function getParent() { - $reflection = new ReflectionClass($this->_interface); - $parent = $reflection->getParentClass(); - if ($parent) { - return $parent->getName(); - } - return false; - } - - /** - * Trivially determines if the class is abstract. - * @returns boolean True if abstract. - * @access public - */ - function isAbstract() { - $reflection = new ReflectionClass($this->_interface); - return $reflection->isAbstract(); - } - - /** - * Trivially determines if the class is an interface. - * @returns boolean True if interface. - * @access public - */ - function isInterface() { - $reflection = new ReflectionClass($this->_interface); - return $reflection->isInterface(); - } - - /** - * Scans for final methods, as they screw up inherited - * mocks by not allowing you to override them. - * @returns boolean True if the class has a final method. - * @access public - */ - function hasFinal() { - $reflection = new ReflectionClass($this->_interface); - foreach ($reflection->getMethods() as $method) { - if ($method->isFinal()) { - return true; - } - } - return false; - } - - /** - * Whittles a list of interfaces down to only the - * necessary top level parents. - * @param array $interfaces Reflection API interfaces - * to reduce. - * @returns array List of parent interface names. - * @access private - */ - function _onlyParents($interfaces) { - $parents = array(); - $blacklist = array(); - foreach ($interfaces as $interface) { - foreach($interfaces as $possible_parent) { - if ($interface->getName() == $possible_parent->getName()) { - continue; - } - if ($interface->isSubClassOf($possible_parent)) { - $blacklist[$possible_parent->getName()] = true; - } - } - if (!isset($blacklist[$interface->getName()])) { - $parents[] = $interface->getName(); - } - } - return $parents; - } - - /** - * Checks whether a method is abstract or not. - * @param string $name Method name. - * @return bool true if method is abstract, else false - * @access private - */ - function _isAbstractMethod($name) { - $interface = new ReflectionClass($this->_interface); - if (! $interface->hasMethod($name)) { - return false; - } - return $interface->getMethod($name)->isAbstract(); - } - - /** - * Checks whether a method is the constructor. - * @param string $name Method name. - * @return bool true if method is the constructor - * @access private - */ - function _isConstructor($name) { - return ($name == '__construct') || ($name == $this->_interface); - } - - /** - * Checks whether a method is abstract in all parents or not. - * @param string $name Method name. - * @return bool true if method is abstract in parent, else false - * @access private - */ - function _isAbstractMethodInParents($name) { - $interface = new ReflectionClass($this->_interface); - $parent = $interface->getParentClass(); - while($parent) { - if (! $parent->hasMethod($name)) { - return false; - } - if ($parent->getMethod($name)->isAbstract()) { - return true; - } - $parent = $parent->getParentClass(); - } - return false; - } - - /** - * Checks whether a method is static or not. - * @param string $name Method name - * @return bool true if method is static, else false - * @access private - */ - function _isStaticMethod($name) { - $interface = new ReflectionClass($this->_interface); - if (! $interface->hasMethod($name)) { - return false; - } - return $interface->getMethod($name)->isStatic(); - } - - /** - * Writes the source code matching the declaration - * of a method. - * @param string $name Method name. - * @return string Method signature up to last - * bracket. - * @access public - */ - function getSignature($name) { - if ($name == '__set') { - return 'function __set($key, $value)'; - } - if ($name == '__call') { - return 'function __call($method, $arguments)'; - } - if (version_compare(phpversion(), '5.1.0', '>=')) { - if (in_array($name, array('__get', '__isset', $name == '__unset'))) { - return "function {$name}(\$key)"; - } - } - if ($name == '__toString') { - return "function $name()"; - } - if ($this->_isInterfaceMethod($name) || - $this->_isAbstractMethod($name) || - $this->_isAbstractMethodInParents($name) || - $this->_isStaticMethod($name)) { - return $this->_getFullSignature($name); - } - return "function $name()"; - } - - /** - * For a signature specified in an interface, full - * details must be replicated to be a valid implementation. - * @param string $name Method name. - * @return string Method signature up to last - * bracket. - * @access private - */ - function _getFullSignature($name) { - $interface = new ReflectionClass($this->_interface); - $method = $interface->getMethod($name); - $reference = $method->returnsReference() ? '&' : ''; - $static = $method->isStatic() ? 'static ' : ''; - return "{$static}function $reference$name(" . - implode(', ', $this->_getParameterSignatures($method)) . - ")"; - } - - /** - * Gets the source code for each parameter. - * @param ReflectionMethod $method Method object from - * reflection API - * @return array List of strings, each - * a snippet of code. - * @access private - */ - function _getParameterSignatures($method) { - $signatures = array(); - foreach ($method->getParameters() as $parameter) { - $signature = ''; - $type = $parameter->getClass(); - if (is_null($type) && version_compare(phpversion(), '5.1.0', '>=') && $parameter->isArray()) { - $signature .= 'array '; - } elseif (!is_null($type)) { - $signature .= $type->getName() . ' '; - } - if ($parameter->isPassedByReference()) { - $signature .= '&'; - } - $signature .= '$' . $this->_suppressSpurious($parameter->getName()); - if ($this->_isOptional($parameter)) { - $signature .= ' = null'; - } - $signatures[] = $signature; - } - return $signatures; - } - - /** - * The SPL library has problems with the - * Reflection library. In particular, you can - * get extra characters in parameter names :(. - * @param string $name Parameter name. - * @return string Cleaner name. - * @access private - */ - function _suppressSpurious($name) { - return str_replace(array('[', ']', ' '), '', $name); - } - - /** - * Test of a reflection parameter being optional - * that works with early versions of PHP5. - * @param reflectionParameter $parameter Is this optional. - * @return boolean True if optional. - * @access private - */ - function _isOptional($parameter) { - if (method_exists($parameter, 'isOptional')) { - return $parameter->isOptional(); - } - return false; - } -} -?> diff --git a/tests/simpletest/remote.php b/tests/simpletest/remote.php deleted file mode 100644 index 8889ed7bf..000000000 --- a/tests/simpletest/remote.php +++ /dev/null @@ -1,117 +0,0 @@ -_url = $url; - $this->_dry_url = $dry_url ? $dry_url : $url; - $this->_size = false; - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->_url; - } - - /** - * Runs the top level test for this class. Currently - * reads the data as a single chunk. I'll fix this - * once I have added iteration to the browser. - * @param SimpleReporter $reporter Target of test results. - * @returns boolean True if no failures. - * @access public - */ - function run(&$reporter) { - $browser = &$this->_createBrowser(); - $xml = $browser->get($this->_url); - if (! $xml) { - trigger_error('Cannot read remote test URL [' . $this->_url . ']'); - return false; - } - $parser = &$this->_createParser($reporter); - if (! $parser->parse($xml)) { - trigger_error('Cannot parse incoming XML from [' . $this->_url . ']'); - return false; - } - return true; - } - - /** - * Creates a new web browser object for fetching - * the XML report. - * @return SimpleBrowser New browser. - * @access protected - */ - function &_createBrowser() { - $browser = &new SimpleBrowser(); - return $browser; - } - - /** - * Creates the XML parser. - * @param SimpleReporter $reporter Target of test results. - * @return SimpleTestXmlListener XML reader. - * @access protected - */ - function &_createParser(&$reporter) { - $parser = &new SimpleTestXmlParser($reporter); - return $parser; - } - - /** - * Accessor for the number of subtests. - * @return integer Number of test cases. - * @access public - */ - function getSize() { - if ($this->_size === false) { - $browser = &$this->_createBrowser(); - $xml = $browser->get($this->_dry_url); - if (! $xml) { - trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']'); - return false; - } - $reporter = &new SimpleReporter(); - $parser = &$this->_createParser($reporter); - if (! $parser->parse($xml)) { - trigger_error('Cannot parse incoming XML from [' . $this->_dry_url . ']'); - return false; - } - $this->_size = $reporter->getTestCaseCount(); - } - return $this->_size; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/reporter.php b/tests/simpletest/reporter.php deleted file mode 100644 index a13eff8cf..000000000 --- a/tests/simpletest/reporter.php +++ /dev/null @@ -1,447 +0,0 @@ -SimpleReporter(); - $this->_character_set = $character_set; - } - - /** - * Paints the top of the web page setting the - * title to the name of the starting test. - * @param string $test_name Name class of test. - * @access public - */ - function paintHeader($test_name) { - $this->sendNoCacheHeaders(); - print ""; - print "\n\n$test_name\n"; - print "\n"; - print "\n"; - print "\n\n"; - print "

$test_name

\n"; - flush(); - } - - /** - * Send the headers necessary to ensure the page is - * reloaded on every request. Otherwise you could be - * scratching your head over out of date test data. - * @access public - * @static - */ - function sendNoCacheHeaders() { - if (! headers_sent()) { - header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); - header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); - header("Cache-Control: no-store, no-cache, must-revalidate"); - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); - } - } - - /** - * Paints the CSS. Add additional styles here. - * @return string CSS code as text. - * @access protected - */ - function _getCss() { - return ".fail { background-color: inherit; color: red; }" . - ".pass { background-color: inherit; color: green; }" . - " pre { background-color: lightgray; color: inherit; }"; - } - - /** - * Paints the end of the test with a summary of - * the passes and failures. - * @param string $test_name Name class of test. - * @access public - */ - function paintFooter($test_name) { - $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green"); - print "
"; - print $this->getTestCaseProgress() . "/" . $this->getTestCaseCount(); - print " test cases complete:\n"; - print "" . $this->getPassCount() . " passes, "; - print "" . $this->getFailCount() . " fails and "; - print "" . $this->getExceptionCount() . " exceptions."; - print "
\n"; - print "\n\n"; - } - - /** - * Paints the test failure with a breadcrumbs - * trail of the nesting test suites below the - * top level test. - * @param string $message Failure message displayed in - * the context of the other tests. - * @access public - */ - function paintFail($message) { - parent::paintFail($message); - print "Fail: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . $this->_htmlEntities($message) . "
\n"; - } - - /** - * Paints a PHP error. - * @param string $message Message is ignored. - * @access public - */ - function paintError($message) { - parent::paintError($message); - print "Exception: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . $this->_htmlEntities($message) . "
\n"; - } - - /** - * Paints a PHP exception. - * @param Exception $exception Exception to display. - * @access public - */ - function paintException($exception) { - parent::paintException($exception); - print "Exception: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - $message = 'Unexpected exception of type [' . get_class($exception) . - '] with message ['. $exception->getMessage() . - '] in ['. $exception->getFile() . - ' line ' . $exception->getLine() . ']'; - print " -> " . $this->_htmlEntities($message) . "
\n"; - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - parent::paintSkip($message); - print "Skipped: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . $this->_htmlEntities($message) . "
\n"; - } - - /** - * Paints formatted text such as dumped variables. - * @param string $message Text to show. - * @access public - */ - function paintFormattedMessage($message) { - print '
' . $this->_htmlEntities($message) . '
'; - } - - /** - * Character set adjusted entity conversion. - * @param string $message Plain text or Unicode message. - * @return string Browser readable message. - * @access protected - */ - function _htmlEntities($message) { - return htmlentities($message, ENT_COMPAT, $this->_character_set); - } -} - -/** - * Sample minimal test displayer. Generates only - * failure messages and a pass count. For command - * line use. I've tried to make it look like JUnit, - * but I wanted to output the errors as they arrived - * which meant dropping the dots. - * @package SimpleTest - * @subpackage UnitTester - */ -class TextReporter extends SimpleReporter { - - /** - * Does nothing yet. The first output will - * be sent on the first test start. - * @access public - */ - function TextReporter() { - $this->SimpleReporter(); - } - - /** - * Paints the title only. - * @param string $test_name Name class of test. - * @access public - */ - function paintHeader($test_name) { - if (! SimpleReporter::inCli()) { - header('Content-type: text/plain'); - } - print "$test_name\n"; - flush(); - } - - /** - * Paints the end of the test with a summary of - * the passes and failures. - * @param string $test_name Name class of test. - * @access public - */ - function paintFooter($test_name) { - if ($this->getFailCount() + $this->getExceptionCount() == 0) { - print "OK\n"; - } else { - print "FAILURES!!!\n"; - } - print "Test cases run: " . $this->getTestCaseProgress() . - "/" . $this->getTestCaseCount() . - ", Passes: " . $this->getPassCount() . - ", Failures: " . $this->getFailCount() . - ", Exceptions: " . $this->getExceptionCount() . "\n"; - } - - /** - * Paints the test failure as a stack trace. - * @param string $message Failure message displayed in - * the context of the other tests. - * @access public - */ - function paintFail($message) { - parent::paintFail($message); - print $this->getFailCount() . ") $message\n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); - print "\n"; - } - - /** - * Paints a PHP error or exception. - * @param string $message Message to be shown. - * @access public - * @abstract - */ - function paintError($message) { - parent::paintError($message); - print "Exception " . $this->getExceptionCount() . "!\n$message\n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); - print "\n"; - } - - /** - * Paints a PHP error or exception. - * @param Exception $exception Exception to describe. - * @access public - * @abstract - */ - function paintException($exception) { - parent::paintException($exception); - $message = 'Unexpected exception of type [' . get_class($exception) . - '] with message ['. $exception->getMessage() . - '] in ['. $exception->getFile() . - ' line ' . $exception->getLine() . ']'; - print "Exception " . $this->getExceptionCount() . "!\n$message\n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); - print "\n"; - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - parent::paintSkip($message); - print "Skip: $message\n"; - } - - /** - * Paints formatted text such as dumped variables. - * @param string $message Text to show. - * @access public - */ - function paintFormattedMessage($message) { - print "$message\n"; - flush(); - } -} - -/** - * Runs just a single test group, a single case or - * even a single test within that case. - * @package SimpleTest - * @subpackage UnitTester - */ -class SelectiveReporter extends SimpleReporterDecorator { - var $_just_this_case = false; - var $_just_this_test = false; - var $_on; - - /** - * Selects the test case or group to be run, - * and optionally a specific test. - * @param SimpleScorer $reporter Reporter to receive events. - * @param string $just_this_case Only this case or group will run. - * @param string $just_this_test Only this test method will run. - */ - function SelectiveReporter(&$reporter, $just_this_case = false, $just_this_test = false) { - if (isset($just_this_case) && $just_this_case) { - $this->_just_this_case = strtolower($just_this_case); - $this->_off(); - } else { - $this->_on(); - } - if (isset($just_this_test) && $just_this_test) { - $this->_just_this_test = strtolower($just_this_test); - } - $this->SimpleReporterDecorator($reporter); - } - - /** - * Compares criteria to actual the case/group name. - * @param string $test_case The incoming test. - * @return boolean True if matched. - * @access protected - */ - function _matchesTestCase($test_case) { - return $this->_just_this_case == strtolower($test_case); - } - - /** - * Compares criteria to actual the test name. If no - * name was specified at the beginning, then all tests - * can run. - * @param string $method The incoming test method. - * @return boolean True if matched. - * @access protected - */ - function _shouldRunTest($test_case, $method) { - if ($this->_isOn() || $this->_matchesTestCase($test_case)) { - if ($this->_just_this_test) { - return $this->_just_this_test == strtolower($method); - } else { - return true; - } - } - return false; - } - - /** - * Switch on testing for the group or subgroup. - * @access private - */ - function _on() { - $this->_on = true; - } - - /** - * Switch off testing for the group or subgroup. - * @access private - */ - function _off() { - $this->_on = false; - } - - /** - * Is this group actually being tested? - * @return boolean True if the current test group is active. - * @access private - */ - function _isOn() { - return $this->_on; - } - - /** - * Veto everything that doesn't match the method wanted. - * @param string $test_case Name of test case. - * @param string $method Name of test method. - * @return boolean True if test should be run. - * @access public - */ - function shouldInvoke($test_case, $method) { - if ($this->_shouldRunTest($test_case, $method)) { - return $this->_reporter->shouldInvoke($test_case, $method); - } - return false; - } - - /** - * Paints the start of a group test. - * @param string $test_case Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_case, $size) { - if ($this->_just_this_case && $this->_matchesTestCase($test_case)) { - $this->_on(); - } - $this->_reporter->paintGroupStart($test_case, $size); - } - - /** - * Paints the end of a group test. - * @param string $test_case Name of test or other label. - * @access public - */ - function paintGroupEnd($test_case) { - $this->_reporter->paintGroupEnd($test_case); - if ($this->_just_this_case && $this->_matchesTestCase($test_case)) { - $this->_off(); - } - } -} - -/** - * Suppresses skip messages. - * @package SimpleTest - * @subpackage UnitTester - */ -class NoSkipsReporter extends SimpleReporterDecorator { - - /** - * Does nothing. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { } -} -?> \ No newline at end of file diff --git a/tests/simpletest/scorer.php b/tests/simpletest/scorer.php deleted file mode 100644 index cc1331b89..000000000 --- a/tests/simpletest/scorer.php +++ /dev/null @@ -1,863 +0,0 @@ -_passes = 0; - $this->_fails = 0; - $this->_exceptions = 0; - $this->_is_dry_run = false; - } - - /** - * Signals that the next evaluation will be a dry - * run. That is, the structure events will be - * recorded, but no tests will be run. - * @param boolean $is_dry Dry run if true. - * @access public - */ - function makeDry($is_dry = true) { - $this->_is_dry_run = $is_dry; - } - - /** - * The reporter has a veto on what should be run. - * @param string $test_case_name name of test case. - * @param string $method Name of test method. - * @access public - */ - function shouldInvoke($test_case_name, $method) { - return ! $this->_is_dry_run; - } - - /** - * Can wrap the invoker in preperation for running - * a test. - * @param SimpleInvoker $invoker Individual test runner. - * @return SimpleInvoker Wrapped test runner. - * @access public - */ - function &createInvoker(&$invoker) { - return $invoker; - } - - /** - * Accessor for current status. Will be false - * if there have been any failures or exceptions. - * Used for command line tools. - * @return boolean True if no failures. - * @access public - */ - function getStatus() { - if ($this->_exceptions + $this->_fails > 0) { - return false; - } - return true; - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintGroupEnd($test_name) { - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($test_name) { - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($test_name) { - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodStart($test_name) { - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodEnd($test_name) { - } - - /** - * Increments the pass count. - * @param string $message Message is ignored. - * @access public - */ - function paintPass($message) { - $this->_passes++; - } - - /** - * Increments the fail count. - * @param string $message Message is ignored. - * @access public - */ - function paintFail($message) { - $this->_fails++; - } - - /** - * Deals with PHP 4 throwing an error. - * @param string $message Text of error formatted by - * the test case. - * @access public - */ - function paintError($message) { - $this->_exceptions++; - } - - /** - * Deals with PHP 5 throwing an exception. - * @param Exception $exception The actual exception thrown. - * @access public - */ - function paintException($exception) { - $this->_exceptions++; - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - } - - /** - * Accessor for the number of passes so far. - * @return integer Number of passes. - * @access public - */ - function getPassCount() { - return $this->_passes; - } - - /** - * Accessor for the number of fails so far. - * @return integer Number of fails. - * @access public - */ - function getFailCount() { - return $this->_fails; - } - - /** - * Accessor for the number of untrapped errors - * so far. - * @return integer Number of exceptions. - * @access public - */ - function getExceptionCount() { - return $this->_exceptions; - } - - /** - * Paints a simple supplementary message. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - } - - /** - * Paints a formatted ASCII message such as a - * variable dump. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - } - - /** - * By default just ignores user generated events. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @access public - */ - function paintSignal($type, $payload) { - } -} - -/** - * Recipient of generated test messages that can display - * page footers and headers. Also keeps track of the - * test nesting. This is the main base class on which - * to build the finished test (page based) displays. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleReporter extends SimpleScorer { - var $_test_stack; - var $_size; - var $_progress; - - /** - * Starts the display with no results in. - * @access public - */ - function SimpleReporter() { - $this->SimpleScorer(); - $this->_test_stack = array(); - $this->_size = null; - $this->_progress = 0; - } - - /** - * Gets the formatter for variables and other small - * generic data items. - * @return SimpleDumper Formatter. - * @access public - */ - function getDumper() { - return new SimpleDumper(); - } - - /** - * Paints the start of a group test. Will also paint - * the page header and footer if this is the - * first test. Will stash the size if the first - * start. - * @param string $test_name Name of test that is starting. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - if (! isset($this->_size)) { - $this->_size = $size; - } - if (count($this->_test_stack) == 0) { - $this->paintHeader($test_name); - } - $this->_test_stack[] = $test_name; - } - - /** - * Paints the end of a group test. Will paint the page - * footer if the stack of tests has unwound. - * @param string $test_name Name of test that is ending. - * @param integer $progress Number of test cases ending. - * @access public - */ - function paintGroupEnd($test_name) { - array_pop($this->_test_stack); - if (count($this->_test_stack) == 0) { - $this->paintFooter($test_name); - } - } - - /** - * Paints the start of a test case. Will also paint - * the page header and footer if this is the - * first test. Will stash the size if the first - * start. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintCaseStart($test_name) { - if (! isset($this->_size)) { - $this->_size = 1; - } - if (count($this->_test_stack) == 0) { - $this->paintHeader($test_name); - } - $this->_test_stack[] = $test_name; - } - - /** - * Paints the end of a test case. Will paint the page - * footer if the stack of tests has unwound. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintCaseEnd($test_name) { - $this->_progress++; - array_pop($this->_test_stack); - if (count($this->_test_stack) == 0) { - $this->paintFooter($test_name); - } - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintMethodStart($test_name) { - $this->_test_stack[] = $test_name; - } - - /** - * Paints the end of a test method. Will paint the page - * footer if the stack of tests has unwound. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintMethodEnd($test_name) { - array_pop($this->_test_stack); - } - - /** - * Paints the test document header. - * @param string $test_name First test top level - * to start. - * @access public - * @abstract - */ - function paintHeader($test_name) { - } - - /** - * Paints the test document footer. - * @param string $test_name The top level test. - * @access public - * @abstract - */ - function paintFooter($test_name) { - } - - /** - * Accessor for internal test stack. For - * subclasses that need to see the whole test - * history for display purposes. - * @return array List of methods in nesting order. - * @access public - */ - function getTestList() { - return $this->_test_stack; - } - - /** - * Accessor for total test size in number - * of test cases. Null until the first - * test is started. - * @return integer Total number of cases at start. - * @access public - */ - function getTestCaseCount() { - return $this->_size; - } - - /** - * Accessor for the number of test cases - * completed so far. - * @return integer Number of ended cases. - * @access public - */ - function getTestCaseProgress() { - return $this->_progress; - } - - /** - * Static check for running in the comand line. - * @return boolean True if CLI. - * @access public - * @static - */ - function inCli() { - return php_sapi_name() == 'cli'; - } -} - -/** - * For modifying the behaviour of the visual reporters. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleReporterDecorator { - var $_reporter; - - /** - * Mediates between the reporter and the test case. - * @param SimpleScorer $reporter Reporter to receive events. - */ - function SimpleReporterDecorator(&$reporter) { - $this->_reporter = &$reporter; - } - - /** - * Signals that the next evaluation will be a dry - * run. That is, the structure events will be - * recorded, but no tests will be run. - * @param boolean $is_dry Dry run if true. - * @access public - */ - function makeDry($is_dry = true) { - $this->_reporter->makeDry($is_dry); - } - - /** - * Accessor for current status. Will be false - * if there have been any failures or exceptions. - * Used for command line tools. - * @return boolean True if no failures. - * @access public - */ - function getStatus() { - return $this->_reporter->getStatus(); - } - - /** - * The reporter has a veto on what should be run. - * @param string $test_case_name name of test case. - * @param string $method Name of test method. - * @return boolean True if test should be run. - * @access public - */ - function shouldInvoke($test_case_name, $method) { - return $this->_reporter->shouldInvoke($test_case_name, $method); - } - - /** - * Can wrap the invoker in preperation for running - * a test. - * @param SimpleInvoker $invoker Individual test runner. - * @return SimpleInvoker Wrapped test runner. - * @access public - */ - function &createInvoker(&$invoker) { - return $this->_reporter->createInvoker($invoker); - } - - /** - * Gets the formatter for variables and other small - * generic data items. - * @return SimpleDumper Formatter. - * @access public - */ - function getDumper() { - return $this->_reporter->getDumper(); - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - $this->_reporter->paintGroupStart($test_name, $size); - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintGroupEnd($test_name) { - $this->_reporter->paintGroupEnd($test_name); - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($test_name) { - $this->_reporter->paintCaseStart($test_name); - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($test_name) { - $this->_reporter->paintCaseEnd($test_name); - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodStart($test_name) { - $this->_reporter->paintMethodStart($test_name); - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodEnd($test_name) { - $this->_reporter->paintMethodEnd($test_name); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintPass($message) { - $this->_reporter->paintPass($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintFail($message) { - $this->_reporter->paintFail($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text of error formatted by - * the test case. - * @access public - */ - function paintError($message) { - $this->_reporter->paintError($message); - } - - /** - * Chains to the wrapped reporter. - * @param Exception $exception Exception to show. - * @access public - */ - function paintException($exception) { - $this->_reporter->paintException($exception); - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - $this->_reporter->paintSkip($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - $this->_reporter->paintMessage($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - $this->_reporter->paintFormattedMessage($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @return boolean Should return false if this - * type of signal should fail the - * test suite. - * @access public - */ - function paintSignal($type, &$payload) { - $this->_reporter->paintSignal($type, $payload); - } -} - -/** - * For sending messages to multiple reporters at - * the same time. - * @package SimpleTest - * @subpackage UnitTester - */ -class MultipleReporter { - var $_reporters = array(); - - /** - * Adds a reporter to the subscriber list. - * @param SimpleScorer $reporter Reporter to receive events. - * @access public - */ - function attachReporter(&$reporter) { - $this->_reporters[] = &$reporter; - } - - /** - * Signals that the next evaluation will be a dry - * run. That is, the structure events will be - * recorded, but no tests will be run. - * @param boolean $is_dry Dry run if true. - * @access public - */ - function makeDry($is_dry = true) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->makeDry($is_dry); - } - } - - /** - * Accessor for current status. Will be false - * if there have been any failures or exceptions. - * If any reporter reports a failure, the whole - * suite fails. - * @return boolean True if no failures. - * @access public - */ - function getStatus() { - for ($i = 0; $i < count($this->_reporters); $i++) { - if (! $this->_reporters[$i]->getStatus()) { - return false; - } - } - return true; - } - - /** - * The reporter has a veto on what should be run. - * It requires all reporters to want to run the method. - * @param string $test_case_name name of test case. - * @param string $method Name of test method. - * @access public - */ - function shouldInvoke($test_case_name, $method) { - for ($i = 0; $i < count($this->_reporters); $i++) { - if (! $this->_reporters[$i]->shouldInvoke($test_case_name, $method)) { - return false; - } - } - return true; - } - - /** - * Every reporter gets a chance to wrap the invoker. - * @param SimpleInvoker $invoker Individual test runner. - * @return SimpleInvoker Wrapped test runner. - * @access public - */ - function &createInvoker(&$invoker) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $invoker = &$this->_reporters[$i]->createInvoker($invoker); - } - return $invoker; - } - - /** - * Gets the formatter for variables and other small - * generic data items. - * @return SimpleDumper Formatter. - * @access public - */ - function getDumper() { - return new SimpleDumper(); - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintGroupStart($test_name, $size); - } - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintGroupEnd($test_name) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintGroupEnd($test_name); - } - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($test_name) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintCaseStart($test_name); - } - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($test_name) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintCaseEnd($test_name); - } - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodStart($test_name) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintMethodStart($test_name); - } - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodEnd($test_name) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintMethodEnd($test_name); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintPass($message) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintPass($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintFail($message) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintFail($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text of error formatted by - * the test case. - * @access public - */ - function paintError($message) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintError($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param Exception $exception Exception to display. - * @access public - */ - function paintException($exception) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintException($exception); - } - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintSkip($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintMessage($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintFormattedMessage($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @return boolean Should return false if this - * type of signal should fail the - * test suite. - * @access public - */ - function paintSignal($type, &$payload) { - for ($i = 0; $i < count($this->_reporters); $i++) { - $this->_reporters[$i]->paintSignal($type, $payload); - } - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/selector.php b/tests/simpletest/selector.php deleted file mode 100644 index de044b85a..000000000 --- a/tests/simpletest/selector.php +++ /dev/null @@ -1,137 +0,0 @@ -_name = $name; - } - - function getName() { - return $this->_name; - } - - /** - * Compares with name attribute of widget. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - return ($widget->getName() == $this->_name); - } -} - -/** - * Used to extract form elements for testing against. - * Searches by visible label or alt text. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleByLabel { - var $_label; - - /** - * Stashes the name for later comparison. - * @param string $label Visible text to match. - */ - function SimpleByLabel($label) { - $this->_label = $label; - } - - /** - * Comparison. Compares visible text of widget or - * related label. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - if (! method_exists($widget, 'isLabel')) { - return false; - } - return $widget->isLabel($this->_label); - } -} - -/** - * Used to extract form elements for testing against. - * Searches dy id attribute. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleById { - var $_id; - - /** - * Stashes the name for later comparison. - * @param string $id ID atribute to match. - */ - function SimpleById($id) { - $this->_id = $id; - } - - /** - * Comparison. Compares id attribute of widget. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - return $widget->isId($this->_id); - } -} - -/** - * Used to extract form elements for testing against. - * Searches by visible label, name or alt text. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleByLabelOrName { - var $_label; - - /** - * Stashes the name/label for later comparison. - * @param string $label Visible text to match. - */ - function SimpleByLabelOrName($label) { - $this->_label = $label; - } - - /** - * Comparison. Compares visible text of widget or - * related label or name. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - if (method_exists($widget, 'isLabel')) { - if ($widget->isLabel($this->_label)) { - return true; - } - } - return ($widget->getName() == $this->_label); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/shell_tester.php b/tests/simpletest/shell_tester.php deleted file mode 100644 index 7b98869ec..000000000 --- a/tests/simpletest/shell_tester.php +++ /dev/null @@ -1,333 +0,0 @@ -_output = false; - } - - /** - * Actually runs the command. Does not trap the - * error stream output as this need PHP 4.3+. - * @param string $command The actual command line - * to run. - * @return integer Exit code. - * @access public - */ - function execute($command) { - $this->_output = false; - exec($command, $this->_output, $ret); - return $ret; - } - - /** - * Accessor for the last output. - * @return string Output as text. - * @access public - */ - function getOutput() { - return implode("\n", $this->_output); - } - - /** - * Accessor for the last output. - * @return array Output as array of lines. - * @access public - */ - function getOutputAsList() { - return $this->_output; - } -} - -/** - * Test case for testing of command line scripts and - * utilities. Usually scripts that are external to the - * PHP code, but support it in some way. - * @package SimpleTest - * @subpackage UnitTester - */ -class ShellTestCase extends SimpleTestCase { - var $_current_shell; - var $_last_status; - var $_last_command; - - /** - * Creates an empty test case. Should be subclassed - * with test methods for a functional test case. - * @param string $label Name of test case. Will use - * the class name if none specified. - * @access public - */ - function ShellTestCase($label = false) { - $this->SimpleTestCase($label); - $this->_current_shell = &$this->_createShell(); - $this->_last_status = false; - $this->_last_command = ''; - } - - /** - * Executes a command and buffers the results. - * @param string $command Command to run. - * @return boolean True if zero exit code. - * @access public - */ - function execute($command) { - $shell = &$this->_getShell(); - $this->_last_status = $shell->execute($command); - $this->_last_command = $command; - return ($this->_last_status === 0); - } - - /** - * Dumps the output of the last command. - * @access public - */ - function dumpOutput() { - $this->dump($this->getOutput()); - } - - /** - * Accessor for the last output. - * @return string Output as text. - * @access public - */ - function getOutput() { - $shell = &$this->_getShell(); - return $shell->getOutput(); - } - - /** - * Accessor for the last output. - * @return array Output as array of lines. - * @access public - */ - function getOutputAsList() { - $shell = &$this->_getShell(); - return $shell->getOutputAsList(); - } - - /** - * Called from within the test methods to register - * passes and failures. - * @param boolean $result Pass on true. - * @param string $message Message to display describing - * the test state. - * @return boolean True on pass - * @access public - */ - function assertTrue($result, $message = false) { - return $this->assert(new TrueExpectation(), $result, $message); - } - - /** - * Will be true on false and vice versa. False - * is the PHP definition of false, so that null, - * empty strings, zero and an empty array all count - * as false. - * @param boolean $result Pass on false. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertFalse($result, $message = '%s') { - return $this->assert(new FalseExpectation(), $result, $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value only. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertEqual($first, $second, $message = "%s") { - return $this->assert( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * a different value. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotEqual($first, $second, $message = "%s") { - return $this->assert( - new NotEqualExpectation($first), - $second, - $message); - } - - /** - * Tests the last status code from the shell. - * @param integer $status Expected status of last - * command. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertExitCode($status, $message = "%s") { - $message = sprintf($message, "Expected status code of [$status] from [" . - $this->_last_command . "], but got [" . - $this->_last_status . "]"); - return $this->assertTrue($status === $this->_last_status, $message); - } - - /** - * Attempt to exactly match the combined STDERR and - * STDOUT output. - * @param string $expected Expected output. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertOutput($expected, $message = "%s") { - $shell = &$this->_getShell(); - return $this->assert( - new EqualExpectation($expected), - $shell->getOutput(), - $message); - } - - /** - * Scans the output for a Perl regex. If found - * anywhere it passes, else it fails. - * @param string $pattern Regex to search for. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertOutputPattern($pattern, $message = "%s") { - $shell = &$this->_getShell(); - return $this->assert( - new PatternExpectation($pattern), - $shell->getOutput(), - $message); - } - - /** - * If a Perl regex is found anywhere in the current - * output then a failure is generated, else a pass. - * @param string $pattern Regex to search for. - * @param $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoOutputPattern($pattern, $message = "%s") { - $shell = &$this->_getShell(); - return $this->assert( - new NoPatternExpectation($pattern), - $shell->getOutput(), - $message); - } - - /** - * File existence check. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertFileExists($path, $message = "%s") { - $message = sprintf($message, "File [$path] should exist"); - return $this->assertTrue(file_exists($path), $message); - } - - /** - * File non-existence check. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertFileNotExists($path, $message = "%s") { - $message = sprintf($message, "File [$path] should not exist"); - return $this->assertFalse(file_exists($path), $message); - } - - /** - * Scans a file for a Perl regex. If found - * anywhere it passes, else it fails. - * @param string $pattern Regex to search for. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertFilePattern($pattern, $path, $message = "%s") { - $shell = &$this->_getShell(); - return $this->assert( - new PatternExpectation($pattern), - implode('', file($path)), - $message); - } - - /** - * If a Perl regex is found anywhere in the named - * file then a failure is generated, else a pass. - * @param string $pattern Regex to search for. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoFilePattern($pattern, $path, $message = "%s") { - $shell = &$this->_getShell(); - return $this->assert( - new NoPatternExpectation($pattern), - implode('', file($path)), - $message); - } - - /** - * Accessor for current shell. Used for testing the - * the tester itself. - * @return Shell Current shell. - * @access protected - */ - function &_getShell() { - return $this->_current_shell; - } - - /** - * Factory for the shell to run the command on. - * @return Shell New shell object. - * @access protected - */ - function &_createShell() { - $shell = &new SimpleShell(); - return $shell; - } -} -?> diff --git a/tests/simpletest/simpletest.php b/tests/simpletest/simpletest.php deleted file mode 100644 index bab2c1a6a..000000000 --- a/tests/simpletest/simpletest.php +++ /dev/null @@ -1,478 +0,0 @@ -= 0) { - require_once(dirname(__FILE__) . '/reflection_php5.php'); -} else { - require_once(dirname(__FILE__) . '/reflection_php4.php'); -} -require_once(dirname(__FILE__) . '/default_reporter.php'); -require_once(dirname(__FILE__) . '/compatibility.php'); -/**#@-*/ - -/** - * Registry and test context. Includes a few - * global options that I'm slowly getting rid of. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleTest { - - /** - * Reads the SimpleTest version from the release file. - * @return string Version string. - * @static - * @access public - */ - function getVersion() { - $content = file(dirname(__FILE__) . '/VERSION'); - return trim($content[0]); - } - - /** - * Sets the name of a test case to ignore, usually - * because the class is an abstract case that should - * not be run. Once PHP4 is dropped this will disappear - * as a public method and "abstract" will rule. - * @param string $class Add a class to ignore. - * @static - * @access public - */ - function ignore($class) { - $registry = &SimpleTest::_getRegistry(); - $registry['IgnoreList'][strtolower($class)] = true; - } - - /** - * Scans the now complete ignore list, and adds - * all parent classes to the list. If a class - * is not a runnable test case, then it's parents - * wouldn't be either. This is syntactic sugar - * to cut down on ommissions of ignore()'s or - * missing abstract declarations. This cannot - * be done whilst loading classes wiithout forcing - * a particular order on the class declarations and - * the ignore() calls. It's just nice to have the ignore() - * calls at the top of the file before the actual declarations. - * @param array $classes Class names of interest. - * @static - * @access public - */ - function ignoreParentsIfIgnored($classes) { - $registry = &SimpleTest::_getRegistry(); - foreach ($classes as $class) { - if (SimpleTest::isIgnored($class)) { - $reflection = new SimpleReflection($class); - if ($parent = $reflection->getParent()) { - SimpleTest::ignore($parent); - } - } - } - } - - /** - * Puts the object to the global pool of 'preferred' objects - * which can be retrieved with SimpleTest :: preferred() method. - * Instances of the same class are overwritten. - * @param object $object Preferred object - * @static - * @access public - * @see preferred() - */ - function prefer(&$object) { - $registry = &SimpleTest::_getRegistry(); - $registry['Preferred'][] = &$object; - } - - /** - * Retrieves 'preferred' objects from global pool. Class filter - * can be applied in order to retrieve the object of the specific - * class - * @param array|string $classes Allowed classes or interfaces. - * @static - * @access public - * @return array|object|null - * @see prefer() - */ - function &preferred($classes) { - if (! is_array($classes)) { - $classes = array($classes); - } - $registry = &SimpleTest::_getRegistry(); - for ($i = count($registry['Preferred']) - 1; $i >= 0; $i--) { - foreach ($classes as $class) { - if (SimpleTestCompatibility::isA($registry['Preferred'][$i], $class)) { - return $registry['Preferred'][$i]; - } - } - } - return null; - } - - /** - * Test to see if a test case is in the ignore - * list. Quite obviously the ignore list should - * be a separate object and will be one day. - * This method is internal to SimpleTest. Don't - * use it. - * @param string $class Class name to test. - * @return boolean True if should not be run. - * @access public - * @static - */ - function isIgnored($class) { - $registry = &SimpleTest::_getRegistry(); - return isset($registry['IgnoreList'][strtolower($class)]); - } - - /** - * @deprecated - */ - function setMockBaseClass($mock_base) { - $registry = &SimpleTest::_getRegistry(); - $registry['MockBaseClass'] = $mock_base; - } - - /** - * @deprecated - */ - function getMockBaseClass() { - $registry = &SimpleTest::_getRegistry(); - return $registry['MockBaseClass']; - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set host - * to false to disable. This will take effect - * if there are no other proxy settings. - * @param string $proxy Proxy host as URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - * @access public - */ - function useProxy($proxy, $username = false, $password = false) { - $registry = &SimpleTest::_getRegistry(); - $registry['DefaultProxy'] = $proxy; - $registry['DefaultProxyUsername'] = $username; - $registry['DefaultProxyPassword'] = $password; - } - - /** - * Accessor for default proxy host. - * @return string Proxy URL. - * @access public - */ - function getDefaultProxy() { - $registry = &SimpleTest::_getRegistry(); - return $registry['DefaultProxy']; - } - - /** - * Accessor for default proxy username. - * @return string Proxy username for authentication. - * @access public - */ - function getDefaultProxyUsername() { - $registry = &SimpleTest::_getRegistry(); - return $registry['DefaultProxyUsername']; - } - - /** - * Accessor for default proxy password. - * @return string Proxy password for authentication. - * @access public - */ - function getDefaultProxyPassword() { - $registry = &SimpleTest::_getRegistry(); - return $registry['DefaultProxyPassword']; - } - - /** - * Accessor for global registry of options. - * @return hash All stored values. - * @access private - * @static - */ - function &_getRegistry() { - static $registry = false; - if (! $registry) { - $registry = SimpleTest::_getDefaults(); - } - return $registry; - } - - /** - * Accessor for the context of the current - * test run. - * @return SimpleTestContext Current test run. - * @access public - * @static - */ - function &getContext() { - static $context = false; - if (! $context) { - $context = new SimpleTestContext(); - } - return $context; - } - - /** - * Constant default values. - * @return hash All registry defaults. - * @access private - * @static - */ - function _getDefaults() { - return array( - 'StubBaseClass' => 'SimpleStub', - 'MockBaseClass' => 'SimpleMock', - 'IgnoreList' => array(), - 'DefaultProxy' => false, - 'DefaultProxyUsername' => false, - 'DefaultProxyPassword' => false, - 'Preferred' => array(new HtmlReporter(), new TextReporter(), new XmlReporter())); - } -} - -/** - * Container for all components for a specific - * test run. Makes things like error queues - * available to PHP event handlers, and also - * gets around some nasty reference issues in - * the mocks. - * @package SimpleTest - */ -class SimpleTestContext { - var $_test; - var $_reporter; - var $_resources; - - /** - * Clears down the current context. - * @access public - */ - function clear() { - $this->_resources = array(); - } - - /** - * Sets the current test case instance. This - * global instance can be used by the mock objects - * to send message to the test cases. - * @param SimpleTestCase $test Test case to register. - * @access public - */ - function setTest(&$test) { - $this->clear(); - $this->_test = &$test; - } - - /** - * Accessor for currently running test case. - * @return SimpleTestCase Current test. - * @access public - */ - function &getTest() { - return $this->_test; - } - - /** - * Sets the current reporter. This - * global instance can be used by the mock objects - * to send messages. - * @param SimpleReporter $reporter Reporter to register. - * @access public - */ - function setReporter(&$reporter) { - $this->clear(); - $this->_reporter = &$reporter; - } - - /** - * Accessor for current reporter. - * @return SimpleReporter Current reporter. - * @access public - */ - function &getReporter() { - return $this->_reporter; - } - - /** - * Accessor for the Singleton resource. - * @return object Global resource. - * @access public - * @static - */ - function &get($resource) { - if (! isset($this->_resources[$resource])) { - $this->_resources[$resource] = &new $resource(); - } - return $this->_resources[$resource]; - } -} - -/** - * Interrogates the stack trace to recover the - * failure point. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleStackTrace { - var $_prefixes; - - /** - * Stashes the list of target prefixes. - * @param array $prefixes List of method prefixes - * to search for. - */ - function SimpleStackTrace($prefixes) { - $this->_prefixes = $prefixes; - } - - /** - * Extracts the last method name that was not within - * Simpletest itself. Captures a stack trace if none given. - * @param array $stack List of stack frames. - * @return string Snippet of test report with line - * number and file. - * @access public - */ - function traceMethod($stack = false) { - $stack = $stack ? $stack : $this->_captureTrace(); - foreach ($stack as $frame) { - if ($this->_frameLiesWithinSimpleTestFolder($frame)) { - continue; - } - if ($this->_frameMatchesPrefix($frame)) { - return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']'; - } - } - return ''; - } - - /** - * Test to see if error is generated by SimpleTest itself. - * @param array $frame PHP stack frame. - * @return boolean True if a SimpleTest file. - * @access private - */ - function _frameLiesWithinSimpleTestFolder($frame) { - if (isset($frame['file'])) { - $path = substr(SIMPLE_TEST, 0, -1); - if (strpos($frame['file'], $path) === 0) { - if (dirname($frame['file']) == $path) { - return true; - } - } - } - return false; - } - - /** - * Tries to determine if the method call is an assert, etc. - * @param array $frame PHP stack frame. - * @return boolean True if matches a target. - * @access private - */ - function _frameMatchesPrefix($frame) { - foreach ($this->_prefixes as $prefix) { - if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) { - return true; - } - } - return false; - } - - /** - * Grabs a current stack trace. - * @return array Fulle trace. - * @access private - */ - function _captureTrace() { - if (function_exists('debug_backtrace')) { - return array_reverse(debug_backtrace()); - } - return array(); - } -} - -/** - * @package SimpleTest - * @subpackage UnitTester - * @deprecated - */ -class SimpleTestOptions extends SimpleTest { - - /** - * @deprecated - */ - function getVersion() { - return Simpletest::getVersion(); - } - - /** - * @deprecated - */ - function ignore($class) { - return Simpletest::ignore($class); - } - - /** - * @deprecated - */ - function isIgnored($class) { - return Simpletest::isIgnored($class); - } - - /** - * @deprecated - */ - function setMockBaseClass($mock_base) { - return Simpletest::setMockBaseClass($mock_base); - } - - /** - * @deprecated - */ - function getMockBaseClass() { - return Simpletest::getMockBaseClass(); - } - - /** - * @deprecated - */ - function useProxy($proxy, $username = false, $password = false) { - return Simpletest::useProxy($proxy, $username, $password); - } - - /** - * @deprecated - */ - function getDefaultProxy() { - return Simpletest::getDefaultProxy(); - } - - /** - * @deprecated - */ - function getDefaultProxyUsername() { - return Simpletest::getDefaultProxyUsername(); - } - - /** - * @deprecated - */ - function getDefaultProxyPassword() { - return Simpletest::getDefaultProxyPassword(); - } -} -?> diff --git a/tests/simpletest/socket.php b/tests/simpletest/socket.php deleted file mode 100644 index 3ad5a9ff4..000000000 --- a/tests/simpletest/socket.php +++ /dev/null @@ -1,216 +0,0 @@ -_clearError(); - } - - /** - * Test for an outstanding error. - * @return boolean True if there is an error. - * @access public - */ - function isError() { - return ($this->_error != ''); - } - - /** - * Accessor for an outstanding error. - * @return string Empty string if no error otherwise - * the error message. - * @access public - */ - function getError() { - return $this->_error; - } - - /** - * Sets the internal error. - * @param string Error message to stash. - * @access protected - */ - function _setError($error) { - $this->_error = $error; - } - - /** - * Resets the error state to no error. - * @access protected - */ - function _clearError() { - $this->_setError(''); - } -} - -/** - * Wrapper for TCP/IP socket. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSocket extends SimpleStickyError { - var $_handle; - var $_is_open = false; - var $_sent = ''; - var $lock_size; - - /** - * Opens a socket for reading and writing. - * @param string $host Hostname to send request to. - * @param integer $port Port on remote machine to open. - * @param integer $timeout Connection timeout in seconds. - * @param integer $block_size Size of chunk to read. - * @access public - */ - function SimpleSocket($host, $port, $timeout, $block_size = 255) { - $this->SimpleStickyError(); - if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) { - $this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds"); - return; - } - $this->_is_open = true; - $this->_block_size = $block_size; - SimpleTestCompatibility::setTimeout($this->_handle, $timeout); - } - - /** - * Writes some data to the socket and saves alocal copy. - * @param string $message String to send to socket. - * @return boolean True if successful. - * @access public - */ - function write($message) { - if ($this->isError() || ! $this->isOpen()) { - return false; - } - $count = fwrite($this->_handle, $message); - if (! $count) { - if ($count === false) { - $this->_setError('Cannot write to socket'); - $this->close(); - } - return false; - } - fflush($this->_handle); - $this->_sent .= $message; - return true; - } - - /** - * Reads data from the socket. The error suppresion - * is a workaround for PHP4 always throwing a warning - * with a secure socket. - * @return integer/boolean Incoming bytes. False - * on error. - * @access public - */ - function read() { - if ($this->isError() || ! $this->isOpen()) { - return false; - } - $raw = @fread($this->_handle, $this->_block_size); - if ($raw === false) { - $this->_setError('Cannot read from socket'); - $this->close(); - } - return $raw; - } - - /** - * Accessor for socket open state. - * @return boolean True if open. - * @access public - */ - function isOpen() { - return $this->_is_open; - } - - /** - * Closes the socket preventing further reads. - * Cannot be reopened once closed. - * @return boolean True if successful. - * @access public - */ - function close() { - $this->_is_open = false; - return fclose($this->_handle); - } - - /** - * Accessor for content so far. - * @return string Bytes sent only. - * @access public - */ - function getSent() { - return $this->_sent; - } - - /** - * Actually opens the low level socket. - * @param string $host Host to connect to. - * @param integer $port Port on host. - * @param integer $error_number Recipient of error code. - * @param string $error Recipoent of error message. - * @param integer $timeout Maximum time to wait for connection. - * @access protected - */ - function _openSocket($host, $port, &$error_number, &$error, $timeout) { - return @fsockopen($host, $port, $error_number, $error, $timeout); - } -} - -/** - * Wrapper for TCP/IP socket over TLS. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSecureSocket extends SimpleSocket { - - /** - * Opens a secure socket for reading and writing. - * @param string $host Hostname to send request to. - * @param integer $port Port on remote machine to open. - * @param integer $timeout Connection timeout in seconds. - * @access public - */ - function SimpleSecureSocket($host, $port, $timeout) { - $this->SimpleSocket($host, $port, $timeout); - } - - /** - * Actually opens the low level socket. - * @param string $host Host to connect to. - * @param integer $port Port on host. - * @param integer $error_number Recipient of error code. - * @param string $error Recipient of error message. - * @param integer $timeout Maximum time to wait for connection. - * @access protected - */ - function _openSocket($host, $port, &$error_number, &$error, $timeout) { - return parent::_openSocket("tls://$host", $port, $error_number, $error, $timeout); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/tag.php b/tests/simpletest/tag.php deleted file mode 100644 index 7bccae205..000000000 --- a/tests/simpletest/tag.php +++ /dev/null @@ -1,1418 +0,0 @@ -_name = strtolower(trim($name)); - $this->_attributes = $attributes; - $this->_content = ''; - } - - /** - * Check to see if the tag can have both start and - * end tags with content in between. - * @return boolean True if content allowed. - * @access public - */ - function expectEndTag() { - return true; - } - - /** - * The current tag should not swallow all content for - * itself as it's searchable page content. Private - * content tags are usually widgets that contain default - * values. - * @return boolean False as content is available - * to other tags by default. - * @access public - */ - function isPrivateContent() { - return false; - } - - /** - * Appends string content to the current content. - * @param string $content Additional text. - * @access public - */ - function addContent($content) { - $this->_content .= (string)$content; - } - - /** - * Adds an enclosed tag to the content. - * @param SimpleTag $tag New tag. - * @access public - */ - function addTag(&$tag) { - } - - /** - * Accessor for tag name. - * @return string Name of tag. - * @access public - */ - function getTagName() { - return $this->_name; - } - - /** - * List of legal child elements. - * @return array List of element names. - * @access public - */ - function getChildElements() { - return array(); - } - - /** - * Accessor for an attribute. - * @param string $label Attribute name. - * @return string Attribute value. - * @access public - */ - function getAttribute($label) { - $label = strtolower($label); - if (! isset($this->_attributes[$label])) { - return false; - } - return (string)$this->_attributes[$label]; - } - - /** - * Sets an attribute. - * @param string $label Attribute name. - * @return string $value New attribute value. - * @access protected - */ - function _setAttribute($label, $value) { - $this->_attributes[strtolower($label)] = $value; - } - - /** - * Accessor for the whole content so far. - * @return string Content as big raw string. - * @access public - */ - function getContent() { - return $this->_content; - } - - /** - * Accessor for content reduced to visible text. Acts - * like a text mode browser, normalising space and - * reducing images to their alt text. - * @return string Content as plain text. - * @access public - */ - function getText() { - return SimpleHtmlSaxParser::normalise($this->_content); - } - - /** - * Test to see if id attribute matches. - * @param string $id ID to test against. - * @return boolean True on match. - * @access public - */ - function isId($id) { - return ($this->getAttribute('id') == $id); - } -} - -/** - * Base url. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleBaseTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleBaseTag($attributes) { - $this->SimpleTag('base', $attributes); - } - - /** - * Base tag is not a block tag. - * @return boolean false - * @access public - */ - function expectEndTag() { - return false; - } -} - -/** - * Page title. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTitleTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleTitleTag($attributes) { - $this->SimpleTag('title', $attributes); - } -} - -/** - * Link. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleAnchorTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleAnchorTag($attributes) { - $this->SimpleTag('a', $attributes); - } - - /** - * Accessor for URL as string. - * @return string Coerced as string. - * @access public - */ - function getHref() { - $url = $this->getAttribute('href'); - if (is_bool($url)) { - $url = ''; - } - return $url; - } -} - -/** - * Form element. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleWidget extends SimpleTag { - var $_value; - var $_label; - var $_is_set; - - /** - * Starts with a named tag with attributes only. - * @param string $name Tag name. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleWidget($name, $attributes) { - $this->SimpleTag($name, $attributes); - $this->_value = false; - $this->_label = false; - $this->_is_set = false; - } - - /** - * Accessor for name submitted as the key in - * GET/POST variables hash. - * @return string Parsed value. - * @access public - */ - function getName() { - return $this->getAttribute('name'); - } - - /** - * Accessor for default value parsed with the tag. - * @return string Parsed value. - * @access public - */ - function getDefault() { - return $this->getAttribute('value'); - } - - /** - * Accessor for currently set value or default if - * none. - * @return string Value set by form or default - * if none. - * @access public - */ - function getValue() { - if (! $this->_is_set) { - return $this->getDefault(); - } - return $this->_value; - } - - /** - * Sets the current form element value. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - $this->_value = $value; - $this->_is_set = true; - return true; - } - - /** - * Resets the form element value back to the - * default. - * @access public - */ - function resetValue() { - $this->_is_set = false; - } - - /** - * Allows setting of a label externally, say by a - * label tag. - * @param string $label Label to attach. - * @access public - */ - function setLabel($label) { - $this->_label = trim($label); - } - - /** - * Reads external or internal label. - * @param string $label Label to test. - * @return boolean True is match. - * @access public - */ - function isLabel($label) { - return $this->_label == trim($label); - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @access public - */ - function write(&$encoding) { - if ($this->getName()) { - $encoding->add($this->getName(), $this->getValue()); - } - } -} - -/** - * Text, password and hidden field. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTextTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleTextTag($attributes) { - $this->SimpleWidget('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->_setAttribute('value', ''); - } - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Sets the current form element value. Cannot - * change the value of a hidden field. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - if ($this->getAttribute('type') == 'hidden') { - return false; - } - return parent::setValue($value); - } -} - -/** - * Submit button as input tag. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSubmitTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleSubmitTag($attributes) { - $this->SimpleWidget('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->_setAttribute('value', 'Submit'); - } - } - - /** - * Tag contains no end element. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Disables the setting of the button value. - * @param string $value Ignored. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Value of browser visible text. - * @return string Visible label. - * @access public - */ - function getLabel() { - return $this->getValue(); - } - - /** - * Test for a label match when searching. - * @param string $label Label to test. - * @return boolean True on match. - * @access public - */ - function isLabel($label) { - return trim($label) == trim($this->getLabel()); - } -} - -/** - * Image button as input tag. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleImageSubmitTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleImageSubmitTag($attributes) { - $this->SimpleWidget('input', $attributes); - } - - /** - * Tag contains no end element. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Disables the setting of the button value. - * @param string $value Ignored. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Value of browser visible text. - * @return string Visible label. - * @access public - */ - function getLabel() { - if ($this->getAttribute('title')) { - return $this->getAttribute('title'); - } - return $this->getAttribute('alt'); - } - - /** - * Test for a label match when searching. - * @param string $label Label to test. - * @return boolean True on match. - * @access public - */ - function isLabel($label) { - return trim($label) == trim($this->getLabel()); - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @param integer $x X coordinate of click. - * @param integer $y Y coordinate of click. - * @access public - */ - function write(&$encoding, $x, $y) { - if ($this->getName()) { - $encoding->add($this->getName() . '.x', $x); - $encoding->add($this->getName() . '.y', $y); - } else { - $encoding->add('x', $x); - $encoding->add('y', $y); - } - } -} - -/** - * Submit button as button tag. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleButtonTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * Defaults are very browser dependent. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleButtonTag($attributes) { - $this->SimpleWidget('button', $attributes); - } - - /** - * Check to see if the tag can have both start and - * end tags with content in between. - * @return boolean True if content allowed. - * @access public - */ - function expectEndTag() { - return true; - } - - /** - * Disables the setting of the button value. - * @param string $value Ignored. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Value of browser visible text. - * @return string Visible label. - * @access public - */ - function getLabel() { - return $this->getContent(); - } - - /** - * Test for a label match when searching. - * @param string $label Label to test. - * @return boolean True on match. - * @access public - */ - function isLabel($label) { - return trim($label) == trim($this->getLabel()); - } -} - -/** - * Content tag for text area. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTextAreaTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleTextAreaTag($attributes) { - $this->SimpleWidget('textarea', $attributes); - } - - /** - * Accessor for starting value. - * @return string Parsed value. - * @access public - */ - function getDefault() { - return $this->_wrap(SimpleHtmlSaxParser::decodeHtml($this->getContent())); - } - - /** - * Applies word wrapping if needed. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return parent::setValue($this->_wrap($value)); - } - - /** - * Test to see if text should be wrapped. - * @return boolean True if wrapping on. - * @access private - */ - function _wrapIsEnabled() { - if ($this->getAttribute('cols')) { - $wrap = $this->getAttribute('wrap'); - if (($wrap == 'physical') || ($wrap == 'hard')) { - return true; - } - } - return false; - } - - /** - * Performs the formatting that is peculiar to - * this tag. There is strange behaviour in this - * one, including stripping a leading new line. - * Go figure. I am using Firefox as a guide. - * @param string $text Text to wrap. - * @return string Text wrapped with carriage - * returns and line feeds - * @access private - */ - function _wrap($text) { - $text = str_replace("\r\r\n", "\r\n", str_replace("\n", "\r\n", $text)); - $text = str_replace("\r\n\n", "\r\n", str_replace("\r", "\r\n", $text)); - if (strncmp($text, "\r\n", strlen("\r\n")) == 0) { - $text = substr($text, strlen("\r\n")); - } - if ($this->_wrapIsEnabled()) { - return wordwrap( - $text, - (integer)$this->getAttribute('cols'), - "\r\n"); - } - return $text; - } - - /** - * The content of textarea is not part of the page. - * @return boolean True. - * @access public - */ - function isPrivateContent() { - return true; - } -} - -/** - * File upload widget. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleUploadTag extends SimpleWidget { - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleUploadTag($attributes) { - $this->SimpleWidget('input', $attributes); - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @access public - */ - function write(&$encoding) { - if (! file_exists($this->getValue())) { - return; - } - $encoding->attach( - $this->getName(), - implode('', file($this->getValue())), - basename($this->getValue())); - } -} - -/** - * Drop down widget. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSelectionTag extends SimpleWidget { - var $_options; - var $_choice; - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleSelectionTag($attributes) { - $this->SimpleWidget('select', $attributes); - $this->_options = array(); - $this->_choice = false; - } - - /** - * Adds an option tag to a selection field. - * @param SimpleOptionTag $tag New option. - * @access public - */ - function addTag(&$tag) { - if ($tag->getTagName() == 'option') { - $this->_options[] = &$tag; - } - } - - /** - * Text within the selection element is ignored. - * @param string $content Ignored. - * @access public - */ - function addContent($content) { - } - - /** - * Scans options for defaults. If none, then - * the first option is selected. - * @return string Selected field. - * @access public - */ - function getDefault() { - for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if ($this->_options[$i]->getAttribute('selected') !== false) { - return $this->_options[$i]->getDefault(); - } - } - if ($count > 0) { - return $this->_options[0]->getDefault(); - } - return ''; - } - - /** - * Can only set allowed values. - * @param string $value New choice. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if ($this->_options[$i]->isValue($value)) { - $this->_choice = $i; - return true; - } - } - return false; - } - - /** - * Accessor for current selection value. - * @return string Value attribute or - * content of opton. - * @access public - */ - function getValue() { - if ($this->_choice === false) { - return $this->getDefault(); - } - return $this->_options[$this->_choice]->getValue(); - } -} - -/** - * Drop down widget. - * @package SimpleTest - * @subpackage WebTester - */ -class MultipleSelectionTag extends SimpleWidget { - var $_options; - var $_values; - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function MultipleSelectionTag($attributes) { - $this->SimpleWidget('select', $attributes); - $this->_options = array(); - $this->_values = false; - } - - /** - * Adds an option tag to a selection field. - * @param SimpleOptionTag $tag New option. - * @access public - */ - function addTag(&$tag) { - if ($tag->getTagName() == 'option') { - $this->_options[] = &$tag; - } - } - - /** - * Text within the selection element is ignored. - * @param string $content Ignored. - * @access public - */ - function addContent($content) { - } - - /** - * Scans options for defaults to populate the - * value array(). - * @return array Selected fields. - * @access public - */ - function getDefault() { - $default = array(); - for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if ($this->_options[$i]->getAttribute('selected') !== false) { - $default[] = $this->_options[$i]->getDefault(); - } - } - return $default; - } - - /** - * Can only set allowed values. Any illegal value - * will result in a failure, but all correct values - * will be set. - * @param array $desired New choices. - * @return boolean True if all allowed. - * @access public - */ - function setValue($desired) { - $achieved = array(); - foreach ($desired as $value) { - $success = false; - for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if ($this->_options[$i]->isValue($value)) { - $achieved[] = $this->_options[$i]->getValue(); - $success = true; - break; - } - } - if (! $success) { - return false; - } - } - $this->_values = $achieved; - return true; - } - - /** - * Accessor for current selection value. - * @return array List of currently set options. - * @access public - */ - function getValue() { - if ($this->_values === false) { - return $this->getDefault(); - } - return $this->_values; - } -} - -/** - * Option for selection field. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleOptionTag extends SimpleWidget { - - /** - * Stashes the attributes. - */ - function SimpleOptionTag($attributes) { - $this->SimpleWidget('option', $attributes); - } - - /** - * Does nothing. - * @param string $value Ignored. - * @return boolean Not allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Test to see if a value matches the option. - * @param string $compare Value to compare with. - * @return boolean True if possible match. - * @access public - */ - function isValue($compare) { - $compare = trim($compare); - if (trim($this->getValue()) == $compare) { - return true; - } - return trim($this->getContent()) == $compare; - } - - /** - * Accessor for starting value. Will be set to - * the option label if no value exists. - * @return string Parsed value. - * @access public - */ - function getDefault() { - if ($this->getAttribute('value') === false) { - return $this->getContent(); - } - return $this->getAttribute('value'); - } - - /** - * The content of options is not part of the page. - * @return boolean True. - * @access public - */ - function isPrivateContent() { - return true; - } -} - -/** - * Radio button. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleRadioButtonTag extends SimpleWidget { - - /** - * Stashes the attributes. - * @param array $attributes Hash of attributes. - */ - function SimpleRadioButtonTag($attributes) { - $this->SimpleWidget('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->_setAttribute('value', 'on'); - } - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * The only allowed value sn the one in the - * "value" attribute. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - if ($value === false) { - return parent::setValue($value); - } - if ($value != $this->getAttribute('value')) { - return false; - } - return parent::setValue($value); - } - - /** - * Accessor for starting value. - * @return string Parsed value. - * @access public - */ - function getDefault() { - if ($this->getAttribute('checked') !== false) { - return $this->getAttribute('value'); - } - return false; - } -} - -/** - * Checkbox widget. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleCheckboxTag extends SimpleWidget { - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleCheckboxTag($attributes) { - $this->SimpleWidget('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->_setAttribute('value', 'on'); - } - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * The only allowed value in the one in the - * "value" attribute. The default for this - * attribute is "on". If this widget is set to - * true, then the usual value will be taken. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - if ($value === false) { - return parent::setValue($value); - } - if ($value === true) { - return parent::setValue($this->getAttribute('value')); - } - if ($value != $this->getAttribute('value')) { - return false; - } - return parent::setValue($value); - } - - /** - * Accessor for starting value. The default - * value is "on". - * @return string Parsed value. - * @access public - */ - function getDefault() { - if ($this->getAttribute('checked') !== false) { - return $this->getAttribute('value'); - } - return false; - } -} - -/** - * A group of multiple widgets with some shared behaviour. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTagGroup { - var $_widgets = array(); - - /** - * Adds a tag to the group. - * @param SimpleWidget $widget - * @access public - */ - function addWidget(&$widget) { - $this->_widgets[] = &$widget; - } - - /** - * Accessor to widget set. - * @return array All widgets. - * @access protected - */ - function &_getWidgets() { - return $this->_widgets; - } - - /** - * Accessor for an attribute. - * @param string $label Attribute name. - * @return boolean Always false. - * @access public - */ - function getAttribute($label) { - return false; - } - - /** - * Fetches the name for the widget from the first - * member. - * @return string Name of widget. - * @access public - */ - function getName() { - if (count($this->_widgets) > 0) { - return $this->_widgets[0]->getName(); - } - } - - /** - * Scans the widgets for one with the appropriate - * ID field. - * @param string $id ID value to try. - * @return boolean True if matched. - * @access public - */ - function isId($id) { - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($this->_widgets[$i]->isId($id)) { - return true; - } - } - return false; - } - - /** - * Scans the widgets for one with the appropriate - * attached label. - * @param string $label Attached label to try. - * @return boolean True if matched. - * @access public - */ - function isLabel($label) { - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($this->_widgets[$i]->isLabel($label)) { - return true; - } - } - return false; - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @access public - */ - function write(&$encoding) { - $encoding->add($this->getName(), $this->getValue()); - } -} - -/** - * A group of tags with the same name within a form. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleCheckboxGroup extends SimpleTagGroup { - - /** - * Accessor for current selected widget or false - * if none. - * @return string/array Widget values or false if none. - * @access public - */ - function getValue() { - $values = array(); - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getValue() !== false) { - $values[] = $widgets[$i]->getValue(); - } - } - return $this->_coerceValues($values); - } - - /** - * Accessor for starting value that is active. - * @return string/array Widget values or false if none. - * @access public - */ - function getDefault() { - $values = array(); - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getDefault() !== false) { - $values[] = $widgets[$i]->getDefault(); - } - } - return $this->_coerceValues($values); - } - - /** - * Accessor for current set values. - * @param string/array/boolean $values Either a single string, a - * hash or false for nothing set. - * @return boolean True if all values can be set. - * @access public - */ - function setValue($values) { - $values = $this->_makeArray($values); - if (! $this->_valuesArePossible($values)) { - return false; - } - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - $possible = $widgets[$i]->getAttribute('value'); - if (in_array($widgets[$i]->getAttribute('value'), $values)) { - $widgets[$i]->setValue($possible); - } else { - $widgets[$i]->setValue(false); - } - } - return true; - } - - /** - * Tests to see if a possible value set is legal. - * @param string/array/boolean $values Either a single string, a - * hash or false for nothing set. - * @return boolean False if trying to set a - * missing value. - * @access private - */ - function _valuesArePossible($values) { - $matches = array(); - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - $possible = $widgets[$i]->getAttribute('value'); - if (in_array($possible, $values)) { - $matches[] = $possible; - } - } - return ($values == $matches); - } - - /** - * Converts the output to an appropriate format. This means - * that no values is false, a single value is just that - * value and only two or more are contained in an array. - * @param array $values List of values of widgets. - * @return string/array/boolean Expected format for a tag. - * @access private - */ - function _coerceValues($values) { - if (count($values) == 0) { - return false; - } elseif (count($values) == 1) { - return $values[0]; - } else { - return $values; - } - } - - /** - * Converts false or string into array. The opposite of - * the coercian method. - * @param string/array/boolean $value A single item is converted - * to a one item list. False - * gives an empty list. - * @return array List of values, possibly empty. - * @access private - */ - function _makeArray($value) { - if ($value === false) { - return array(); - } - if (is_string($value)) { - return array($value); - } - return $value; - } -} - -/** - * A group of tags with the same name within a form. - * Used for radio buttons. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleRadioGroup extends SimpleTagGroup { - - /** - * Each tag is tried in turn until one is - * successfully set. The others will be - * unchecked if successful. - * @param string $value New value. - * @return boolean True if any allowed. - * @access public - */ - function setValue($value) { - if (! $this->_valueIsPossible($value)) { - return false; - } - $index = false; - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if (! $widgets[$i]->setValue($value)) { - $widgets[$i]->setValue(false); - } - } - return true; - } - - /** - * Tests to see if a value is allowed. - * @param string Attempted value. - * @return boolean True if a valid value. - * @access private - */ - function _valueIsPossible($value) { - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getAttribute('value') == $value) { - return true; - } - } - return false; - } - - /** - * Accessor for current selected widget or false - * if none. - * @return string/boolean Value attribute or - * content of opton. - * @access public - */ - function getValue() { - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getValue() !== false) { - return $widgets[$i]->getValue(); - } - } - return false; - } - - /** - * Accessor for starting value that is active. - * @return string/boolean Value of first checked - * widget or false if none. - * @access public - */ - function getDefault() { - $widgets = &$this->_getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getDefault() !== false) { - return $widgets[$i]->getDefault(); - } - } - return false; - } -} - -/** - * Tag to keep track of labels. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleLabelTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleLabelTag($attributes) { - $this->SimpleTag('label', $attributes); - } - - /** - * Access for the ID to attach the label to. - * @return string For attribute. - * @access public - */ - function getFor() { - return $this->getAttribute('for'); - } -} - -/** - * Tag to aid parsing the form. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleFormTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleFormTag($attributes) { - $this->SimpleTag('form', $attributes); - } -} - -/** - * Tag to aid parsing the frames in a page. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleFrameTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function SimpleFrameTag($attributes) { - $this->SimpleTag('frame', $attributes); - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/acceptance_test.php b/tests/simpletest/test/acceptance_test.php deleted file mode 100644 index 9dbb5a35a..000000000 --- a/tests/simpletest/test/acceptance_test.php +++ /dev/null @@ -1,1633 +0,0 @@ -addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->get($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?
GET<\/dd>/', $browser->getContent()); - $this->assertEqual($browser->getTitle(), 'Simple test target file'); - $this->assertEqual($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - } - - function testPost() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->post($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); - } - - function testAbsoluteLinkFollowing() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Absolute')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeEncodedeLinkFollowing() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink("märcêl kiek'eboe")); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeLinkFollowing() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testUnifiedClickLinkClicking() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->click('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testIdLinkFollowing() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLinkById(1)); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testCookieReading() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'set_cookies.php'); - $this->assertEqual($browser->getCurrentCookieValue('session_cookie'), 'A'); - $this->assertEqual($browser->getCurrentCookieValue('short_cookie'), 'B'); - $this->assertEqual($browser->getCurrentCookieValue('day_cookie'), 'C'); - } - - function testSimpleSubmit() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } - - function testUnifiedClickCanSubmit() { - $browser = &new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->click('Go!')); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } -} - -class TestRadioFields extends SimpleTestAcceptanceTest { - function testSetFieldAsInteger() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', 2)); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } - - function testSetFieldAsString() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', '2')); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } -} - -class TestOfLiveFetching extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testFormWithArrayBasedInputs() { - $this->get($this->samples() . 'form_with_array_based_inputs.php'); - $this->setField('value[]', '3', '1'); - $this->setField('value[]', '4', '2'); - $this->clickSubmit('Go'); - $this->assertPattern('/QUERY_STRING : value%5B%5D=3&value%5B%5D=4&submit=Go/'); - } - - function testFormWithQuotedValues() { - $this->get($this->samples() . 'form_with_quoted_values.php'); - $this->assertField('a', 'default'); - $this->assertFieldById('text_field', 'default'); - $this->clickSubmit('Go'); - $this->assertPattern('/a=default&submit=Go/'); - } - - function testGet() { - $this->assertTrue($this->get($this->samples() . 'network_confirm.php')); - $this->assertEqual($this->getUrl(), $this->samples() . 'network_confirm.php'); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertTitle('Simple test target file'); - $this->assertTitle(new PatternExpectation('/target file/')); - $this->assertResponse(200); - $this->assertMime('text/html'); - $this->assertHeader('connection', 'close'); - $this->assertHeader('connection', new PatternExpectation('/los/')); - } - - function testSlowGet() { - $this->assertTrue($this->get($this->samples() . 'slow_page.php')); - } - - function testTimedOutGet() { - $this->setConnectionTimeout(1); - $this->ignoreErrors(); - $this->assertFalse($this->get($this->samples() . 'slow_page.php')); - } - - function testPost() { - $this->assertTrue($this->post($this->samples() . 'network_confirm.php')); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - } - - function testGetWithData() { - $this->get($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithRecursiveData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa]" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa][aaa]" => "aaaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => "aaa"))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => array("aaa" => "aaaa")))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - } - - function testRelativeGet() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->get('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativePost() { - $this->post($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->post('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } -} - -class TestOfLinkFollowing extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testLinkAssertions() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLink('Absolute', $this->samples() . 'network_confirm.php'); - $this->assertLink('Absolute', new PatternExpectation('/confirm/')); - $this->assertClickable('Absolute'); - } - - function testAbsoluteLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Absolute')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativeLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Relative')); - $this->assertText('target for the SimpleTest'); - } - - function testLinkIdFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLinkById(1); - $this->assertTrue($this->clickLinkById(1)); - $this->assertText('target for the SimpleTest'); - } - - function testAbsoluteUrlBehavesAbsolutely() { - $this->get($this->samples() . 'link_confirm.php'); - $this->get('http://www.lastcraft.com'); - $this->assertText('No guarantee of quality is given or even intended'); - } - - function testRelativeUrlRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/base_link.html'); - $this->click('Back to test pages'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLivePageLinkingWithMinimalLinks extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testClickToExplicitelyNamedSelfReturns() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->assertEqual($this->getUrl(), $this->samples() . 'front_controller_style/a_page.php'); - $this->assertTitle('Simple test page with links'); - $this->assertLink('Self'); - $this->clickLink('Self'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToMissingPageReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('No page'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=no_page]'); - } - - function testClickToBareActionReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Bare action'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=]'); - } - - function testClickToSingleQuestionMarkReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty query'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToEmptyStringReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty link'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToSingleDotGoesToCurrentDirectory() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Current directory'); - $this->assertTitle( - 'Simple test front controller', - '%s -> index.php needs to be set as a default web server home page'); - } - - function testClickBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|i'); - } -} - -class TestOfLiveFrontControllerEmulation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testJumpToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - } - - function testJumpToUnnamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - } - - function testJumpToUnnamedPageWithBareParameter() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - } - - function testJumpToUnnamedPageWithEmptyQuery() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpToUnnamedPageWithEmptyLink() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - } - - function testSubmitToSameDirectory() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - } - - function testSubmitToEmptyAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - } - - function testSubmitToNoAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - } - - function testSubmitBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickSubmit('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPageWithMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/?a=A'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index post'); - $this->assertText('action=[Index post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToSameDirectoryMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Same directory post'); - $this->assertText('action=[Same directory post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToEmptyActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Empty action post'); - $this->assertText('action=[Empty action post]'); - $this->assertText('[a=A]'); - } - - function testSubmitToNoActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('No action post'); - $this->assertText('action=[No action post]'); - $this->assertText('[a=A]'); - } -} - -class TestOfLiveHeaders extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testConfirmingHeaderExistence() { - $this->get('http://www.lastcraft.com/'); - $this->assertHeader('content-type'); - $this->assertHeader('content-type', 'text/html'); - $this->assertHeaderPattern('content-type', '/HTML/i'); - $this->assertNoHeader('WWW-Authenticate'); - } -} - -class TestOfLiveRedirects extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoRedirects() { - $this->setMaximumRedirects(0); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Redirection test'); - } - - function testRedirects() { - $this->setMaximumRedirects(1); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectLosesGetData() { - $this->get($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectKeepsExtraRequestDataOfItsOwn() { - $this->get($this->samples() . 'redirect.php'); - $this->assertText('r=[rrr]'); - } - - function testRedirectLosesPostData() { - $this->post($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertTitle('Simple test target file'); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectWithBaseUrlChange() { - $this->get($this->samples() . 'base_change_redirect.php'); - $this->assertTitle('Simple test target file in folder'); - $this->get($this->samples() . 'path/base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectWithDoubleBaseUrlChange() { - $this->get($this->samples() . 'double_base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLiveCookies extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function here() { - return new SimpleUrl($this->samples()); - } - - function thisHost() { - $here = $this->here(); - return $here->getHost(); - } - - function thisPath() { - $here = $this->here(); - return $here->getPath(); - } - - function testCookieSettingAndAssertions() { - $this->setCookie('a', 'Test cookie a'); - $this->setCookie('b', 'Test cookie b', $this->thisHost()); - $this->setCookie('c', 'Test cookie c', $this->thisHost(), $this->thisPath()); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertText('Test cookie a'); - $this->assertText('Test cookie b'); - $this->assertText('Test cookie c'); - $this->assertCookie('a'); - $this->assertCookie('b', 'Test cookie b'); - $this->assertTrue($this->getCookie('c') == 'Test cookie c'); - } - - function testNoCookieSetWhenCookiesDisabled() { - $this->setCookie('a', 'Test cookie a'); - $this->ignoreCookies(); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertNoText('Test cookie a'); - } - - function testCookieReading() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', 'A'); - $this->assertCookie('short_cookie', 'B'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoCookieReadingWhenCookiesDisabled() { - $this->ignoreCookies(); - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('short_cookie'); - $this->assertNoCookie('day_cookie'); - } - - function testCookiePatternAssertions() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', new PatternExpectation('/a/i')); - } - - function testTemporaryCookieExpiry() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(); - $this->assertNoCookie('session_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testTimedCookieExpiryWith100SecondMargin() { - $this->get($this->samples() . 'set_cookies.php'); - $this->ageCookies(3600); - $this->restart(time() + 100); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('hour_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoClockOverDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 200); - $this->assertNoCookie( - 'short_cookie', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testNoClockUnderDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 0); - $this->assertCookie( - 'short_cookie', - 'B', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testCookiePath() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('path_cookie', 'D'); - $this->get('./path/show_cookies.php'); - $this->assertPattern('/path_cookie/'); - $this->assertCookie('path_cookie', 'D'); - } -} - -class LiveTestOfForms extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSimpleSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('go=[Go!]'); - } - - function testDefaultFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldByName('a', ''); - $this->assertFieldByName('b', 'Default text'); - $this->assertFieldByName('c', ''); - $this->assertFieldByName('d', 'd1'); - $this->assertFieldByName('e', false); - $this->assertFieldByName('f', 'on'); - $this->assertFieldByName('g', 'g3'); - $this->assertFieldByName('h', 2); - $this->assertFieldByName('go', 'Go!'); - $this->assertClickable('Go!'); - $this->assertSubmit('Go!'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - $this->assertText('b=[Default text]'); - $this->assertText('c=[]'); - $this->assertText('d=[d1]'); - $this->assertNoText('e=['); - $this->assertText('f=[on]'); - $this->assertText('g=[g3]'); - } - - function testFormSubmissionByButtonLabel() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'aaa'); - $this->setFieldByName('b', 'bbb'); - $this->setFieldByName('c', 'ccc'); - $this->setFieldByName('d', 'D2'); - $this->setFieldByName('e', 'on'); - $this->setFieldByName('f', false); - $this->setFieldByName('g', 'g2'); - $this->setFieldByName('h', 1); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - } - - function testAdditionalFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'A'); - $this->assertTrue($this->clickSubmitByName('go')); - $this->assertText('a=[A]'); - } - - function testFormSubmissionByNameAndAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('go', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionBySubmitButtonLabeledSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('test')); - $this->assertText('test=[Submit]'); - } - - function testFormSubmissionWithIds() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldById(1, ''); - $this->assertFieldById(2, 'Default text'); - $this->assertFieldById(3, ''); - $this->assertFieldById(4, 'd1'); - $this->assertFieldById(5, false); - $this->assertFieldById(6, 'on'); - $this->assertFieldById(8, 'g3'); - $this->assertFieldById(11, 2); - $this->setFieldById(1, 'aaa'); - $this->setFieldById(2, 'bbb'); - $this->setFieldById(3, 'ccc'); - $this->setFieldById(4, 'D2'); - $this->setFieldById(5, 'on'); - $this->setFieldById(6, false); - $this->setFieldById(8, 'g2'); - $this->setFieldById(11, 'H1'); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testFormSubmissionWithLabels() { - $this->get($this->samples() . 'form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->clickSubmit('Go!'); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingCheckboxWithBooleanTrueSetsUnderlyingValue() { - $this->get($this->samples() . 'form.html'); - $this->setField('Checkbox E', true); - $this->assertField('Checkbox E', 'on'); - $this->clickSubmit('Go!'); - $this->assertText('e=[on]'); - } - - function testFormSubmissionWithMixedPostAndGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text A', 'Hello'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithMixedPostAndEncodedGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text B', 'Hello'); - $this->assertTrue($this->clickSubmit('Go encoded!')); - $this->assertText('b=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithoutAction() { - $this->get($this->samples() . 'form_without_action.php?test=test'); - $this->assertText('_GET : [test]'); - $this->assertTrue($this->clickSubmit('Submit Post With Empty Action')); - $this->assertText('_GET : [test]'); - $this->assertText('_POST : [test]'); - } - - function testImageSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertImage('Image go!'); - $this->assertTrue($this->clickImage('Image go!', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionByLabelWithAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImage('Image go!', 10, 12, array('add' => 'A'))); - $this->assertText('add=[A]'); - } - - function testImageSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageByName('go', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionById() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageById(97, 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testButtonSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Button go!', 10, 12)); - $this->assertPattern('/go=\[ButtonGo\]/s'); - } - - function testNamelessSubmitSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Go!'); - $this->assertNoText('Go!'); - $this->assertNoText('submit'); - } - - function testNamelessImageSendsXAndYValues() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->clickImage('Image go!', 4, 5); - $this->assertNoText('ImageGo'); - $this->assertText('x=[4]'); - $this->assertText('y=[5]'); - } - - function testNamelessButtonSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Button Go!'); - $this->assertNoText('ButtonGo'); - } - - function testSelfSubmit() { - $this->get($this->samples() . 'self_form.php'); - $this->assertNoText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTitle('Test of form self submission'); - } - - function testSelfSubmitWithParameters() { - $this->get($this->samples() . 'self_form.php'); - $this->setFieldByName('visible', 'Resent'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Resent]'); - } - - function testSettingOfBlankOption() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->setFieldByName('d', '')); - $this->clickSubmit('Go!'); - $this->assertText('d=[]'); - } - - function testAssertingFieldValueWithPattern() { - $this->get($this->samples() . 'form.html'); - $this->setField('c', 'A very long string'); - $this->assertField('c', new PatternExpectation('/very long/')); - } - - function testSendingMultipartFormDataEncodedForm() { - $this->get($this->samples() . 'form_data_encoded_form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingVariousBlanksInFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->assertField('Text A', ''); - $this->setField('Text A', '0'); - $this->assertField('Text A', '0'); - $this->assertField('Text area B', ''); - $this->setField('Text area B', '0'); - $this->assertField('Text area B', '0'); - $this->assertField('Text area C', " "); - $this->assertField('Selection D', ''); - $this->setField('Selection D', 'D2'); - $this->assertField('Selection D', 'D2'); - $this->setField('Selection D', 'D3'); - $this->assertField('Selection D', '0'); - $this->setField('Selection D', 'D4'); - $this->assertField('Selection D', '?'); - $this->assertField('Checkbox E', ''); - $this->assertField('Checkbox F', 'on'); - $this->assertField('Checkbox G', '0'); - $this->assertField('Checkbox H', '?'); - $this->assertFieldByName('i', 'on'); - $this->setFieldByName('i', ''); - $this->assertFieldByName('i', ''); - $this->setFieldByName('i', '0'); - $this->assertFieldByName('i', '0'); - $this->setFieldByName('i', '?'); - $this->assertFieldByName('i', '?'); - } - - function testSubmissionOfBlankFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', ''); - $this->setField('Text area B', ''); - $this->setFieldByName('i', ''); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertPattern('/c=\[ \]/'); - $this->assertText('d=[]'); - $this->assertText('e=[]'); - $this->assertText('i=[]'); - } - - function testSubmissionOfEmptyValues() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Selection D', 'D2'); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertText('d=[D2]'); - $this->assertText('f=[on]'); - $this->assertText('i=[on]'); - } - - function testSubmissionOfZeroes() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '0'); - $this->setField('Text area B', '0'); - $this->setField('Selection D', 'D3'); - $this->setFieldByName('i', '0'); - $this->click('Go!'); - $this->assertText('a=[0]'); - $this->assertText('b=[0]'); - $this->assertText('d=[0]'); - $this->assertText('g=[0]'); - $this->assertText('i=[0]'); - } - - function testSubmissionOfQuestionMarks() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '?'); - $this->setField('Text area B', '?'); - $this->setField('Selection D', 'D4'); - $this->setFieldByName('i', '?'); - $this->click('Go!'); - $this->assertText('a=[?]'); - $this->assertText('b=[?]'); - $this->assertText('d=[?]'); - $this->assertText('h=[?]'); - $this->assertText('i=[?]'); - } - - function testSubmissionOfHtmlEncodedValues() { - $this->get($this->samples() . 'form_with_tricky_defaults.html'); - $this->assertField('Text A', '&\'"<>'); - $this->assertField('Text B', '"'); - $this->assertField('Text area C', '&\'"<>'); - $this->assertField('Selection D', "'"); - $this->assertField('Checkbox E', '&\'"<>'); - $this->assertField('Checkbox F', false); - $this->assertFieldByname('i', "'"); - $this->click('Go!'); - $this->assertText('a=[&\'"<>, "]'); - $this->assertText('c=[&\'"<>]'); - $this->assertText("d=[']"); - $this->assertText('e=[&\'"<>]'); - $this->assertText("i=[']"); - } - - function testFormActionRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - } -} - -class TestOfLiveMultiValueWidgets extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testDefaultFormValueSubmission() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->assertFieldByName('a', array('a2', 'a3')); - $this->assertFieldByName('b', array('b2', 'b3')); - $this->assertFieldByName('c[]', array('c2', 'c3')); - $this->assertFieldByName('d', array('2', '3')); - $this->assertFieldByName('e', array('2', '3')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a2, a3]'); - $this->assertText('b=[b2, b3]'); - $this->assertText('c=[c2, c3]'); - $this->assertText('d=[2, 3]'); - $this->assertText('e=[2, 3]'); - } - - function testSubmittingMultipleValues() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a4', 'a1')); - $this->setFieldByName('b', array('b1', 'b4')); - $this->assertFieldByName('b', array('b1', 'b4')); - $this->setFieldByName('c[]', array('c1', 'c4')); - $this->assertField('c[]', array('c1', 'c4')); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->setFieldByName('e', array('e1', 'e4')); - $this->assertField('e', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('b=[b1, b4]'); - $this->assertText('c=[c1, c4]'); - $this->assertText('d=[1, 4]'); - $this->assertText('e=[1, 4]'); - } - - function testSettingByOptionValue() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('d=[1, 4]'); - } - - function testSubmittingMultipleValuesByLabel() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a4', 'a1')); - $this->setField('multiple selection C', array('c1', 'c4')); - $this->assertField('multiple selection C', array('c1', 'c4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('c=[c1, c4]'); - } - - function testSavantStyleHiddenFieldDefaults() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldByName('a', array('a0')); - $this->assertFieldByName('b', array('b0')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a0]'); - $this->assertText('b=[b0]'); - } - - function testSavantStyleHiddenDefaultsAreOverridden() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertTrue($this->setFieldByName('a', array('a1'))); - $this->assertTrue($this->setFieldByName('b', 'b1')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } - - function testSavantStyleFormSettingById() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldById(1, array('a0')); - $this->assertFieldById(4, array('b0')); - $this->assertTrue($this->setFieldById(2, 'a1')); - $this->assertTrue($this->setFieldById(5, 'b1')); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } -} - -class TestOfFileUploads extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSingleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertField('Content:', dirname(__FILE__) . '/support/upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - } - - function testMultipleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertTrue($this->setField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt')); - $this->assertField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - $this->assertText('Some more text content'); - } - - function testBinaryFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/latin1_sample')); - $this->click('Go!'); - $this->assertText( - implode('', file(dirname(__FILE__) . '/support/latin1_sample'))); - } -} - -class TestOfLiveHistoryNavigation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testRetry() { - $this->get($this->samples() . 'cookie_based_counter.php'); - $this->assertPattern('/count: 1/i'); - $this->retry(); - $this->assertPattern('/count: 2/i'); - $this->retry(); - $this->assertPattern('/count: 3/i'); - } - - function testOfBackButton() { - $this->get($this->samples() . '1.html'); - $this->clickLink('2'); - $this->assertTitle('2'); - $this->assertTrue($this->back()); - $this->assertTitle('1'); - $this->assertTrue($this->forward()); - $this->assertTitle('2'); - $this->assertFalse($this->forward()); - } - - function testGetRetryResubmitsData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=aaa')); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsExtraData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostRetryResubmitsData() { - $this->assertTrue($this->post( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsRepeatedData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=1&a=2')); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - } -} - -class TestOfLiveAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testChallengeFromProtectedPage() { - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertRealm(new PatternExpectation('/simpletest/i')); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->retry(); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedWithinRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected'); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedSettingRealm() { - $this->get($this->samples() . 'protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPage() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPageAfterTrailingSlashRedirect() { - $this->get('http://test:secret@www.lastcraft.com/test/protected'); - $this->assertResponse(200); - } - - function testRealmExtendsToWholeDirectory() { - $this->get($this->samples() . 'protected/1.html'); - $this->authenticate('test', 'secret'); - $this->clickLink('2'); - $this->assertResponse(200); - $this->clickLink('3'); - $this->assertResponse(200); - } - - function testRedirectKeepsAuthentication() { - $this->get($this->samples() . 'protected/local_redirect.php'); - $this->authenticate('test', 'secret'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectKeepsEncodedAuthentication() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/local_redirect.php'); - $this->assertResponse(200); - $this->assertTitle('Simple test target file'); - } - - function testSessionRestartLosesAuthentication() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->restart(); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - } -} - -class TestOfLoadingFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoFramesContentWhenFramesDisabled() { - $this->ignoreFrames(); - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This content is for no frames only'); - } - - function testPatternMatchCanReadTheOnlyFrame() { - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertText('A target for the SimpleTest test suite'); - $this->assertNoText('This content is for no frames only'); - } - - function testMessyFramesetResponsesByName() { - $this->assertTrue($this->get( - $this->samples() . 'messy_frameset.html')); - $this->assertTitle('Frameset for testing of SimpleTest'); - - $this->assertTrue($this->setFrameFocus('Front controller')); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocus('One')); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocus('Frame links')); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocus('Counter')); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocus('Redirected')); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocus('Protected')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocus('Protected redirect')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(1)); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocusByIndex(2)); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocusByIndex(3)); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocusByIndex(4)); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocusByIndex(5)); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocusByIndex(6)); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(7)); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertText('Count: 1'); - $this->retry(); - $this->assertText('Count: 2'); - $this->retry(); - $this->assertText('Count: 3'); - } - - function testReloadingSingleFrameWithCookieCounter() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->setFrameFocus('a'); - $this->retry(); - $this->assertText('Count: 3'); - $this->retry(); - $this->assertText('Count: 4'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - } - - function testReloadingFrameWhenUnfocusedReloadsWholeFrameset() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->clearFrameFocus('a'); - $this->retry(); - - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->setFrameFocus('a'); - $this->assertText('Count: 3'); - $this->setFrameFocus('b'); - $this->assertText('Count: 4'); - } - - function testClickingNormalLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('2'); - $this->assertLink('3'); - $this->assertText('Simple test front controller'); - } - - function testJumpToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithBareParameterReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithEmptyQueryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testSubmitToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - $this->assertText('Count: 1'); - } - - function testSubmitToSameDirectoryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - $this->assertText('Count: 1'); - } - - function testSubmitToEmptyActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitToNoActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testTopLinkExitsFrameset() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Exit the frameset'); - $this->assertTitle('Simple test target file'); - } - - function testLinkInOnePageCanLoadAnother() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertNoLink('3'); - $this->clickLink('Set one to 2'); - $this->assertLink('3'); - $this->assertNoLink('2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - } - - function testFrameWithRelativeLinksRespectsBaseTagForThatPage() { - $this->get($this->samples() . 'base_tag/frameset.html'); - $this->click('Back to test pages'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testRelativeLinkInFrameIsNotAffectedByFramesetBaseTag() { - $this->get($this->samples() . 'base_tag/frameset_with_base_tag.html'); - $this->assertText('This is page 1'); - $this->click('To page 2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This is page 2'); - } -} - -class TestOfFrameAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testUnauthenticatedFrameSendsChallenge() { - $this->get($this->samples() . 'protected/'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - } - - function testCanReadFrameFromAlreadyAuthenticatedRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testCanAuthenticateFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } - - function testCanAuthenticateRedirectedFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected redirect'); - $this->assertResponse(401); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } -} - -class TestOfNestedFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testCanNavigateToSpecificContent() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertTitle('Nested frameset for testing of SimpleTest'); - - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertPattern('/Simple test front controller/'); - $this->assertLink('2'); - $this->assertLink('Set one to 2'); - $this->assertPattern('/Count: 1/'); - $this->assertPattern('/r=rrr/'); - - $this->setFrameFocus('pair'); - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertNoPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - - $this->setFrameFocus('aaa'); - $this->assertPattern('/This is frame A/'); - $this->assertNoPattern('/This is frame B/'); - - $this->clearFrameFocus(); - $this->assertResponse(200); - $this->setFrameFocus('messy'); - $this->assertResponse(200); - $this->setFrameFocus('Front controller'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - } - - function testRetryingNestedPageOnlyRetriesThatSet() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->setFrameFocus('messy'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->setFrameFocus('Counter'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - - $this->clearFrameFocus(); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Front controller'); - $this->retry(); - - $this->clearFrameFocus(); - $this->assertPattern('/Count: 3/'); - } - - function testAuthenticatingNestedPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertPattern('/A target for the SimpleTest test suite/'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/adapter_test.php b/tests/simpletest/test/adapter_test.php deleted file mode 100644 index f4564ea87..000000000 --- a/tests/simpletest/test/adapter_test.php +++ /dev/null @@ -1,77 +0,0 @@ -assertTrue(true, "PEAR true"); - $this->assertFalse(false, "PEAR false"); - } - - function testName() { - $this->assertTrue($this->getName() == get_class($this)); - } - - function testPass() { - $this->pass("PEAR pass"); - } - - function testNulls() { - $value = null; - $this->assertNull($value, "PEAR null"); - $value = 0; - $this->assertNotNull($value, "PEAR not null"); - } - - function testType() { - $this->assertType("Hello", "string", "PEAR type"); - } - - function testEquals() { - $this->assertEquals(12, 12, "PEAR identity"); - $this->setLooselyTyped(true); - $this->assertEquals("12", 12, "PEAR equality"); - } - - function testSame() { - $same = &new SameTestClass(); - $this->assertSame($same, $same, "PEAR same"); - } - - function testRegExp() { - $this->assertRegExp('/hello/', "A big hello from me", "PEAR regex"); - } -} - -class TestOfPhpUnitAdapter extends TestCase { - function TestOfPhpUnitAdapter() { - $this->TestCase('TestOfPhpUnitAdapter'); - } - - function testBoolean() { - $this->assert(true, 'PHP Unit true'); - } - - function testName() { - $this->assert($this->name() == 'TestOfPhpUnitAdapter'); - } - - function testEquals() { - $this->assertEquals(12, 12, 'PHP Unit equality'); - } - - function testMultilineEquals() { - $this->assertEquals("a\nb\n", "a\nb\n", 'PHP Unit equality'); - } - - function testRegExp() { - $this->assertRegexp('/hello/', 'A big hello from me', 'PHPUnit regex'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/all_tests.php b/tests/simpletest/test/all_tests.php deleted file mode 100644 index 99ce9451e..000000000 --- a/tests/simpletest/test/all_tests.php +++ /dev/null @@ -1,13 +0,0 @@ -TestSuite('All tests for SimpleTest ' . SimpleTest::getVersion()); - $this->addFile(dirname(__FILE__) . '/unit_tests.php'); - $this->addFile(dirname(__FILE__) . '/shell_test.php'); - $this->addFile(dirname(__FILE__) . '/live_test.php'); - $this->addFile(dirname(__FILE__) . '/acceptance_test.php'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/authentication_test.php b/tests/simpletest/test/authentication_test.php deleted file mode 100644 index 8573eddc8..000000000 --- a/tests/simpletest/test/authentication_test.php +++ /dev/null @@ -1,145 +0,0 @@ -assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testInsideWithLongerUrl() { - $realm = &new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testBelowRootIsOutside() { - $realm = &new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/more/hello.html'))); - } - - function testOldNetscapeDefinitionIsOutside() { - $realm = &new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathmore/hello.html'))); - } - - function testInsideWithMissingTrailingSlash() { - $realm = &new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path'))); - } - - function testDifferentPageNameStillInside() { - $realm = &new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/goodbye.html'))); - } - - function testNewUrlInSameDirectoryDoesNotChangeRealm() { - $realm = &new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - } - - function testNewUrlMakesRealmTheCommonPath() { - $realm = &new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/here/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/there/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/here/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/there/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/paths/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathindex.html'))); - } -} - -class TestOfAuthenticator extends UnitTestCase { - - function testNoRealms() { - $request = &new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &new SimpleAuthenticator(); - $authenticator->addHeaders($request, new SimpleUrl('http://here.com/')); - } - - function &createSingleRealm() { - $authenticator = &new SimpleAuthenticator(); - $authenticator->addRealm( - new SimpleUrl('http://www.here.com/path/hello.html'), - 'Basic', - 'Sanctuary'); - $authenticator->setIdentityForRealm('www.here.com', 'Sanctuary', 'test', 'secret'); - return $authenticator; - } - - function testOutsideRealm() { - $request = &new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testWithinRealm() { - $request = &new MockSimpleHttpRequest(); - $request->expectOnce('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/path/more/hello.html')); - } - - function testRestartingClearsRealm() { - $request = &new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->restartSession(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testDifferentHostIsOutsideRealm() { - $request = &new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://here.com/path/hello.html')); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/autorun_test.php b/tests/simpletest/test/autorun_test.php deleted file mode 100644 index cec9f4a51..000000000 --- a/tests/simpletest/test/autorun_test.php +++ /dev/null @@ -1,13 +0,0 @@ -addFile(dirname(__FILE__) . '/support/test1.php'); - $this->assertEqual($tests->getSize(), 1); - } -} - -?> \ No newline at end of file diff --git a/tests/simpletest/test/bad_test_suite.php b/tests/simpletest/test/bad_test_suite.php deleted file mode 100644 index b426013be..000000000 --- a/tests/simpletest/test/bad_test_suite.php +++ /dev/null @@ -1,10 +0,0 @@ -TestSuite('Two bad test cases'); - $this->addFile(dirname(__FILE__) . '/support/empty_test_file.php'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/browser_test.php b/tests/simpletest/test/browser_test.php deleted file mode 100644 index 18faee8f2..000000000 --- a/tests/simpletest/test/browser_test.php +++ /dev/null @@ -1,779 +0,0 @@ -assertIdentical($history->getUrl(), false); - $this->assertIdentical($history->getParameters(), false); - } - - function testCannotMoveInEmptyHistory() { - $history = &new SimpleBrowserHistory(); - $this->assertFalse($history->back()); - $this->assertFalse($history->forward()); - } - - function testCurrentTargetAccessors() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.here.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testSecondEntryAccessors() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testGoingBackwards() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsOffBeginning() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingForwardsOffEnd() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsAndForwards() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertTrue($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testNewEntryReplacesNextOne() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testNewEntryDropsFutureEntries() { - $history = &new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $history->back(); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.fourth.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/')); - $this->assertFalse($history->forward()); - $history->back(); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertFalse($history->back()); - } -} - -class TestOfParsedPageAccess extends UnitTestCase { - - function &loadPage(&$page) { - $response = &new MockSimpleHttpResponse($this); - - $agent = &new MockSimpleUserAgent($this); - $agent->setReturnReference('fetchResponse', $response); - - $browser = &new MockParseSimpleBrowser($this); - $browser->setReturnReference('_createUserAgent', $agent); - $browser->setReturnReference('_parse', $page); - $browser->SimpleBrowser(); - - $browser->get('http://this.com/page.html'); - return $browser; - } - - function testAccessorsWhenNoPage() { - $agent = &new MockSimpleUserAgent($this); - - $browser = &new MockParseSimpleBrowser($this); - $browser->setReturnReference('_createUserAgent', $agent); - $browser->SimpleBrowser(); - - $this->assertEqual($browser->getContent(), ''); - } - - function testParse() { - $page = &new MockSimplePage(); - $page->setReturnValue('getRequest', "GET here.html\r\n\r\n"); - $page->setReturnValue('getRaw', 'Raw HTML'); - $page->setReturnValue('getTitle', 'Here'); - $page->setReturnValue('getFrameFocus', 'Frame'); - $page->setReturnValue('getMimeType', 'text/html'); - $page->setReturnValue('getResponseCode', 200); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Somewhere'); - $page->setReturnValue('getTransportError', 'Ouch!'); - - $browser = &$this->loadPage($page); - - $this->assertEqual($browser->getRequest(), "GET here.html\r\n\r\n"); - $this->assertEqual($browser->getContent(), 'Raw HTML'); - $this->assertEqual($browser->getTitle(), 'Here'); - $this->assertEqual($browser->getFrameFocus(), 'Frame'); - $this->assertIdentical($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - $this->assertEqual($browser->getAuthentication(), 'Basic'); - $this->assertEqual($browser->getRealm(), 'Somewhere'); - $this->assertEqual($browser->getTransportError(), 'Ouch!'); - } - - function testLinkAffirmationWhenPresent() { - $page = &new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com')); - $page->expectOnce('getUrlsByLabel', array('a link label')); - $browser = &$this->loadPage($page); - $this->assertIdentical($browser->getLink('a link label'), 'http://www.nowhere.com'); - } - - function testLinkAffirmationByIdWhenPresent() { - $page = &new MockSimplePage(); - $page->setReturnValue('getUrlById', 'a_page.com', array(99)); - $page->setReturnValue('getUrlById', false, array('*')); - $browser = &$this->loadPage($page); - $this->assertIdentical($browser->getLinkById(99), 'a_page.com'); - $this->assertFalse($browser->getLinkById(98)); - } - - function testSettingFieldIsPassedToPage() { - $page = &new MockSimplePage(); - $page->expectOnce('setField', array(new SimpleByLabelOrName('key'), 'Value', false)); - $page->setReturnValue('getField', 'Value'); - $browser = &$this->loadPage($page); - $this->assertEqual($browser->getField('key'), 'Value'); - $browser->setField('key', 'Value'); - } -} - -class TestOfBrowserNavigation extends UnitTestCase { - - function &createBrowser(&$agent, &$page) { - $browser = &new MockParseSimpleBrowser(); - $browser->setReturnReference('_createUserAgent', $agent); - $browser->setReturnReference('_parse', $page); - $browser->SimpleBrowser(); - return $browser; - } - - function testClickLinkRequestsPage() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectArgumentsAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $agent->expectArgumentsAt( - 1, - 'fetchResponse', - array(new SimpleUrl('http://this.com/new.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = &new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array(new SimpleUrl('http://this.com/new.html'))); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickLinkWithUnknownFrameStillRequestsWholePage() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectArgumentsAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $target = new SimpleUrl('http://this.com/new.html'); - $target->setTarget('missing'); - $agent->expectArgumentsAt( - 1, - 'fetchResponse', - array($target, new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $parsed_url = new SimpleUrl('http://this.com/new.html'); - $parsed_url->setTarget('missing'); - - $page = &new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array($parsed_url)); - $page->setReturnValue('hasFrames', false); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickingMissingLinkFails() { - $agent = &new MockSimpleUserAgent($this); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - - $page = &new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array()); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $this->assertTrue($browser->get('http://this.com/page.html')); - $this->assertFalse($browser->clickLink('New')); - } - - function testClickIndexedLink() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectArgumentsAt( - 1, - 'fetchResponse', - array(new SimpleUrl('1.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = &new MockSimplePage(); - $page->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('0.html'), new SimpleUrl('1.html'))); - $page->setReturnValue('getRaw', 'A page'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New', 1)); - } - - function testClinkLinkById() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectArgumentsAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/link.html'), - new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = &new MockSimplePage(); - $page->setReturnValue('getUrlById', new SimpleUrl('http://this.com/link.html')); - $page->expectOnce('getUrlById', array(2)); - $page->setReturnValue('getRaw', 'A page'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLinkById(2)); - } - - function testClickingMissingLinkIdFails() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - - $page = &new MockSimplePage(); - $page->setReturnValue('getUrlById', false); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertFalse($browser->clickLink(0)); - } - - function testSubmitFormByLabel() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectArgumentsAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleByLabel('Go'), false)); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Go'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit('Go')); - } - - function testDefaultSubmitFormByLabel() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectArgumentsAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html')); - $form->setReturnValue('getMethod', 'get'); - $form->setReturnValue('submitButton', new SimpleGetEncoding(array('a' => 'A'))); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Submit'))); - $page->setReturnValue('getRaw', 'stuff'); - $page->setReturnValue('getUrl', new SimpleUrl('http://this.com/page.html')); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit()); - } - - function testSubmitFormByName() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByName('me'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitByName('me')); - } - - function testSubmitFormById() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleById(99), false)); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitById(99)); - } - - function testSubmitFormByImageLabel() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByLabel('Go!'), 10, 11, false)); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByLabel('Go!'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImage('Go!', 10, 11)); - } - - function testSubmitFormByImageName() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByName('a'), 10, 11, false)); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByName('a'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageByName('a', 10, 11)); - } - - function testSubmitFormByImageId() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleById(99), 10, 11, false)); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageById(99, 10, 11)); - } - - function testSubmitFormByFormId() { - $agent = &new MockSimpleUserAgent(); - $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectArgumentsAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = &new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submit', new SimplePostEncoding(array('a' => 'A'))); - - $page = &new MockSimplePage(); - $page->setReturnReference('getFormById', $form); - $page->expectOnce('getFormById', array(33)); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = &$this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->submitFormById(33)); - } -} - -class TestOfBrowserFrames extends UnitTestCase { - - function &createBrowser(&$agent) { - $browser = &new MockUserAgentSimpleBrowser(); - $browser->setReturnReference('_createUserAgent', $agent); - $browser->SimpleBrowser(); - return $browser; - } - - function &createUserAgent($pages) { - $agent = &new MockSimpleUserAgent(); - foreach ($pages as $url => $raw) { - $url = new SimpleUrl($url); - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', $url); - $response->setReturnValue('getContent', $raw); - $agent->setReturnReference('fetchResponse', $response, array($url, '*')); - } - return $agent; - } - - function testSimplePageHasNoFrames() { - $browser = &$this->createBrowser($this->createUserAgent( - array('http://site.with.no.frames/' => 'A non-framed page'))); - $this->assertEqual( - $browser->get('http://site.with.no.frames/'), - 'A non-framed page'); - $this->assertIdentical($browser->getFrames(), 'http://site.with.no.frames/'); - } - - function testFramesetWithNoFrames() { - $browser = &$this->createBrowser($this->createUserAgent( - array('http://site.with.no.frames/' => ''))); - $this->assertEqual($browser->get('http://site.with.no.frames/'), ''); - $this->assertIdentical($browser->getFrames(), array()); - } - - function testFramesetWithSingleFrame() { - $frameset = ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'A frame'))); - $this->assertEqual($browser->get('http://site.with.one.frame/'), 'A frame'); - $this->assertIdentical( - $browser->getFrames(), - array('a' => 'http://site.with.one.frame/frame.html')); - } - - function testTitleTakenFromFramesetPage() { - $frameset = 'Frameset title' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'Page title'))); - $browser->get('http://site.with.one.frame/'); - $this->assertEqual($browser->getTitle(), 'Frameset title'); - } - - function testFramesetWithSingleUnnamedFrame() { - $frameset = ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'One frame'))); - $this->assertEqual( - $browser->get('http://site.with.one.frame/'), - 'One frame'); - $this->assertIdentical( - $browser->getFrames(), - array(1 => 'http://site.with.one.frame/frame.html')); - } - - function testFramesetWithMultipleFrames() { - $frameset = '' . - '' . - '' . - '' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 'b' => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html')); - } - - function testFrameFocusByName() { - $frameset = '' . - '' . - '' . - '' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus('b'); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - } - - function testFramesetWithSomeNamedFrames() { - $frameset = '' . - '' . - '' . - '' . - '' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frameD frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 2 => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html', - 4 => 'http://site.with.frames/frame_d.html')); - } - - function testFrameFocusWithMixedNamesAndIndexes() { - $frameset = '' . - '' . - '' . - '' . - '' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus(2); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - $browser->setFrameFocus(4); - $this->assertEqual($browser->getContent(), 'D frame'); - $browser->clearFrameFocus(); - $this->assertEqual($browser->getContent(), 'A frameB frameC frameD frame'); - } - - function testNestedFrameset() { - $inner = '' . - '' . - ''; - $outer = '' . - '' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frame/' => $outer, - 'http://site.with.nested.frame/inner.html' => $inner, - 'http://site.with.nested.frame/page.html' => 'The page'))); - $this->assertEqual( - $browser->get('http://site.with.nested.frame/'), - 'The page'); - $this->assertIdentical($browser->getFrames(), array( - 'inner' => array( - 'page' => 'http://site.with.nested.frame/page.html'))); - } - - function testCanNavigateToNestedFrame() { - $inner = '' . - '' . - '' . - ''; - $outer = '' . - '' . - '' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getFrameFocus(), array('inner')); - $this->assertTrue($browser->setFrameFocus('one')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'one')); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocus('two')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'two')); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocus('three')); - $this->assertEqual($browser->getFrameFocus(), array('three')); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } - - function testCanNavigateToNestedFrameByIndex() { - $inner = '' . - '' . - '' . - ''; - $outer = '' . - '' . - '' . - ''; - $browser = &$this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1)); - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1, 1)); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(1, 2)); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(2)); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/collector_test.php b/tests/simpletest/test/collector_test.php deleted file mode 100644 index 803974c73..000000000 --- a/tests/simpletest/test/collector_test.php +++ /dev/null @@ -1,51 +0,0 @@ -EqualExpectation(str_replace("\\", '/', $value), $message); - } - - function test($compare) { - return parent::test(str_replace("\\", '/', $compare)); - } -} - -class TestOfCollector extends UnitTestCase { - - function testCollectionIsAddedToGroup() { - $suite = &new MockTestSuite(); - $suite->expectMinimumCallCount('addTestFile', 2); - $suite->expectArguments( - 'addTestFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = &new SimpleCollector(); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} - -class TestOfPatternCollector extends UnitTestCase { - - function testAddingEverythingToGroup() { - $suite = &new MockTestSuite(); - $suite->expectCallCount('addTestFile', 2); - $suite->expectArguments( - 'addTestFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = &new SimplePatternCollector('/.*/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } - - function testOnlyMatchedFilesAreAddedToGroup() { - $suite = &new MockTestSuite(); - $suite->expectOnce('addTestFile', array(new PathEqualExpectation( - dirname(__FILE__) . '/support/collector/collectable.1'))); - $collector = &new SimplePatternCollector('/1$/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/command_line_test.php b/tests/simpletest/test/command_line_test.php deleted file mode 100644 index 5baabff33..000000000 --- a/tests/simpletest/test/command_line_test.php +++ /dev/null @@ -1,40 +0,0 @@ -assertIdentical($parser->getTest(), ''); - $this->assertIdentical($parser->getTestCase(), ''); - } - - function testNotXmlByDefault() { - $parser = new SimpleCommandLineParser(array()); - $this->assertFalse($parser->isXml()); - } - - function testCanDetectRequestForXml() { - $parser = new SimpleCommandLineParser(array('--xml')); - $this->assertTrue($parser->isXml()); - } - - function testCanReadAssignmentSyntax() { - $parser = new SimpleCommandLineParser(array('--test=myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadFollowOnSyntax() { - $parser = new SimpleCommandLineParser(array('--test', 'myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadShortForms() { - $parser = new SimpleCommandLineParser(array('-t', 'myTest', '-c', 'MyClass', '-x')); - $this->assertEqual($parser->getTest(), 'myTest'); - $this->assertEqual($parser->getTestCase(), 'MyClass'); - $this->assertTrue($parser->isXml()); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/compatibility_test.php b/tests/simpletest/test/compatibility_test.php deleted file mode 100644 index ea48f8396..000000000 --- a/tests/simpletest/test/compatibility_test.php +++ /dev/null @@ -1,97 +0,0 @@ -= 0) { - eval('interface ComparisonInterface { }'); - eval('class ComparisonClassWithInterface implements ComparisonInterface { }'); -} - -class TestOfCompatibility extends UnitTestCase { - - function testIsA() { - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonClass')); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonSubclass')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonSubclass(), - 'ComparisonClass')); - } - - function testIdentityOfNumericStrings() { - $numericString1 = "123"; - $numericString2 = "00123"; - $this->assertNotIdentical($numericString1, $numericString2); - } - - function testIdentityOfObjects() { - $object1 = new ComparisonClass(); - $object2 = new ComparisonClass(); - $this->assertIdentical($object1, $object2); - } - - function testReferences () { - $thing = "Hello"; - $thing_reference = &$thing; - $thing_copy = $thing; - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $thing, - $thing_copy)); - } - - function testObjectReferences () { - $object = &new ComparisonClass(); - $object_reference = &$object; - $object_copy = new ComparisonClass(); - $object_assignment = $object; - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_copy)); - if (version_compare(phpversion(), '5', '>=')) { - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } else { - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } - } - - function testInteraceComparison() { - if (version_compare(phpversion(), '5', '<')) { - return; - } - - $object = new ComparisonClassWithInterface(); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonInterface')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonClassWithInterface(), - 'ComparisonInterface')); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/cookies_test.php b/tests/simpletest/test/cookies_test.php deleted file mode 100644 index 0b49e43bf..000000000 --- a/tests/simpletest/test/cookies_test.php +++ /dev/null @@ -1,227 +0,0 @@ -assertFalse($cookie->getValue()); - $this->assertEqual($cookie->getPath(), "/"); - $this->assertIdentical($cookie->getHost(), false); - $this->assertFalse($cookie->getExpiry()); - $this->assertFalse($cookie->isSecure()); - } - - function testCookieAccessors() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT", - true); - $this->assertEqual($cookie->getName(), "name"); - $this->assertEqual($cookie->getValue(), "value"); - $this->assertEqual($cookie->getPath(), "/path/"); - $this->assertEqual($cookie->getExpiry(), "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isSecure()); - } - - function testFullHostname() { - $cookie = new SimpleCookie("name"); - $this->assertTrue($cookie->setHost("host.name.here")); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $this->assertTrue($cookie->setHost("host.com")); - $this->assertEqual($cookie->getHost(), "host.com"); - } - - function testHostTruncation() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $cookie->setHost("this.host.com"); - $this->assertEqual($cookie->getHost(), "host.com"); - $this->assertTrue($cookie->setHost("dashes.in-host.com")); - $this->assertEqual($cookie->getHost(), "in-host.com"); - } - - function testBadHosts() { - $cookie = new SimpleCookie("name"); - $this->assertFalse($cookie->setHost("gibberish")); - $this->assertFalse($cookie->setHost("host.here")); - $this->assertFalse($cookie->setHost("host..com")); - $this->assertFalse($cookie->setHost("...")); - $this->assertFalse($cookie->setHost("host.com.")); - } - - function testHostValidity() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertTrue($cookie->isValidHost("host.name.here")); - $this->assertTrue($cookie->isValidHost("that.host.name.here")); - $this->assertFalse($cookie->isValidHost("bad.host")); - $this->assertFalse($cookie->isValidHost("nearly.name.here")); - } - - function testPathValidity() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertFalse($cookie->isValidPath("/")); - $this->assertTrue($cookie->isValidPath("/path/")); - $this->assertTrue($cookie->isValidPath("/path/more")); - } - - function testSessionExpiring() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertTrue($cookie->isExpired(0)); - } - - function testTimestampExpiry() { - $cookie = new SimpleCookie("name", "value", "/path", 456); - $this->assertFalse($cookie->isExpired(0)); - $this->assertTrue($cookie->isExpired(457)); - $this->assertFalse($cookie->isExpired(455)); - } - - function testDateExpiry() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isExpired("Mon, 18 Nov 2002 15:50:30 GMT")); - $this->assertFalse($cookie->isExpired("Mon, 18 Nov 2002 15:50:28 GMT")); - } - - function testAging() { - $cookie = new SimpleCookie("name", "value", "/path", 200); - $cookie->agePrematurely(199); - $this->assertFalse($cookie->isExpired(0)); - $cookie->agePrematurely(2); - $this->assertTrue($cookie->isExpired(0)); - } -} - -class TestOfCookieJar extends UnitTestCase { - - function testAddCookie() { - $jar = new SimpleCookieJar(); - $jar->setCookie("a", "A"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - } - - function testHostFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', 'my-host.com'); - $jar->setCookie('b', 'B', 'another-host.com'); - $jar->setCookie('c', 'C'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com')), - array('a=A', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('www.another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('new-host.org')), - array('c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=A', 'b=B', 'c=C')); - } - - function testPathFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/elsewhere')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/here')), array('a=A')); - } - - function testPathFilterDeeply() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/more_path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/and_more')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/not_here/')), array()); - } - - function testMultipleCookieWithDifferentPathsButSameName() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '123', false, '/path/here/'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here')), - array('a=abc', 'a=123')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here/there')), - array('a=abc', 'a=123')); - } - - function testOverwrite() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', 'cde', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=cde')); - } - - function testClearSessionCookies() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/'); - $jar->restartSession(); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->restartSession("Wed, 25-Dec-02 04:24:21 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByAgeing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->agePrematurely(2); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testCookieClearing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=')); - } - - function testCookieClearByLoweringDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/', 'Wed, 25-Dec-02 04:24:21 GMT'); - $jar->setCookie('a', 'def', false, '/', 'Wed, 25-Dec-02 04:24:19 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=def')); - $jar->restartSession('Wed, 25-Dec-02 04:24:20 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/detached_test.php b/tests/simpletest/test/detached_test.php deleted file mode 100644 index 06db8280b..000000000 --- a/tests/simpletest/test/detached_test.php +++ /dev/null @@ -1,15 +0,0 @@ -addTestCase(new DetachedTestCase($command)); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/tests/simpletest/test/dumper_test.php b/tests/simpletest/test/dumper_test.php deleted file mode 100644 index 789047de9..000000000 --- a/tests/simpletest/test/dumper_test.php +++ /dev/null @@ -1,88 +0,0 @@ -assertEqual( - $dumper->clipString("Hello", 6), - "Hello", - "Hello, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello", 5), - "Hello", - "Hello, 5->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3), - "Hel...", - "Hello world, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 6, 3), - "Hello ...", - "Hello world, 6, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3, 6), - "...o w...", - "Hello world, 3, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 11), - "...orld", - "Hello world, 4, 11->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 12), - "...orld", - "Hello world, 4, 12->%s"); - } - - function testDescribeNull() { - $dumper = new SimpleDumper(); - $this->assertPattern('/null/i', $dumper->describeValue(null)); - } - - function testDescribeBoolean() { - $dumper = new SimpleDumper(); - $this->assertPattern('/boolean/i', $dumper->describeValue(true)); - $this->assertPattern('/true/i', $dumper->describeValue(true)); - $this->assertPattern('/false/i', $dumper->describeValue(false)); - } - - function testDescribeString() { - $dumper = new SimpleDumper(); - $this->assertPattern('/string/i', $dumper->describeValue('Hello')); - $this->assertPattern('/Hello/', $dumper->describeValue('Hello')); - } - - function testDescribeInteger() { - $dumper = new SimpleDumper(); - $this->assertPattern('/integer/i', $dumper->describeValue(35)); - $this->assertPattern('/35/', $dumper->describeValue(35)); - } - - function testDescribeFloat() { - $dumper = new SimpleDumper(); - $this->assertPattern('/float/i', $dumper->describeValue(0.99)); - $this->assertPattern('/0\.99/', $dumper->describeValue(0.99)); - } - - function testDescribeArray() { - $dumper = new SimpleDumper(); - $this->assertPattern('/array/i', $dumper->describeValue(array(1, 4))); - $this->assertPattern('/2/i', $dumper->describeValue(array(1, 4))); - } - - function testDescribeObject() { - $dumper = new SimpleDumper(); - $this->assertPattern( - '/object/i', - $dumper->describeValue(new DumperDummy())); - $this->assertPattern( - '/DumperDummy/i', - $dumper->describeValue(new DumperDummy())); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/eclipse_test.php b/tests/simpletest/test/eclipse_test.php deleted file mode 100644 index 0f1bf4bd4..000000000 --- a/tests/simpletest/test/eclipse_test.php +++ /dev/null @@ -1,32 +0,0 @@ -expectOnce('write',array($expected)); - $listener->setReturnValue('write',-1); - - $pathparts = pathinfo($fullpath); - $filename = $pathparts['basename']; - $test= &new TestSuite($filename); - $test->addTestFile($fullpath); - $test->run(new EclipseReporter(&$listener)); - $this->assertEqual($expected,$listener->output); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/encoding_test.php b/tests/simpletest/test/encoding_test.php deleted file mode 100644 index 95031fb0f..000000000 --- a/tests/simpletest/test/encoding_test.php +++ /dev/null @@ -1,213 +0,0 @@ -assertEqual($pair->asRequest(), 'a=A'); - } - - function testMimeEncodedAsHeadersAndContent() { - $pair = new SimpleEncodedPair('a', 'A'); - $this->assertEqual( - $pair->asMime(), - "Content-Disposition: form-data; name=\"a\"\r\n\r\nA"); - } - - function testAttachmentEncodedAsHeadersWithDispositionAndContent() { - $part = new SimpleAttachment('a', 'A', 'aaa.txt'); - $this->assertEqual( - $part->asMime(), - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n\r\nA"); - } -} - -class TestOfEncoding extends UnitTestCase { - var $_content_so_far; - - function write($content) { - $this->_content_so_far .= $content; - } - - function clear() { - $this->_content_so_far = ''; - } - - function assertWritten($encoding, $content, $message = '%s') { - $this->clear(); - $encoding->writeTo($this); - $this->assertIdentical($this->_content_so_far, $content, $message); - } - - function testGetEmpty() { - $encoding = &new SimpleGetEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertIdentical($encoding->asUrlRequest(), ''); - } - - function testPostEmpty() { - $encoding = &new SimplePostEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testPrefilled() { - $encoding = &new SimplePostEncoding(array('a' => 'aaa')); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testPrefilledWithTwoLevels() { - $query = array('a' => array('aa' => 'aaa')); - $encoding = &new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa]' => 'aaa')); - $this->assertIdentical($encoding->getValue('a[aa]'), 'aaa'); - $this->assertWritten($encoding, 'a%5Baa%5D=aaa'); - } - - function testPrefilledWithThreeLevels() { - $query = array('a' => array('aa' => array('aaa' => 'aaaa'))); - $encoding = &new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa][aaa]' => 'aaaa')); - $this->assertIdentical($encoding->getValue('a[aa][aaa]'), 'aaaa'); - $this->assertWritten($encoding, 'a%5Baa%5D%5Baaa%5D=aaaa'); - } - - function testPrefilledWithObject() { - $encoding = &new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa'))); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testMultiplePrefilled() { - $query = array('a' => array('a1', 'a2')); - $encoding = &new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[0]' => 'a1', 'a[1]' => 'a2')); - $this->assertIdentical($encoding->getValue('a[0]'), 'a1'); - $this->assertIdentical($encoding->getValue('a[1]'), 'a2'); - $this->assertWritten($encoding, 'a%5B0%5D=a1&a%5B1%5D=a2'); - } - - function testSingleParameter() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $this->assertEqual($encoding->getValue('a'), 'Hello'); - $this->assertWritten($encoding, 'a=Hello'); - } - - function testFalseParameter() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a', false); - $this->assertEqual($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testUrlEncoding() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a', 'Hello there!'); - $this->assertWritten($encoding, 'a=Hello+there%21'); - } - - function testUrlEncodingOfKey() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a!', 'Hello'); - $this->assertWritten($encoding, 'a%21=Hello'); - } - - function testMultipleParameter() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('b', 'Goodbye'); - $this->assertWritten($encoding, 'a=Hello&b=Goodbye'); - } - - function testEmptyParameters() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a', ''); - $encoding->add('b', ''); - $this->assertWritten($encoding, 'a=&b='); - } - - function testRepeatedParameter() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('a', 'Goodbye'); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testAddingLists() { - $encoding = &new SimplePostEncoding(); - $encoding->add('a', array('Hello', 'Goodbye')); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testMergeInHash() { - $encoding = &new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(array('a' => 'A2')); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testMergeInObject() { - $encoding = &new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(new SimpleEncoding(array('a' => 'A2'))); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testPrefilledMultipart() { - $encoding = &new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary'); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } - - function testAttachment() { - $encoding = &new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->attach('a', 'aaa', 'aaa.txt'); - $this->assertIdentical($encoding->getValue('a'), 'aaa.txt'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } -} - -class TestOfFormHeaders extends UnitTestCase { - - function testEmptyEncodingWritesZeroContentLength() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $encoding = &new SimplePostEncoding(); - $encoding->writeHeadersTo($socket); - } - - function testEmptyMultipartEncodingWritesEndBoundaryContentLength() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("Content-Length: 14\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Content-Type: multipart/form-data, boundary=boundary\r\n")); - $encoding = &new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->writeHeadersTo($socket); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/errors_test.php b/tests/simpletest/test/errors_test.php deleted file mode 100644 index 7db8769a2..000000000 --- a/tests/simpletest/test/errors_test.php +++ /dev/null @@ -1,300 +0,0 @@ -get('SimpleErrorQueue'); - $queue->clear(); - } - - function tearDown() { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - $queue->clear(); - } - - function testOrder() { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - $queue->add(1024, 'Ouch', 'here.php', 100); - $queue->add(512, 'Yuk', 'there.php', 101); - $this->assertEqual( - $queue->extract(), - array(1024, 'Ouch', 'here.php', 100)); - $this->assertEqual( - $queue->extract(), - array(512, 'Yuk', 'there.php', 101)); - $this->assertFalse($queue->extract()); - } - - function testAssertNoErrorsGivesTrueWhenNoErrors() { - $test = &new MockSimpleTestCase(); - $test->expectOnce('assert', array( - new IdenticalExpectation(new TrueExpectation()), - true, - 'Should be no errors')); - $test->setReturnValue('assert', true); - $queue = &new SimpleErrorQueue(); - $queue->setTestCase($test); - $this->assertTrue($queue->assertNoErrors('%s')); - } - - function testAssertNoErrorsIssuesFailWhenErrors() { - $test = &new MockSimpleTestCase(); - $test->expectOnce('assert', array( - new IdenticalExpectation(new TrueExpectation()), - false, - 'Should be no errors')); - $test->setReturnValue('assert', false); - $queue = &new SimpleErrorQueue(); - $queue->setTestCase($test); - $queue->add(1024, 'Ouch', 'here.php', 100); - $this->assertFalse($queue->assertNoErrors('%s')); - } - - function testAssertErrorFailsWhenNoError() { - $test = &new MockSimpleTestCase(); - $test->expectOnce('fail', array('Expected error not found')); - $test->setReturnValue('assert', false); - $queue = &new SimpleErrorQueue(); - $queue->setTestCase($test); - $this->assertFalse($queue->assertError(false, '%s')); - } - - function testAssertErrorFailsWhenErrorDoesntMatchTheExpectation() { - $test = &new MockSimpleTestCase(); - $test->expectOnce('assert', array( - new IdenticalExpectation(new FailedExpectation()), - 'B', - 'Expected PHP error [B] severity [E_USER_NOTICE] in [b.php] line [100]')); - $test->setReturnValue('assert', false); - $queue = &new SimpleErrorQueue(); - $queue->setTestCase($test); - $queue->add(1024, 'B', 'b.php', 100); - $this->assertFalse($queue->assertError(new FailedExpectation(), '%s')); - } - - function testExpectationMatchCancelsIncomingError() { - $test = &new MockSimpleTestCase(); - $test->expectOnce('assert', array( - new IdenticalExpectation(new AnythingExpectation()), - 'B', - 'a message')); - $test->setReturnValue('assert', true); - $test->expectNever('error'); - $queue = &new SimpleErrorQueue(); - $queue->setTestCase($test); - $queue->expectError(new AnythingExpectation(), 'a message'); - $queue->add(1024, 'B', 'b.php', 100); - } -} - -class TestOfErrorTrap extends UnitTestCase { - var $_old; - - function setUp() { - $this->_old = error_reporting(E_ALL); - set_error_handler('SimpleTestErrorHandler'); - } - - function tearDown() { - restore_error_handler(); - error_reporting($this->_old); - } - - function testQueueStartsEmpty() { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - $this->assertFalse($queue->extract()); - } - - function testTrappedErrorPlacedInQueue() { - trigger_error('Ouch!'); - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - list($severity, $message, $file, $line) = $queue->extract(); - $this->assertEqual($message, 'Ouch!'); - $this->assertEqual($file, __FILE__); - $this->assertFalse($queue->extract()); - } - - function testErrorsAreSwallowedByMatchingExpectation() { - $this->expectError('Ouch!'); - trigger_error('Ouch!'); - } - - function testErrorsAreSwallowedInOrder() { - $this->expectError('a'); - $this->expectError('b'); - trigger_error('a'); - trigger_error('b'); - } - - function testAnyErrorCanBeSwallowed() { - $this->expectError(); - trigger_error('Ouch!'); - } - - function testErrorCanBeSwallowedByPatternMatching() { - $this->expectError(new PatternExpectation('/ouch/i')); - trigger_error('Ouch!'); - } - - function testErrorWithPercentsPassesWithNoSprintfError() { - $this->expectError("%"); - trigger_error('%'); - } -} - -class TestOfErrors extends UnitTestCase { - var $_old; - - function setUp() { - $this->_old = error_reporting(E_ALL); - } - - function tearDown() { - error_reporting($this->_old); - } - - function testDefaultWhenAllReported() { - error_reporting(E_ALL); - trigger_error('Ouch!'); - $this->assertError('Ouch!'); - } - - function testNoticeWhenReported() { - error_reporting(E_ALL); - trigger_error('Ouch!', E_USER_NOTICE); - $this->assertError('Ouch!'); - } - - function testWarningWhenReported() { - error_reporting(E_ALL); - trigger_error('Ouch!', E_USER_WARNING); - $this->assertError('Ouch!'); - } - - function testErrorWhenReported() { - error_reporting(E_ALL); - trigger_error('Ouch!', E_USER_ERROR); - $this->assertError('Ouch!'); - } - - function testNoNoticeWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_NOTICE); - } - - function testNoWarningWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_WARNING); - } - - function testNoticeSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_NOTICE); - } - - function testWarningSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_WARNING); - } - - function testErrorWithPercentsReportedWithNoSprintfError() { - trigger_error('%'); - $this->assertError('%'); - } -} - -class TestOfPHP52RecoverableErrors extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '<'), - 'E_RECOVERABLE_ERROR not tested for PHP below 5.2'); - } - - function testError() { - eval(' - class RecoverableErrorTestingStub { - function ouch(RecoverableErrorTestingStub $obj) { - } - } - '); - - $stub = new RecoverableErrorTestingStub(); - $this->expectError(new PatternExpectation('/must be an instance of RecoverableErrorTestingStub/i')); - $stub->ouch(new stdClass()); - } -} - -class TestOfErrorsExcludingPHP52AndAbove extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '>='), - 'E_USER_ERROR not tested for PHP 5.2 and above'); - } - - function testNoErrorWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_ERROR); - } - - function testErrorSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_ERROR); - } -} - -SimpleTest::ignore('TestOfNotEnoughErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfNotEnoughErrors extends UnitTestCase { - function testExpectTwoErrorsThrowOne() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - $this->expectError('Error 2'); - } -} - -SimpleTest::ignore('TestOfLeftOverErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfLeftOverErrors extends UnitTestCase { - function testExpectOneErrorGetTwo() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - trigger_error('Error 2'); - } -} - -class TestRunnerForLeftOverAndNotEnoughErrors extends UnitTestCase { - function testRunLeftOverErrorsTestCase() { - $test = new TestOfLeftOverErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } - - function testRunNotEnoughErrors() { - $test = new TestOfNotEnoughErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } -} - -// TODO: Add stacked error handler test -?> \ No newline at end of file diff --git a/tests/simpletest/test/exceptions_test.php b/tests/simpletest/test/exceptions_test.php deleted file mode 100644 index 9cc35c590..000000000 --- a/tests/simpletest/test/exceptions_test.php +++ /dev/null @@ -1,153 +0,0 @@ -assertTrue($expectation->test(new MyTestException())); - $this->assertTrue($expectation->test(new HigherTestException())); - $this->assertFalse($expectation->test(new OtherTestException())); - } - - function testMatchesClassAndMessageWhenExceptionExpected() { - $expectation = new ExceptionExpectation(new MyTestException('Hello')); - $this->assertTrue($expectation->test(new MyTestException('Hello'))); - $this->assertFalse($expectation->test(new HigherTestException('Hello'))); - $this->assertFalse($expectation->test(new OtherTestException('Hello'))); - $this->assertFalse($expectation->test(new MyTestException('Goodbye'))); - $this->assertFalse($expectation->test(new MyTestException())); - } - - function testMessagelessExceptionMatchesOnlyOnClass() { - $expectation = new ExceptionExpectation(new MyTestException()); - $this->assertTrue($expectation->test(new MyTestException())); - $this->assertFalse($expectation->test(new HigherTestException())); - } -} - -class TestOfExceptionTrap extends UnitTestCase { - - function testNoExceptionsInQueueMeansNoTestMessages() { - $test = new MockSimpleTestCase(); - $test->expectNever('assert'); - $queue = new SimpleExceptionTrap(); - $this->assertFalse($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionGivesTrue() { - $expectation = new MockSimpleExpectation(); - $expectation->setReturnValue('test', true); - $test = new MockSimpleTestCase(); - $test->setReturnValue('assert', true); - $queue = new SimpleExceptionTrap(); - $queue->expectException($expectation, 'message'); - $this->assertTrue($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionTriggersAssertion() { - $test = new MockSimpleTestCase(); - $test->expectOnce('assert', array( - '*', - new ExceptionExpectation(new Exception()), - 'message')); - $queue = new SimpleExceptionTrap(); - $queue->expectException(new ExceptionExpectation(new Exception()), 'message'); - $queue->isExpected($test, new Exception()); - } -} - -class TestOfCatchingExceptions extends UnitTestCase { - - function testCanCatchAnyExpectedException() { - $this->expectException(); - throw new Exception(); - } - - function testCanMatchExceptionByClass() { - $this->expectException('MyTestException'); - throw new HigherTestException(); - } - - function testCanMatchExceptionExactly() { - $this->expectException(new Exception('Ouch')); - throw new Exception('Ouch'); - } - - function testLastListedExceptionIsTheOneThatCounts() { - $this->expectException('OtherTestException'); - $this->expectException('MyTestException'); - throw new HigherTestException(); - } -} - -class TestOfCallingTearDownAfterExceptions extends UnitTestCase { - private $debri = 0; - - function tearDown() { - $this->debri--; - } - - function testLeaveSomeDebri() { - $this->debri++; - $this->expectException(); - throw new Exception(__FUNCTION__); - } - - function testDebriWasRemovedOnce() { - $this->assertEqual($this->debri, 0); - } -} - -class TestOfExceptionThrownInSetUpDoesNotRunTestBody extends UnitTestCase { - - function setUp() { - $this->expectException(); - throw new Exception(); - } - - function testShouldNotBeRun() { - $this->fail('This test body should not be run'); - } - - function testShouldNotBeRunEither() { - $this->fail('This test body should not be run either'); - } -} - -class TestOfExpectExceptionWithSetUp extends UnitTestCase { - - function setUp() { - $this->expectException(); - } - - function testThisExceptionShouldBeCaught() { - throw new Exception(); - } - - function testJustThrowingMyTestException() { - throw new MyTestException(); - } -} - -class TestOfThrowingExceptionsInTearDown extends UnitTestCase { - - function tearDown() { - throw new Exception(); - } - - function testDoesntFatal() { - $this->expectException(); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/expectation_test.php b/tests/simpletest/test/expectation_test.php deleted file mode 100644 index 8f4fc3878..000000000 --- a/tests/simpletest/test/expectation_test.php +++ /dev/null @@ -1,245 +0,0 @@ -assertTrue($is_true->test(true)); - $this->assertFalse($is_true->test(false)); - } - - function testStringMatch() { - $hello = &new EqualExpectation("Hello"); - $this->assertTrue($hello->test("Hello")); - $this->assertFalse($hello->test("Goodbye")); - } - - function testInteger() { - $fifteen = &new EqualExpectation(15); - $this->assertTrue($fifteen->test(15)); - $this->assertFalse($fifteen->test(14)); - } - - function testFloat() { - $pi = &new EqualExpectation(3.14); - $this->assertTrue($pi->test(3.14)); - $this->assertFalse($pi->test(3.15)); - } - - function testArray() { - $colours = &new EqualExpectation(array("r", "g", "b")); - $this->assertTrue($colours->test(array("r", "g", "b"))); - $this->assertFalse($colours->test(array("g", "b", "r"))); - } - - function testHash() { - $is_blue = &new EqualExpectation(array("r" => 0, "g" => 0, "b" => 255)); - $this->assertTrue($is_blue->test(array("r" => 0, "g" => 0, "b" => 255))); - $this->assertFalse($is_blue->test(array("r" => 0, "g" => 255, "b" => 0))); - } - - function testHashWithOutOfOrderKeysShouldStillMatch() { - $any_order = &new EqualExpectation(array('a' => 1, 'b' => 2)); - $this->assertTrue($any_order->test(array('b' => 2, 'a' => 1))); - } -} - -class TestOfWithin extends UnitTestCase { - - function testWithinFloatingPointMargin() { - $within = new WithinMarginExpectation(1.0, 0.2); - $this->assertFalse($within->test(0.7)); - $this->assertTrue($within->test(0.8)); - $this->assertTrue($within->test(0.9)); - $this->assertTrue($within->test(1.1)); - $this->assertTrue($within->test(1.2)); - $this->assertFalse($within->test(1.3)); - } - - function testOutsideFloatingPointMargin() { - $within = new OutsideMarginExpectation(1.0, 0.2); - $this->assertTrue($within->test(0.7)); - $this->assertFalse($within->test(0.8)); - $this->assertFalse($within->test(1.2)); - $this->assertTrue($within->test(1.3)); - } -} - -class TestOfInequality extends UnitTestCase { - - function testStringMismatch() { - $not_hello = &new NotEqualExpectation("Hello"); - $this->assertTrue($not_hello->test("Goodbye")); - $this->assertFalse($not_hello->test("Hello")); - } -} - -class RecursiveNasty { - var $_me; - - function RecursiveNasty() { - $this->_me = $this; - } -} - -class TestOfIdentity extends UnitTestCase { - - function testType() { - $string = &new IdenticalExpectation("37"); - $this->assertTrue($string->test("37")); - $this->assertFalse($string->test(37)); - $this->assertFalse($string->test("38")); - } - - function _testNastyPhp5Bug() { - $this->assertFalse(new RecursiveNasty() != new RecursiveNasty()); - } - - function _testReallyHorribleRecursiveStructure() { - $hopeful = &new IdenticalExpectation(new RecursiveNasty()); - $this->assertTrue($hopeful->test(new RecursiveNasty())); - } -} - -class DummyReferencedObject{} - -class TestOfReference extends UnitTestCase { - - function testReference() { - $foo = "foo"; - $ref =& $foo; - $not_ref = $foo; - $bar = "bar"; - - $expect = &new ReferenceExpectation($foo); - $this->assertTrue($expect->test($ref)); - $this->assertFalse($expect->test($not_ref)); - $this->assertFalse($expect->test($bar)); - } - - function testObjectsReferencesDualityForPhp5AndPhp4() { - $dummy = new DummyReferencedObject(); - $ref =& $dummy; - $not_ref = $dummy; - - $hopeful = &new ReferenceExpectation($dummy); - $this->assertTrue($hopeful->test($ref)); - - if (version_compare(phpversion(), '5') >= 0) { - $this->assertTrue($hopeful->test($not_ref)); - } else { - $this->assertFalse($hopeful->test($not_ref)); - } - } - - function testReallyHorribleRecursiveStructure() { - $nasty = new RecursiveNasty(); - $ref =& $nasty; - $hopeful = &new ReferenceExpectation($nasty); - $this->assertTrue($hopeful->test($ref)); - } -} - -class TestOfNonIdentity extends UnitTestCase { - - function testType() { - $string = &new NotIdenticalExpectation("37"); - $this->assertTrue($string->test("38")); - $this->assertTrue($string->test(37)); - $this->assertFalse($string->test("37")); - } -} - -class TestOfPatterns extends UnitTestCase { - - function testWanted() { - $pattern = &new PatternExpectation('/hello/i'); - $this->assertTrue($pattern->test("Hello world")); - $this->assertFalse($pattern->test("Goodbye world")); - } - - function testUnwanted() { - $pattern = &new NoPatternExpectation('/hello/i'); - $this->assertFalse($pattern->test("Hello world")); - $this->assertTrue($pattern->test("Goodbye world")); - } -} - -class ExpectedMethodTarget { - function hasThisMethod() {} -} - -class TestOfMethodExistence extends UnitTestCase { - - function testHasMethod() { - $instance = &new ExpectedMethodTarget(); - $expectation = &new MethodExistsExpectation('hasThisMethod'); - $this->assertTrue($expectation->test($instance)); - $expectation = &new MethodExistsExpectation('doesNotHaveThisMethod'); - $this->assertFalse($expectation->test($instance)); - } -} - -class TestOfIsA extends UnitTestCase { - - function testString() { - $expectation = &new IsAExpectation('string'); - $this->assertTrue($expectation->test('Hello')); - $this->assertFalse($expectation->test(5)); - } - - function testBoolean() { - $expectation = &new IsAExpectation('boolean'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testBool() { - $expectation = &new IsAExpectation('bool'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testDouble() { - $expectation = &new IsAExpectation('double'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testFloat() { - $expectation = &new IsAExpectation('float'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testReal() { - $expectation = &new IsAExpectation('real'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testInteger() { - $expectation = &new IsAExpectation('integer'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } - - function testInt() { - $expectation = &new IsAExpectation('int'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } -} - -class TestOfNotA extends UnitTestCase { - - function testString() { - $expectation = &new NotAExpectation('string'); - $this->assertFalse($expectation->test('Hello')); - $this->assertTrue($expectation->test(5)); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/form_test.php b/tests/simpletest/test/form_test.php deleted file mode 100644 index bdc6f67d2..000000000 --- a/tests/simpletest/test/form_test.php +++ /dev/null @@ -1,323 +0,0 @@ -setReturnValue('getUrl', new SimpleUrl($url)); - $page->setReturnValue('expandUrl', new SimpleUrl($url)); - return $page; - } - - function testFormAttributes() { - $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33')); - $form = &new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual($form->getMethod(), 'get'); - $this->assertIdentical($form->getId(), '33'); - $this->assertNull($form->getValue(new SimpleByName('a'))); - } - - function testAction() { - $page = &new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = &new SimpleForm($tag, $page); - $this->assertEqual($form->getAction(), new SimpleUrl('http://host/here.php')); - } - - function testEmptyAction() { - $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => '', 'id' => '33')); - $form = &new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testMissingAction() { - $tag = &new SimpleFormTag(array('method' => 'GET')); - $form = &new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testRootAction() { - $page = &new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('/'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/')); - $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => '/')); - $form = &new SimpleForm($tag, $page); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/')); - } - - function testDefaultFrameTargetOnForm() { - $page = &new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = &new SimpleForm($tag, $page); - $form->setDefaultTarget('frame'); - $expected = new SimpleUrl('http://host/here.php'); - $expected->setTarget('frame'); - $this->assertEqual($form->getAction(), $expected); - } - - function testTextWidget() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'Not me')); - $this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me'); - $this->assertNull($form->getValue(new SimpleByName('not_present'))); - } - - function testTextWidgetById() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50))); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself'); - $this->assertTrue($form->setField(new SimpleById(50), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me'); - } - - function testTextWidgetByLabel() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $widget = &new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a')); - $form->addWidget($widget); - $widget->setLabel('thing'); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a'); - $this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b'); - } - - function testSubmitEmpty() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $this->assertIdentical($form->submit(), new SimpleGetEncoding()); - } - - function testSubmitButton() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9'))); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!'); - $this->assertEqual($form->getValue(new SimpleById(9)), 'Go!'); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go!'))); - } - - function testSubmitWithAdditionalParameters() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')), - new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A'))); - } - - function testSubmitButtonWithLabelOfSubmit() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('test')), - new SimpleGetEncoding(array('test' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => 'Submit'))); - } - - function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => ' Submit '))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => ' Submit '))); - } - - function testImageSubmitButton() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!', - 'id' => '9'))); - $this->assertTrue($form->hasImage(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleByName('go'))); - $this->assertEqual( - $form->submitImage(new SimpleByName('go'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleById(9))); - $this->assertEqual( - $form->submitImage(new SimpleById(9), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - } - - function testImageSubmitButtonWithAdditionalData() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); - } - - function testButtonTag() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $widget = &new SimpleButtonTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9')); - $widget->addContent('Go!'); - $form->addWidget($widget); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go'))); - } - - function testMultipleFieldsWithSameNameSubmitted() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $input = &new SimpleTextTag(array('name' => 'elements[]', 'value' => '1')); - $form->addWidget($input); - $input = &new SimpleTextTag(array('name' => 'elements[]', 'value' => '2')); - $form->addWidget($input); - $form->setField(new SimpleByLabelOrName('elements[]'), '3', 1); - $form->setField(new SimpleByLabelOrName('elements[]'), '4', 2); - $submit = $form->submit(); - $this->assertEqual(count($submit->_request), 2); - $this->assertIdentical($submit->_request[0], new SimpleEncodedPair('elements[]', '3')); - $this->assertIdentical($submit->_request[1], new SimpleEncodedPair('elements[]', '4')); - } - - function testSingleSelectFieldSubmitted() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $select = &new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimpleGetEncoding(array('a' => 'aaa'))); - } - - function testSingleSelectFieldSubmittedWithPost() { - $form = &new SimpleForm(new SimpleFormTag(array('method' => 'post')), $this->page('htp://host')); - $select = &new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimplePostEncoding(array('a' => 'aaa'))); - } - - function testUnchecked() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'type' => 'checkbox'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'on')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - } - - function testChecked() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), false)); - $this->assertEqual($form->getValue(new SimpleByName('me')), false); - } - - function testSingleUncheckedRadioButton() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - } - - function testSingleCheckedRadioButton() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - } - - function testUncheckedRadioButtons() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'c')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - } - - function testCheckedRadioButtons() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - } - - function testMultipleFieldsWithSameKey() { - $form = &new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'me'))); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'you'))); - $this->assertIdentical($form->getValue(new SimpleByName('a')), false); - $this->assertTrue($form->setField(new SimpleByName('a'), 'me')); - $this->assertIdentical($form->getValue(new SimpleByName('a')), 'me'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/frames_test.php b/tests/simpletest/test/frames_test.php deleted file mode 100644 index 160eebc1b..000000000 --- a/tests/simpletest/test/frames_test.php +++ /dev/null @@ -1,549 +0,0 @@ -setReturnValue('getTitle', 'This page'); - $frameset = &new SimpleFrameset($page); - $this->assertEqual($frameset->getTitle(), 'This page'); - } - - function TestHeadersReadFromFramesetByDefault() { - $page = &new MockSimplePage(); - $page->setReturnValue('getHeaders', 'Header: content'); - $page->setReturnValue('getMimeType', 'text/xml'); - $page->setReturnValue('getResponseCode', 401); - $page->setReturnValue('getTransportError', 'Could not parse headers'); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Safe place'); - - $frameset = &new SimpleFrameset($page); - - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testEmptyFramesetHasNoContent() { - $page = &new MockSimplePage(); - $page->setReturnValue('getRaw', 'This content'); - $frameset = &new SimpleFrameset($page); - $this->assertEqual($frameset->getRaw(), ''); - } - - function testRawContentIsFromOnlyFrame() { - $page = &new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = &new MockSimplePage(); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - } - - function testRawContentIsFromAllFrames() { - $page = &new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testTextContentIsFromOnlyFrame() { - $page = &new MockSimplePage(); - $page->expectNever('getText'); - - $frame = &new MockSimplePage(); - $frame->setReturnValue('getText', 'Stuff'); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getText(), 'Stuff'); - } - - function testTextContentIsFromAllFrames() { - $page = &new MockSimplePage(); - $page->expectNever('getText'); - - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getText', 'Stuff1'); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getText', 'Stuff2'); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getText(), 'Stuff1 Stuff2'); - } - - function testFieldFoundIsFirstInFramelist() { - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getField', null); - $frame1->expectOnce('getField', array(new SimpleByName('a'))); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getField', 'A'); - $frame2->expectOnce('getField', array(new SimpleByName('a'))); - - $frame3 = &new MockSimplePage(); - $frame3->expectNever('getField'); - - $page = &new MockSimplePage(); - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $frameset->addFrame($frame3); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'A'); - } - - function testFrameReplacementByIndex() { - $page = &new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->setFrame(array(1), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } - - function testFrameReplacementByName() { - $page = &new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1, 'a'); - $frameset->setFrame(array('a'), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } -} - -class TestOfFrameNavigation extends UnitTestCase { - - function testStartsWithoutFrameFocus() { - $page = &new MockSimplePage(); - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertFalse($frameset->getFrameFocus()); - } - - function testCanFocusOnSingleFrame() { - $page = &new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = &new MockSimplePage(); - $frame->setReturnValue('getFrameFocus', array()); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame); - - $this->assertFalse($frameset->setFrameFocusByIndex(0)); - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - $this->assertFalse($frameset->setFrameFocusByIndex(2)); - $this->assertIdentical($frameset->getFrameFocus(), array(1)); - } - - function testContentComesFromFrameInFocus() { - $page = &new MockSimplePage(); - - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getFrameFocus(), array(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocusByIndex(3)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testCanFocusByName() { - $page = &new MockSimplePage(); - - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - - $this->assertTrue($frameset->setFrameFocus('A')); - $this->assertEqual($frameset->getFrameFocus(), array('A')); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array('B')); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocus('z')); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } -} - -class TestOfFramesetPageInterface extends UnitTestCase { - var $_page_interface; - var $_frameset_interface; - - function TestOfFramesetPageInterface() { - $this->UnitTestCase(); - $this->_page_interface = $this->_getPageMethods(); - $this->_frameset_interface = $this->_getFramesetMethods(); - } - - function assertListInAnyOrder($list, $expected) { - sort($list); - sort($expected); - $this->assertEqual($list, $expected); - } - - function _getPageMethods() { - $methods = array(); - foreach (get_class_methods('SimplePage') as $method) { - if (strtolower($method) == strtolower('SimplePage')) { - continue; - } - if (strtolower($method) == strtolower('getFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (strncmp($method, 'accept', 6) == 0) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - function _getFramesetMethods() { - $methods = array(); - foreach (get_class_methods('SimpleFrameset') as $method) { - if (strtolower($method) == strtolower('SimpleFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (strncmp($method, 'add', 3) == 0) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - function testFramsetHasPageInterface() { - $difference = array(); - foreach ($this->_page_interface as $method) { - if (! in_array($method, $this->_frameset_interface)) { - $this->fail("No [$method] in Frameset class"); - return; - } - } - $this->pass('Frameset covers Page interface'); - } - - function testHeadersReadFromFrameIfInFocus() { - $frame = &new MockSimplePage(); - $frame->setReturnValue('getUrl', new SimpleUrl('http://localhost/stuff')); - - $frame->setReturnValue('getRequest', 'POST stuff'); - $frame->setReturnValue('getMethod', 'POST'); - $frame->setReturnValue('getRequestData', array('a' => 'A')); - $frame->setReturnValue('getHeaders', 'Header: content'); - $frame->setReturnValue('getMimeType', 'text/xml'); - $frame->setReturnValue('getResponseCode', 401); - $frame->setReturnValue('getTransportError', 'Could not parse headers'); - $frame->setReturnValue('getAuthentication', 'Basic'); - $frame->setReturnValue('getRealm', 'Safe place'); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame); - $frameset->setFrameFocusByIndex(1); - - $url = new SimpleUrl('http://localhost/stuff'); - $url->setTarget(1); - $this->assertIdentical($frameset->getUrl(), $url); - - $this->assertIdentical($frameset->getRequest(), 'POST stuff'); - $this->assertIdentical($frameset->getMethod(), 'POST'); - $this->assertIdentical($frameset->getRequestData(), array('a' => 'A')); - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testUrlsComeFromBothFrames() { - $page = &new MockSimplePage(); - $page->expectNever('getUrls'); - - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://myserver/')); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://test/')); - - $frameset = &new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertListInAnyOrder( - $frameset->getUrls(), - array('http://www.lastcraft.com/', 'http://myserver/', 'http://test/')); - } - - function testLabelledUrlsComeFromBothFrames() { - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('goodbye.php')), - array('a')); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('hello.php')), - array('a')); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2, 'Two'); - - $expected1 = new SimpleUrl('goodbye.php'); - $expected1->setTarget(1); - $expected2 = new SimpleUrl('hello.php'); - $expected2->setTarget('Two'); - $this->assertEqual( - $frameset->getUrlsByLabel('a'), - array($expected1, $expected2)); - } - - function testUrlByIdComesFromFirstFrameToRespond() { - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getUrlById', new SimpleUrl('four.php'), array(4)); - $frame1->setReturnValue('getUrlById', false, array(5)); - - $frame2 = &new MockSimplePage(); - $frame2->setReturnValue('getUrlById', false, array(4)); - $frame2->setReturnValue('getUrlById', new SimpleUrl('five.php'), array(5)); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $four = new SimpleUrl('four.php'); - $four->setTarget(1); - $this->assertEqual($frameset->getUrlById(4), $four); - $five = new SimpleUrl('five.php'); - $five->setTarget(2); - $this->assertEqual($frameset->getUrlById(5), $five); - } - - function testReadUrlsFromFrameInFocus() { - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getUrls', array('a')); - $frame1->setReturnValue('getUrlsByLabel', array(new SimpleUrl('l'))); - $frame1->setReturnValue('getUrlById', new SimpleUrl('i')); - - $frame2 = &new MockSimplePage(); - $frame2->expectNever('getUrls'); - $frame2->expectNever('getUrlsByLabel'); - $frame2->expectNever('getUrlById'); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrls(), array('a')); - $expected = new SimpleUrl('l'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($expected)); - $expected = new SimpleUrl('i'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlById(99), $expected); - } - - function testReadFrameTaggedUrlsFromFrameInFocus() { - $frame = &new MockSimplePage(); - - $by_label = new SimpleUrl('l'); - $by_label->setTarget('L'); - $frame->setReturnValue('getUrlsByLabel', array($by_label)); - - $by_id = new SimpleUrl('i'); - $by_id->setTarget('I'); - $frame->setReturnValue('getUrlById', $by_id); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame, 'A'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($by_label)); - $this->assertIdentical($frameset->getUrlById(99), $by_id); - } - - function testFindingFormsById() { - $frame = &new MockSimplePage(); - $form = &new MockSimpleForm(); - $frame->setReturnReference('getFormById', $form, array('a')); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertReference($frameset->getFormById('a'), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormById('a')); - - $frameset->setFrameFocus('B'); - $this->assertReference($frameset->getFormById('a'), $form); - } - - function testFindingFormsBySubmit() { - $frame = &new MockSimplePage(); - $form = &new MockSimpleForm(); - $frame->setReturnReference( - 'getFormBySubmit', - $form, - array(new SimpleByLabel('a'))); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertReference($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormBySubmit(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertReference($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - } - - function testFindingFormsByImage() { - $frame = &new MockSimplePage(); - $form = &new MockSimpleForm(); - $frame->setReturnReference( - 'getFormByImage', - $form, - array(new SimpleByLabel('a'))); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertReference($frameset->getFormByImage(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormByImage(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertReference($frameset->getFormByImage(new SimpleByLabel('a')), $form); - } - - function testSettingAllFrameFieldsWhenNoFrameFocus() { - $frame1 = &new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frame2 = &new MockSimplePage(); - $frame2->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setField(new SimpleById(22), 'A'); - } - - function testOnlySettingFieldFromFocusedFrame() { - $frame1 = &new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleByLabelOrName('a'), 'A')); - - $frame2 = &new MockSimplePage(); - $frame2->expectNever('setField'); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $frameset->setField(new SimpleByLabelOrName('a'), 'A'); - } - - function testOnlyGettingFieldFromFocusedFrame() { - $frame1 = &new MockSimplePage(); - $frame1->setReturnValue('getField', 'f', array(new SimpleByName('a'))); - - $frame2 = &new MockSimplePage(); - $frame2->expectNever('getField'); - - $frameset = &new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'f'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/http_test.php b/tests/simpletest/test/http_test.php deleted file mode 100644 index d249850c8..000000000 --- a/tests/simpletest/test/http_test.php +++ /dev/null @@ -1,427 +0,0 @@ -expectArgumentsAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html')); - - $this->assertReference($route->createConnection('GET', 15), $socket); - } - - function testDefaultPostRequest() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("POST /here.html HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html')); - - $route->createConnection('POST', 15); - } - - function testGetWithPort() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host:81\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleRoute(new SimpleUrl('http://a.valid.host:81/here.html')); - - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("GET /here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html?a=1&b=2')); - - $route->createConnection('GET', 15); - } -} - -class TestOfProxyRoute extends UnitTestCase { - - function testDefaultGet() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleProxyRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleProxyRoute( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testDefaultPost() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("POST http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleProxyRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleProxyRoute( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('POST', 15); - } - - function testGetWithPort() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host:81/here.html HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8081\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleProxyRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleProxyRoute( - new SimpleUrl('http://a.valid.host:81/here.html'), - new SimpleUrl('http://my-proxy:8081')); - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host/here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = &new PartialSimpleProxyRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleProxyRoute( - new SimpleUrl('http://a.valid.host/here.html?a=1&b=2'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testGetWithAuthentication() { - $encoded = base64_encode('Me:Secret'); - - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectArgumentsAt(2, 'write', array("Proxy-Authorization: Basic $encoded\r\n")); - $socket->expectArgumentsAt(3, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 4); - - $route = &new PartialSimpleProxyRoute(); - $route->setReturnReference('_createSocket', $socket); - $route->SimpleProxyRoute( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy'), - 'Me', - 'Secret'); - $route->createConnection('GET', 15); - } -} - -class TestOfHttpRequest extends UnitTestCase { - - function testReadingBadConnection() { - $socket = &new MockSimpleSocket(); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); - $reponse = &$request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = &new MockSimpleSocket(); - $socket->expectOnce('write', array("\r\n")); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expectArguments('createConnection', array('GET', 15)); - - $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testWritingAdditionalHeaders() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("My: stuff\r\n")); - $socket->expectArgumentsAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->addHeaderLine('My: stuff'); - $request->fetch(15); - } - - function testCookieWriting() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("Cookie: a=A\r\n")); - $socket->expectArgumentsAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testMultipleCookieWriting() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("Cookie: a=A;b=B\r\n")); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - $jar->setCookie('b', 'B'); - - $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $request->fetch(15); - } -} - -class TestOfHttpPostRequest extends UnitTestCase { - - function testReadingBadConnectionCausesErrorBecauseOfDeadSocket() { - $socket = &new MockSimpleSocket(); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $request = &new SimpleHttpRequest($route, new SimplePostEncoding()); - $reponse = &$request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectArgumentsAt(2, 'write', array("\r\n")); - $socket->expectArgumentsAt(3, 'write', array("")); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expectArguments('createConnection', array('POST', 15)); - - $request = &new SimpleHttpRequest($route, new SimplePostEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculated() { - $socket = &new MockSimpleSocket(); - $socket->expectArgumentsAt(0, 'write', array("Content-Length: 3\r\n")); - $socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectArgumentsAt(2, 'write', array("\r\n")); - $socket->expectArgumentsAt(3, 'write', array("a=A")); - - $route = &new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expectArguments('createConnection', array('POST', 15)); - - $request = &new SimpleHttpRequest( - $route, - new SimplePostEncoding(array('a' => 'A'))); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } -} - -class TestOfHttpHeaders extends UnitTestCase { - - function testParseBasicHeaders() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - } - - function testNonStandardResponseHeader() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 302 (HTTP-Version SP Status-Code CRLF)\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 302); - } - - function testCanParseMultipleCookies() { - $jar = &new MockSimpleCookieJar(); - $jar->expectAt(0, 'setCookie', array('a', 'aaa', 'host', '/here/', 'Wed, 25 Dec 2002 04:24:20 GMT')); - $jar->expectAt(1, 'setCookie', array('b', 'bbb', 'host', '/', false)); - - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Set-Cookie: a=aaa; expires=Wed, 25-Dec-02 04:24:20 GMT; path=/here/\r\n" . - "Set-Cookie: b=bbb\r\n" . - "Connection: close"); - $headers->writeCookiesToJar($jar, new SimpleUrl('http://host')); - } - - function testCanRecogniseRedirect() { - $headers = new SimpleHttpHeaders("HTTP/1.1 301 OK\r\n" . - "Content-Type: text/plain\r\n" . - "Content-Length: 0\r\n" . - "Location: http://www.somewhere-else.com/\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 301); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - $this->assertTrue($headers->isRedirect()); - } - - function testCanParseChallenge() { - $headers = new SimpleHttpHeaders("HTTP/1.1 401 Authorization required\r\n" . - "Content-Type: text/plain\r\n" . - "Connection: close\r\n" . - "WWW-Authenticate: Basic realm=\"Somewhere\""); - $this->assertEqual($headers->getAuthentication(), 'Basic'); - $this->assertEqual($headers->getRealm(), 'Somewhere'); - $this->assertTrue($headers->isChallenge()); - } -} - -class TestOfHttpResponse extends UnitTestCase { - - function testBadRequest() { - $socket = &new MockSimpleSocket(); - $socket->setReturnValue('getSent', ''); - - $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertPattern('/Nothing fetched/', $response->getError()); - $this->assertIdentical($response->getContent(), false); - $this->assertIdentical($response->getSent(), ''); - } - - function testBadSocketDuringResponse() { - $socket = &new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValue("read", ""); - $socket->setReturnValue('getSent', 'HTTP/1.1 ...'); - - $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ''); - $this->assertEqual($response->getSent(), 'HTTP/1.1 ...'); - } - - function testIncompleteHeader() { - $socket = &new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(2, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValue("read", ""); - - $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ""); - } - - function testParseOfResponseHeadersWhenChunked() { - $socket = &new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\nDate: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\nConne"); - $socket->setReturnValueAt(3, "read", "ction: close\r\n\r\nthis is a test file\n"); - $socket->setReturnValueAt(4, "read", "with two lines in it\n"); - $socket->setReturnValue("read", ""); - - $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertFalse($response->isError()); - $this->assertEqual( - $response->getContent(), - "this is a test file\nwith two lines in it\n"); - $headers = $response->getHeaders(); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - $this->assertFalse($headers->isRedirect()); - $this->assertFalse($headers->getLocation()); - } - - function testRedirect() { - $socket = &new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - } - - function testRedirectWithPort() { - $socket = &new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com:80/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com:80/"); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/interfaces_test.php b/tests/simpletest/test/interfaces_test.php deleted file mode 100644 index b6980edb1..000000000 --- a/tests/simpletest/test/interfaces_test.php +++ /dev/null @@ -1,137 +0,0 @@ -assertIsA($mock, 'SimpleMock'); - $this->assertIsA($mock, 'MockDummyInterface'); - $this->assertTrue(method_exists($mock, 'aMethod')); - $this->assertTrue(method_exists($mock, 'anotherMethod')); - $this->assertNull($mock->aMethod()); - } - - function testMockedInterfaceExpectsParameters() { - $mock = new MockDummyInterface(); - $mock->anotherMethod(); - $this->assertError(); - } - - function testCannotPartiallyMockAnInterface() { - $this->assertFalse(class_exists('PartialDummyInterface')); - } -} - -class TestOfSpl extends UnitTestCase { - - function skip() { - $this->skipUnless(function_exists('spl_classes'), 'No SPL module loaded'); - } - - function testCanMockAllSplClasses() { - if (! function_exists('spl_classes')) { - return; - } - foreach(spl_classes() as $class) { - if ($class == 'SplHeap') { - continue; - } - $mock_class = "Mock$class"; - Mock::generate($class); - $this->assertIsA(new $mock_class(), $mock_class); - } - } - - function testExtensionOfCommonSplClasses() { - Mock::generate('IteratorImplementation'); - $this->assertIsA( - new IteratorImplementation(), - 'IteratorImplementation'); - Mock::generate('IteratorAggregateImplementation'); - $this->assertIsA( - new IteratorAggregateImplementation(), - 'IteratorAggregateImplementation'); - } -} - -class WithHint { - function hinted(DummyInterface $object) { } -} - -class ImplementsDummy implements DummyInterface { - function aMethod() { } - function anotherMethod($a) { } - function &referenceMethod(&$a) { } - function extraMethod($a = false) { } -} -Mock::generate('ImplementsDummy'); - -class TestOfImplementations extends UnitTestCase { - - function testMockedInterfaceCanPassThroughTypeHint() { - $mock = new MockDummyInterface(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testImplementedInterfacesAreCarried() { - $mock = new MockImplementsDummy(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testNoSpuriousWarningsWhenSkippingDefaultedParameter() { - $mock = new MockImplementsDummy(); - $mock->extraMethod(); - } -} - -interface SampleClassWithConstruct { - function __construct($something); -} - -class TestOfInterfaceMocksWithConstruct extends UnitTestCase { - function testBasicConstructOfAnInterface() { - Mock::generate('SampleClassWithConstruct'); - $this->assertNoErrors(); - } -} - -interface SampleInterfaceWithHintInSignature { - function method(array $hinted); -} - -class TestOfInterfaceMocksWithHintInSignature extends UnitTestCase { - function testBasicConstructOfAnInterfaceWithHintInSignature() { - Mock::generate('SampleInterfaceWithHintInSignature'); - $this->assertNoErrors(); - $mock = new MockSampleInterfaceWithHintInSignature(); - $this->assertIsA($mock, 'SampleInterfaceWithHintInSignature'); - } -} - -interface SampleInterfaceWithClone { - function __clone(); -} - -class TestOfSampleInterfaceWithClone extends UnitTestCase { - function testCanMockWithoutErrors() { - Mock::generate('SampleInterfaceWithClone'); - $this->assertNoErrors(); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/live_test.php b/tests/simpletest/test/live_test.php deleted file mode 100644 index b294030e1..000000000 --- a/tests/simpletest/test/live_test.php +++ /dev/null @@ -1,47 +0,0 @@ -assertTrue($socket->isError()); - $this->assertPattern( - '/Cannot open \\[bad_url:111\\] with \\[/', - $socket->getError()); - $this->assertFalse($socket->isOpen()); - $this->assertFalse($socket->write('A message')); - } - - function testSocketClosure() { - $socket = &new SimpleSocket('www.lastcraft.com', 80, 15, 8); - $this->assertTrue($socket->isOpen()); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $this->assertEqual($socket->read(), "HTTP/1.1"); - $socket->close(); - $this->assertIdentical($socket->read(), false); - } - - function testRecordOfSentCharacters() { - $socket = &new SimpleSocket('www.lastcraft.com', 80, 15); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $socket->close(); - $this->assertEqual($socket->getSent(), - "GET /test/network_confirm.php HTTP/1.0\r\n" . - "Host: www.lastcraft.com\r\n" . - "Connection: close\r\n\r\n"); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/mock_objects_test.php b/tests/simpletest/test/mock_objects_test.php deleted file mode 100644 index a208ff727..000000000 --- a/tests/simpletest/test/mock_objects_test.php +++ /dev/null @@ -1,994 +0,0 @@ -assertTrue($expectation->test(33)); - $this->assertTrue($expectation->test(false)); - $this->assertTrue($expectation->test(null)); - } -} - -class TestOfParametersExpectation extends UnitTestCase { - - function testEmptyMatch() { - $expectation = new ParametersExpectation(array()); - $this->assertTrue($expectation->test(array())); - $this->assertFalse($expectation->test(array(33))); - } - - function testSingleMatch() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array(1))); - $this->assertTrue($expectation->test(array(0))); - } - - function testAnyMatch() { - $expectation = new ParametersExpectation(false); - $this->assertTrue($expectation->test(array())); - $this->assertTrue($expectation->test(array(1, 2))); - } - - function testMissingParameter() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array())); - } - - function testNullParameter() { - $expectation = new ParametersExpectation(array(null)); - $this->assertTrue($expectation->test(array(null))); - $this->assertFalse($expectation->test(array())); - } - - function testAnythingExpectations() { - $expectation = new ParametersExpectation(array(new AnythingExpectation())); - $this->assertFalse($expectation->test(array())); - $this->assertIdentical($expectation->test(array(null)), true); - $this->assertIdentical($expectation->test(array(13)), true); - } - - function testOtherExpectations() { - $expectation = new ParametersExpectation( - array(new PatternExpectation('/hello/i'))); - $this->assertFalse($expectation->test(array('Goodbye'))); - $this->assertTrue($expectation->test(array('hello'))); - $this->assertTrue($expectation->test(array('Hello'))); - } - - function testIdentityOnly() { - $expectation = new ParametersExpectation(array("0")); - $this->assertFalse($expectation->test(array(0))); - $this->assertTrue($expectation->test(array("0"))); - } - - function testLongList() { - $expectation = new ParametersExpectation( - array("0", 0, new AnythingExpectation(), false)); - $this->assertTrue($expectation->test(array("0", 0, 37, false))); - $this->assertFalse($expectation->test(array("0", 0, 37, true))); - $this->assertFalse($expectation->test(array("0", 0, 37))); - } -} - -class TestOfSimpleSignatureMap extends UnitTestCase { - - function testEmpty() { - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch("any", array())); - $this->assertNull($map->findFirstAction("any", array())); - } - - function testExactReference() { - $map = new SimpleSignatureMap(); - $ref = "Fred"; - $map->add(array(0), $ref); - $this->assertEqual($map->findFirstAction(array(0)), "Fred"); - $ref2 = &$map->findFirstAction(array(0)); - $this->assertReference($ref2, $ref); - } - - function testDifferentCallSignaturesCanHaveDifferentReferences() { - $map = new SimpleSignatureMap(); - $fred = 'Fred'; - $jim = 'jim'; - $map->add(array(0), $fred); - $map->add(array('0'), $jim); - $this->assertReference($fred, $map->findFirstAction(array(0))); - $this->assertReference($jim, $map->findFirstAction(array('0'))); - } - - function testWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $map->add(array(new AnythingExpectation(), 1, 3), $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertReference($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testAllWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch(array(2, 1, 3))); - $map->add('', $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertReference($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testOrdering() { - $map = new SimpleSignatureMap(); - $map->add(array(1, 2), new SimpleByValue("1, 2")); - $map->add(array(1, 3), new SimpleByValue("1, 3")); - $map->add(array(1), new SimpleByValue("1")); - $map->add(array(1, 4), new SimpleByValue("1, 4")); - $map->add(array(new AnythingExpectation()), new SimpleByValue("Any")); - $map->add(array(2), new SimpleByValue("2")); - $map->add("", new SimpleByValue("Default")); - $map->add(array(), new SimpleByValue("None")); - $this->assertEqual($map->findFirstAction(array(1, 2)), new SimpleByValue("1, 2")); - $this->assertEqual($map->findFirstAction(array(1, 3)), new SimpleByValue("1, 3")); - $this->assertEqual($map->findFirstAction(array(1, 4)), new SimpleByValue("1, 4")); - $this->assertEqual($map->findFirstAction(array(1)), new SimpleByValue("1")); - $this->assertEqual($map->findFirstAction(array(2)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array(3)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array()), new SimpleByValue("Default")); - } -} - -class TestOfCallSchedule extends UnitTestCase { - function testCanBeSetToAlwaysReturnTheSameReference() { - $a = 5; - $schedule = &new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByReference($a)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $a); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $a); - } - - function testSpecificSignaturesOverrideTheAlwaysCase() { - $any = 'any'; - $one = 'two'; - $schedule = &new SimpleCallSchedule(); - $schedule->register('aMethod', array(1), new SimpleByReference($one)); - $schedule->register('aMethod', false, new SimpleByReference($any)); - $this->assertReference($schedule->respond(0, 'aMethod', array(2)), $any); - $this->assertReference($schedule->respond(0, 'aMethod', array(1)), $one); - } - - function testReturnsCanBeSetOverTime() { - $one = 'one'; - $two = 'two'; - $schedule = &new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - } - - function testReturnsOverTimecanBeAlteredByTheArguments() { - $one = '1'; - $two = '2'; - $two_a = '2a'; - $schedule = &new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', array('a'), new SimpleByReference($two_a)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - $this->assertReference($schedule->respond(1, 'aMethod', array('a')), $two_a); - } - - function testCanReturnByValue() { - $a = 5; - $schedule = &new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByValue($a)); - $this->assertClone($schedule->respond(0, 'aMethod', array()), $a); - } - - function testCanThrowException() { - if (version_compare(phpversion(), '5', '>=')) { - $schedule = &new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleThrower(new Exception('Ouch'))); - $this->expectException(new Exception('Ouch')); - $schedule->respond(0, 'aMethod', array()); - } - } - - function testCanEmitError() { - $schedule = &new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleErrorThrower('Ouch', E_USER_WARNING)); - $this->expectError('Ouch'); - $schedule->respond(0, 'aMethod', array()); - } -} - -class Dummy { - function Dummy() { - } - - function aMethod() { - return true; - } - - function anotherMethod() { - return true; - } -} -Mock::generate('Dummy'); -Mock::generate('Dummy', 'AnotherMockDummy'); -Mock::generate('Dummy', 'MockDummyWithExtraMethods', array('extraMethod')); - -class TestOfMockGeneration extends UnitTestCase { - - function testCloning() { - $mock = &new MockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - $this->assertNull($mock->aMethod()); - } - - function testCloningWithExtraMethod() { - $mock = &new MockDummyWithExtraMethods(); - $this->assertTrue(method_exists($mock, "extraMethod")); - } - - function testCloningWithChosenClassName() { - $mock = &new AnotherMockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - } -} - -class TestOfMockReturns extends UnitTestCase { - - function testDefaultReturn() { - $mock = &new MockDummy(); - $mock->setReturnValue("aMethod", "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - } - - function testParameteredReturn() { - $mock = &new MockDummy(); - $mock->setReturnValue('aMethod', 'aaa', array(1, 2, 3)); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(1, 2, 3), 'aaa'); - } - - function testReferenceReturned() { - $mock = &new MockDummy(); - $object = new Dummy(); - $mock->setReturnReference('aMethod', $object, array(1, 2, 3)); - $this->assertReference($zref = &$mock->aMethod(1, 2, 3), $object); - } - - function testPatternMatchReturn() { - $mock = &new MockDummy(); - $mock->setReturnValue( - "aMethod", - "aaa", - array(new PatternExpectation('/hello/i'))); - $this->assertIdentical($mock->aMethod('Hello'), "aaa"); - $this->assertNull($mock->aMethod('Goodbye')); - } - - function testMultipleMethods() { - $mock = &new MockDummy(); - $mock->setReturnValue("aMethod", 100, array(1)); - $mock->setReturnValue("aMethod", 200, array(2)); - $mock->setReturnValue("anotherMethod", 10, array(1)); - $mock->setReturnValue("anotherMethod", 20, array(2)); - $this->assertIdentical($mock->aMethod(1), 100); - $this->assertIdentical($mock->anotherMethod(1), 10); - $this->assertIdentical($mock->aMethod(2), 200); - $this->assertIdentical($mock->anotherMethod(2), 20); - } - - function testReturnSequence() { - $mock = &new MockDummy(); - $mock->setReturnValueAt(0, "aMethod", "aaa"); - $mock->setReturnValueAt(1, "aMethod", "bbb"); - $mock->setReturnValueAt(3, "aMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(), "ddd"); - } - - function testReturnReferenceSequence() { - $mock = &new MockDummy(); - $object = new Dummy(); - $mock->setReturnReferenceAt(1, "aMethod", $object); - $this->assertNull($mock->aMethod()); - $this->assertReference($zref =& $mock->aMethod(), $object); - $this->assertNull($mock->aMethod()); - } - - function testComplicatedReturnSequence() { - $mock = &new MockDummy(); - $object = new Dummy(); - $mock->setReturnValueAt(1, "aMethod", "aaa", array("a")); - $mock->setReturnValueAt(1, "aMethod", "bbb"); - $mock->setReturnReferenceAt(2, "aMethod", $object, array('*', 2)); - $mock->setReturnValueAt(2, "aMethod", "value", array('*', 3)); - $mock->setReturnValue("aMethod", 3, array(3)); - $this->assertNull($mock->aMethod()); - $this->assertEqual($mock->aMethod("a"), "aaa"); - $this->assertReference($zref =& $mock->aMethod(1, 2), $object); - $this->assertEqual($mock->aMethod(3), 3); - $this->assertNull($mock->aMethod()); - } - - function testMultipleMethodSequences() { - $mock = &new MockDummy(); - $mock->setReturnValueAt(0, "aMethod", "aaa"); - $mock->setReturnValueAt(1, "aMethod", "bbb"); - $mock->setReturnValueAt(0, "anotherMethod", "ccc"); - $mock->setReturnValueAt(1, "anotherMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->anotherMethod(), "ccc"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertIdentical($mock->anotherMethod(), "ddd"); - } - - function testSequenceFallback() { - $mock = &new MockDummy(); - $mock->setReturnValueAt(0, "aMethod", "aaa", array('a')); - $mock->setReturnValueAt(1, "aMethod", "bbb", array('a')); - $mock->setReturnValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod('a'), "aaa"); - $this->assertIdentical($mock->aMethod('b'), "AAA"); - } - - function testMethodInterference() { - $mock = &new MockDummy(); - $mock->setReturnValueAt(0, "anotherMethod", "aaa"); - $mock->setReturnValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod(), "AAA"); - $this->assertIdentical($mock->anotherMethod(), "aaa"); - } -} - -class TestOfMockExpectationsThatPass extends UnitTestCase { - - function testAnyArgument() { - $mock = &new MockDummy(); - $mock->expect('aMethod', array('*')); - $mock->aMethod(1); - $mock->aMethod('hello'); - } - - function testAnyTwoArguments() { - $mock = &new MockDummy(); - $mock->expect('aMethod', array('*', '*')); - $mock->aMethod(1, 2); - } - - function testSpecificArgument() { - $mock = &new MockDummy(); - $mock->expect('aMethod', array(1)); - $mock->aMethod(1); - } - - function testExpectation() { - $mock = &new MockDummy(); - $mock->expect('aMethod', array(new IsAExpectation('Dummy'))); - $mock->aMethod(new Dummy()); - } - - function testArgumentsInSequence() { - $mock = &new MockDummy(); - $mock->expectAt(0, 'aMethod', array(1, 2)); - $mock->expectAt(1, 'aMethod', array(3, 4)); - $mock->aMethod(1, 2); - $mock->aMethod(3, 4); - } - - function testAtLeastOnceSatisfiedByOneCall() { - $mock = &new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - } - - function testAtLeastOnceSatisfiedByTwoCalls() { - $mock = &new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - } - - function testOnceSatisfiedByOneCall() { - $mock = &new MockDummy(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByEnoughCalls() { - $mock = &new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByTooManyCalls() { - $mock = &new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 3); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByEnoughCalls() { - $mock = &new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByNoCalls() { - $mock = &new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - } -} - -class MockWithInjectedTestCase extends SimpleMock { - function &_getCurrentTestCase() { - $context = &SimpleTest::getContext(); - $test = &$context->getTest(); - return $test->getMockedTest(); - } -} -SimpleTest::setMockBaseClass('MockWithInjectedTestCase'); -Mock::generate('Dummy', 'MockDummyWithInjectedTestCase'); -SimpleTest::setMockBaseClass('SimpleMock'); -Mock::generate('SimpleTestCase'); - -class LikeExpectation extends IdenticalExpectation { - function LikeExpectation($expectation) { - $expectation->_message = ''; - $this->IdenticalExpectation($expectation); - } - - function test($compare) { - $compare->_message = ''; - return parent::test($compare); - } - - function testMessage($compare) { - $compare->_message = ''; - return parent::testMessage($compare); - } -} - -class TestOfMockExpectations extends UnitTestCase { - var $test; - - function setUp() { - $this->test = &new MockSimpleTestCase(); - } - - function &getMockedTest() { - return $this->test; - } - - function testSettingExpectationOnNonMethodThrowsError() { - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount('aMissingMethod', 2); - $this->assertError(); - } - - function testMaxCallsDetectsOverrun() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new MaximumCallCountExpectation('aMethod', 2)), - 3)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnMaxCallsSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new MaximumCallCountExpectation('aMethod', 2)), - 2)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount("aMethod", 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testExpectNeverDetectsOverrun() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new MaximumCallCountExpectation('aMethod', 0)), - 1)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnExpectNeverStillSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new MaximumCallCountExpectation('aMethod', 0)), - 0)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testMinCalls() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new MinimumCallCountExpectation('aMethod', 2)), - 2)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectMinimumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testFailedNever() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new MaximumCallCountExpectation('aMethod', 0)), - 1)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testUnderOnce() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new CallCountExpectation('aMethod', 1)), - 0)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testOverOnce() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new CallCountExpectation('aMethod', 1)), - 2)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testUnderAtLeastOnce() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new MinimumCallCountExpectation('aMethod', 1)), - 0)); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectAtLeastOnce("aMethod"); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testZeroArguments() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new ParametersExpectation(array())), - array(), - '*')); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expect("aMethod", array()); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testExpectedArguments() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new ParametersExpectation(array(1, 2, 3))), - array(1, 2, 3), - '*')); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array(1, 2, 3)); - $mock->aMethod(1, 2, 3); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testFailedArguments() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new ParametersExpectation(array('this'))), - array('that'), - '*')); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array('this')); - $mock->aMethod('that'); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testWildcardsAreTranslatedToAnythingExpectations() { - $this->test->expectOnce('assert', array( - new LikeExpectation(new ParametersExpectation(array( - new AnythingExpectation(), 123, new AnythingExpectation()))), - array(100, 123, 101), - '*')); - $mock = &new MockDummyWithInjectedTestCase($this); - $mock->expect("aMethod", array('*', 123, '*')); - $mock->aMethod(100, 123, 101); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testSpecificPassingSequence() { - $this->test->expectAt(0, 'assert', array( - new LikeExpectation(new ParametersExpectation(array(1, 2, 3))), - array(1, 2, 3), - '*')); - $this->test->expectAt(1, 'assert', array( - new LikeExpectation(new ParametersExpectation(array('Hello'))), - array('Hello'), - '*')); - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expectAt(1, 'aMethod', array(1, 2, 3)); - $mock->expectAt(2, 'aMethod', array('Hello')); - $mock->aMethod(); - $mock->aMethod(1, 2, 3); - $mock->aMethod('Hello'); - $mock->aMethod(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } - - function testNonArrayForExpectedParametersGivesError() { - $mock = &new MockDummyWithInjectedTestCase(); - $mock->expect("aMethod", "foo"); - $this->assertErrorPattern('/\$args.*not an array/i'); - $mock->aMethod(); - $mock->tally(); - $mock->_mock->atTestEnd('testSomething', $this->test); - } -} - -class TestOfMockComparisons extends UnitTestCase { - - function testEqualComparisonOfMocksDoesNotCrash() { - $expectation = &new EqualExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy(), true)); - } - - function testIdenticalComparisonOfMocksDoesNotCrash() { - $expectation = &new IdenticalExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy())); - } -} - -class ClassWithSpecialMethods { - function __get($name) { } - function __set($name, $value) { } - function __isset($name) { } - function __unset($name) { } - function __call($method, $arguments) { } - function __toString() { } -} -Mock::generate('ClassWithSpecialMethods'); - -class TestOfSpecialMethods extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5', '<='), 'Overloading not tested unless PHP 5+'); - } - - function testCanMockTheThingAtAll() { - $mock = new MockClassWithSpecialMethods(); - } - - function testReturnFromSpecialAccessor() { - $mock = &new MockClassWithSpecialMethods(); - $mock->setReturnValue('__get', '1st Return', array('first')); - $mock->setReturnValue('__get', '2nd Return', array('second')); - $this->assertEqual($mock->first, '1st Return'); - $this->assertEqual($mock->second, '2nd Return'); - } - - function testcanExpectTheSettingOfValue() { - $mock = &new MockClassWithSpecialMethods(); - $mock->expectOnce('__set', array('a', 'A')); - $mock->a = 'A'; - } - - function testCanSimulateAnOverloadmethod() { - $mock = &new MockClassWithSpecialMethods(); - $mock->expectOnce('__call', array('amOverloaded', array('A'))); - $mock->setReturnValue('__call', 'aaa'); - $this->assertIdentical($mock->amOverloaded('A'), 'aaa'); - } - - function testCanEmulateIsset() { - $mock = &new MockClassWithSpecialMethods(); - $mock->setReturnValue('__isset', true); - $this->assertIdentical(isset($mock->a), true); - } - - function testCanExpectUnset() { - $mock = &new MockClassWithSpecialMethods(); - $mock->expectOnce('__unset', array('a')); - unset($mock->a); - } - - function testToStringMagic() { - $mock = &new MockClassWithSpecialMethods(); - $mock->expectOnce('__toString'); - $mock->setReturnValue('__toString', 'AAA'); - ob_start(); - print $mock; - $output = ob_get_contents(); - ob_end_clean(); - $this->assertEqual($output, 'AAA'); - } -} - -if (version_compare(phpversion(), '5', '>=')) { - $class = 'class WithStaticMethod { '; - $class .= ' static function aStaticMethod() { } '; - $class .= '}'; - eval($class); -} -Mock::generate('WithStaticMethod'); - -class TestOfMockingClassesWithStaticMethods extends UnitTestCase { - function skip() { - $this->skipUnless(version_compare(phpversion(), '5', '>='), 'Static methods not tested unless PHP 5+'); - } - - function testStaticMethodIsMockedAsStatic() { - $mock = new WithStaticMethod(); - $reflection = new ReflectionClass($mock); - $method = $reflection->getMethod('aStaticMethod'); - $this->assertTrue($method->isStatic()); - } -} - -if (version_compare(phpversion(), '5', '>=')) { - class MockTestException extends Exception { } -} - -class TestOfThrowingExceptionsFromMocks extends UnitTestCase { - function skip() { - $this->skipUnless(version_compare(phpversion(), '5', '>='), 'Exception throwing not tested unless PHP 5+'); - } - - function testCanThrowOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod'); - $this->expectException(); - $mock->aMethod(); - } - - function testCanThrowSpecificExceptionOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException()); - $this->expectException(); - $mock->aMethod(); - } - - function testThrowsOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException(), array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectException(); - $mock->aMethod(3); - } - - function testCanThrowOnParticularInvocation() { - $mock = new MockDummy(); - $mock->throwAt(2, 'aMethod', new MockTestException()); - $mock->aMethod(); - $mock->aMethod(); - $this->expectException(); - $mock->aMethod(); - } -} - -class TestOfThrowingErrorsFromMocks extends UnitTestCase { - - function testCanGenerateErrorFromMethodCall() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!'); - $this->expectError('Ouch!'); - $mock->aMethod(); - } - - function testGeneratesErrorOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!', array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectError(); - $mock->aMethod(3); - } - - function testCanGenerateErrorOnParticularInvocation() { - $mock = new MockDummy(); - $mock->errorAt(2, 'aMethod', 'Ouch!'); - $mock->aMethod(); - $mock->aMethod(); - $this->expectError(); - $mock->aMethod(); - } -} - -Mock::generatePartial('Dummy', 'TestDummy', array('anotherMethod')); - -class TestOfPartialMocks extends UnitTestCase { - - function testMethodReplacementWithNoBehaviourReturnsNull() { - $mock = &new TestDummy(); - $this->assertEqual($mock->aMethod(99), 99); - $this->assertNull($mock->anotherMethod()); - } - - function testSettingReturns() { - $mock = &new TestDummy(); - $mock->setReturnValue('anotherMethod', 33, array(3)); - $mock->setReturnValue('anotherMethod', 22); - $mock->setReturnValueAt(2, 'anotherMethod', 44, array(3)); - $this->assertEqual($mock->anotherMethod(), 22); - $this->assertEqual($mock->anotherMethod(3), 33); - $this->assertEqual($mock->anotherMethod(3), 44); - } - - function testReferences() { - $mock = &new TestDummy(); - $object = new Dummy(); - $mock->setReturnReferenceAt(0, 'anotherMethod', $object, array(3)); - $this->assertReference($zref =& $mock->anotherMethod(3), $object); - } - - function testExpectations() { - $mock = &new TestDummy(); - $mock->expectCallCount('anotherMethod', 2); - $mock->expect('anotherMethod', array(77)); - $mock->expectAt(1, 'anotherMethod', array(66)); - $mock->anotherMethod(77); - $mock->anotherMethod(66); - } - - function testSettingExpectationOnMissingMethodThrowsError() { - $mock = &new TestDummy(); - $mock->expectCallCount('aMissingMethod', 2); - $this->assertError(); - } -} - -class ConstructorSuperClass { - function ConstructorSuperClass() { } -} - -class ConstructorSubClass extends ConstructorSuperClass { -} - -class TestOfPHP4StyleSuperClassConstruct extends UnitTestCase { - /* - * This addresses issue #1231401. Without the fix in place, this will - * generate a fatal PHP error. - */ - function testBasicConstruct() { - Mock::generate('ConstructorSubClass'); - $mock = &new MockConstructorSubClass(); - $this->assertIsA($mock, 'ConstructorSubClass'); - $this->assertTrue(method_exists($mock, 'ConstructorSuperClass')); - } -} - -class TestOfPHP5StaticMethodMocking extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5', '<='), 'Static methods not tested unless PHP 5+'); - } - - function testCanCreateAMockObjectWithStaticMethodsWithoutError() { - eval(' - class SimpleObjectContainingStaticMethod { - static function someStatic() { } - } - '); - - Mock::generate('SimpleObjectContainingStaticMethod'); - $this->assertNoErrors(); - } -} - -class TestOfPHP5AbstractMethodMocking extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5', '<='), 'Abstract class/methods not tested unless PHP 5+'); - } - - function testCanCreateAMockObjectFromAnAbstractWithProperFunctionDeclarations() { - eval(' - abstract class SimpleAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - '); - - Mock::generate('SimpleAbstractClassContainingAbstractMethods'); - $this->assertNoErrors(); - - $this->assertTrue( - method_exists( - 'MockSimpleAbstractClassContainingAbstractMethods', - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - 'MockSimpleAbstractClassContainingAbstractMethods', - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - 'MockSimpleAbstractClassContainingAbstractMethods', - 'anAbstractWithMultipleParameters' - ) - ); - } - - function testMethodsDefinedAsAbstractInParentShouldHaveFullSignature() { - eval(' - abstract class SimpleParentAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - - class SimpleChildAbstractClassContainingAbstractMethods extends SimpleParentAbstractClassContainingAbstractMethods { - function anAbstract(){} - function anAbstractWithParameter($foo){} - function anAbstractWithMultipleParameters($foo, $bar){} - } - - class EvenDeeperEmptyChildClass extends SimpleChildAbstractClassContainingAbstractMethods {} - '); - - Mock::generate('SimpleChildAbstractClassContainingAbstractMethods'); - $this->assertNoErrors(); - - $this->assertTrue( - method_exists( - 'MockSimpleChildAbstractClassContainingAbstractMethods', - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - 'MockSimpleChildAbstractClassContainingAbstractMethods', - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - 'MockSimpleChildAbstractClassContainingAbstractMethods', - 'anAbstractWithMultipleParameters' - ) - ); - - Mock::generate('EvenDeeperEmptyChildClass'); - $this->assertNoErrors(); - - $this->assertTrue( - method_exists( - 'MockEvenDeeperEmptyChildClass', - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - 'MockEvenDeeperEmptyChildClass', - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - 'MockEvenDeeperEmptyChildClass', - 'anAbstractWithMultipleParameters' - ) - ); - } -} - -?> diff --git a/tests/simpletest/test/page_test.php b/tests/simpletest/test/page_test.php deleted file mode 100644 index 76e6a515b..000000000 --- a/tests/simpletest/test/page_test.php +++ /dev/null @@ -1,903 +0,0 @@ - 'http://somewhere')); - $tag->addContent('Label'); - - $page = &new MockSimplePage(); - $page->expectArguments('acceptTag', array($tag)); - $page->expectCallCount('acceptTag', 1); - - $builder = &new PartialSimplePageBuilder(); - $builder->setReturnReference('_createPage', $page); - $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); - $builder->SimplePageBuilder(); - - $builder->parse(new MockSimpleHttpResponse()); - $this->assertTrue($builder->startElement( - 'a', - array('href' => 'http://somewhere'))); - $this->assertTrue($builder->addContent('Label')); - $this->assertTrue($builder->endElement('a')); - } - - function testLinkWithId() { - $tag = &new SimpleAnchorTag(array("href" => "http://somewhere", "id" => "44")); - $tag->addContent("Label"); - - $page = &new MockSimplePage(); - $page->expectArguments("acceptTag", array($tag)); - $page->expectCallCount("acceptTag", 1); - - $builder = &new PartialSimplePageBuilder(); - $builder->setReturnReference('_createPage', $page); - $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); - $builder->SimplePageBuilder(); - - $builder->parse(new MockSimpleHttpResponse()); - $this->assertTrue($builder->startElement( - "a", - array("href" => "http://somewhere", "id" => "44"))); - $this->assertTrue($builder->addContent("Label")); - $this->assertTrue($builder->endElement("a")); - } - - function testLinkExtraction() { - $tag = &new SimpleAnchorTag(array("href" => "http://somewhere")); - $tag->addContent("Label"); - - $page = &new MockSimplePage(); - $page->expectArguments("acceptTag", array($tag)); - $page->expectCallCount("acceptTag", 1); - - $builder = &new PartialSimplePageBuilder(); - $builder->setReturnReference('_createPage', $page); - $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); - $builder->SimplePageBuilder(); - - $builder->parse(new MockSimpleHttpResponse()); - $this->assertTrue($builder->addContent("Starting stuff")); - $this->assertTrue($builder->startElement( - "a", - array("href" => "http://somewhere"))); - $this->assertTrue($builder->addContent("Label")); - $this->assertTrue($builder->endElement("a")); - $this->assertTrue($builder->addContent("Trailing stuff")); - } - - function testMultipleLinks() { - $a1 = new SimpleAnchorTag(array("href" => "http://somewhere")); - $a1->addContent("1"); - - $a2 = new SimpleAnchorTag(array("href" => "http://elsewhere")); - $a2->addContent("2"); - - $page = &new MockSimplePage(); - $page->expectArgumentsAt(0, "acceptTag", array($a1)); - $page->expectArgumentsAt(1, "acceptTag", array($a2)); - $page->expectCallCount("acceptTag", 2); - - $builder = &new PartialSimplePageBuilder(); - $builder->setReturnReference('_createPage', $page); - $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); - $builder->SimplePageBuilder(); - - $builder->parse(new MockSimpleHttpResponse()); - $builder->startElement("a", array("href" => "http://somewhere")); - $builder->addContent("1"); - $builder->endElement("a"); - $builder->addContent("Padding"); - $builder->startElement("a", array("href" => "http://elsewhere")); - $builder->addContent("2"); - $builder->endElement("a"); - } - - function testTitle() { - $tag = &new SimpleTitleTag(array()); - $tag->addContent("HereThere"); - - $page = &new MockSimplePage(); - $page->expectArguments("acceptTag", array($tag)); - $page->expectCallCount("acceptTag", 1); - - $builder = &new PartialSimplePageBuilder(); - $builder->setReturnReference('_createPage', $page); - $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); - $builder->SimplePageBuilder(); - - $builder->parse(new MockSimpleHttpResponse()); - $builder->startElement("title", array()); - $builder->addContent("Here"); - $builder->addContent("There"); - $builder->endElement("title"); - } - - function testForm() { - $page = &new MockSimplePage(); - $page->expectOnce("acceptFormStart", array(new SimpleFormTag(array()))); - $page->expectOnce("acceptFormEnd", array()); - - $builder = &new PartialSimplePageBuilder(); - $builder->setReturnReference('_createPage', $page); - $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); - $builder->SimplePageBuilder(); - - $builder->parse(new MockSimpleHttpResponse()); - $builder->startElement("form", array()); - $builder->addContent("Stuff"); - $builder->endElement("form"); - } -} - -class TestOfPageParsing extends UnitTestCase { - - function testParseMechanics() { - $parser = &new MockSimpleHtmlSaxParser(); - $parser->expectOnce('parse', array('stuff')); - - $page = &new MockSimplePage(); - $page->expectOnce('acceptPageEnd'); - - $builder = &new PartialSimplePageBuilder(); - $builder->setReturnReference('_createPage', $page); - $builder->setReturnReference('_createParser', $parser); - $builder->SimplePageBuilder(); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', 'stuff'); - $builder->parse($response); - } -} - -class TestOfPageInterface extends UnitTestCase { - - function testInterfaceOnEmptyPage() { - $page = &new SimplePage(); - $this->assertEqual($page->getTransportError(), 'No page fetched yet'); - $this->assertIdentical($page->getRaw(), false); - $this->assertIdentical($page->getHeaders(), false); - $this->assertIdentical($page->getMimeType(), false); - $this->assertIdentical($page->getResponseCode(), false); - $this->assertIdentical($page->getAuthentication(), false); - $this->assertIdentical($page->getRealm(), false); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getUrls(), array()); - $this->assertIdentical($page->getTitle(), false); - } -} - -class TestOfPageHeaders extends UnitTestCase { - - function testUrlAccessor() { - $headers = &new MockSimpleHttpHeaders(); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - $response->setReturnValue('getMethod', 'POST'); - $response->setReturnValue('getUrl', new SimpleUrl('here')); - $response->setReturnValue('getRequestData', array('a' => 'A')); - - $page = &new SimplePage($response); - $this->assertEqual($page->getMethod(), 'POST'); - $this->assertEqual($page->getUrl(), new SimpleUrl('here')); - $this->assertEqual($page->getRequestData(), array('a' => 'A')); - } - - function testTransportError() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getError', 'Ouch'); - - $page = &new SimplePage($response); - $this->assertEqual($page->getTransportError(), 'Ouch'); - } - - function testHeadersAccessor() { - $headers = &new MockSimpleHttpHeaders(); - $headers->setReturnValue('getRaw', 'My: Headers'); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = &new SimplePage($response); - $this->assertEqual($page->getHeaders(), 'My: Headers'); - } - - function testMimeAccessor() { - $headers = &new MockSimpleHttpHeaders(); - $headers->setReturnValue('getMimeType', 'text/html'); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = &new SimplePage($response); - $this->assertEqual($page->getMimeType(), 'text/html'); - } - - function testResponseAccessor() { - $headers = &new MockSimpleHttpHeaders(); - $headers->setReturnValue('getResponseCode', 301); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = &new SimplePage($response); - $this->assertIdentical($page->getResponseCode(), 301); - } - - function testAuthenticationAccessors() { - $headers = &new MockSimpleHttpHeaders(); - $headers->setReturnValue('getAuthentication', 'Basic'); - $headers->setReturnValue('getRealm', 'Secret stuff'); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = &new SimplePage($response); - $this->assertEqual($page->getAuthentication(), 'Basic'); - $this->assertEqual($page->getRealm(), 'Secret stuff'); - } -} - -class TestOfHtmlPage extends UnitTestCase { - - function testRawAccessor() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', 'Raw HTML'); - - $page = &new SimplePage($response); - $this->assertEqual($page->getRaw(), 'Raw HTML'); - } - - function testTextAccessor() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', 'Some "messy" HTML'); - - $page = &new SimplePage($response); - $this->assertEqual($page->getText(), 'Some "messy" HTML'); - } - - function testNoLinks() { - $page = &new SimplePage(new MockSimpleHttpResponse()); - $this->assertIdentical($page->getUrls(), array()); - $this->assertIdentical($page->getUrlsByLabel('Label'), array()); - } - - function testAddAbsoluteLink() { - $link = &new SimpleAnchorTag(array('href' => 'http://somewhere.com')); - $link->addContent('Label'); - $page = &new SimplePage(new MockSimpleHttpResponse()); - $page->AcceptTag($link); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://somewhere.com'))); - } - - function testAddStrictRelativeLink() { - $link = &new SimpleAnchorTag(array('href' => './somewhere.php')); - $link->addContent('Label'); - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - $page = &new SimplePage($response); - $page->AcceptTag($link); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testAddBareRelativeLink() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - $page = &new SimplePage($response); - $page->AcceptTag(new SimpleAnchorTag(array('href' => 'somewhere.php'))); - $this->assertIdentical($page->getUrls(), array('http://host/somewhere.php')); - } - - function testAddRelativeLinkWithBaseTag() { - $link = &new SimpleAnchorTag(array('href' => 'somewhere.php')); - $link->addContent('Label'); - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - $page = &new SimplePage($response); - $page->AcceptTag($link); - $base = &new SimpleBaseTag(array('href' => 'www.lastcraft.com/stuff/')); - $page->AcceptTag($base); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('www.lastcraft.com/stuff/somewhere.php'))); - } - - function testAddAbsoluteLinkWithBaseTag() { - $link = &new SimpleAnchorTag(array('href' => 'http://here.com/somewhere.php')); - $link->addContent('Label'); - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - $page = &new SimplePage($response); - $page->AcceptTag($link); - $base = &new SimpleBaseTag(array('href' => 'www.lastcraft.com/stuff/')); - $page->AcceptTag($base); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://here.com/somewhere.php'))); - } - - function testLinkIds() { - $link = &new SimpleAnchorTag(array('href' => './somewhere.php', 'id' => 33)); - $link->addContent('Label'); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - - $page = &new SimplePage($response); - $page->AcceptTag($link); - - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - $this->assertFalse($page->getUrlById(0)); - $this->assertEqual( - $page->getUrlById(33), - new SimpleUrl('http://host/somewhere.php')); - } - - function testFindLinkWithNormalisation() { - $link = &new SimpleAnchorTag(array('href' => './somewhere.php', 'id' => 33)); - $link->addContent(' Long & thin '); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - - $page = &new SimplePage($response); - $page->AcceptTag($link); - - $this->assertEqual( - $page->getUrlsByLabel('Long & thin'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testFindLinkWithImage() { - $link = &new SimpleAnchorTag(array('href' => './somewhere.php', 'id' => 33)); - $link->addContent('<A picture>'); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - - $page = &new SimplePage($response); - $page->AcceptTag($link); - - $this->assertEqual( - $page->getUrlsByLabel(''), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testTitleSetting() { - $title = &new SimpleTitleTag(array()); - $title->addContent('Title'); - $page = &new SimplePage(new MockSimpleHttpResponse()); - $page->AcceptTag($title); - $this->assertEqual($page->getTitle(), 'Title'); - } - - function testFramesetAbsence() { - $url = new SimpleUrl('here'); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', $url); - $page = &new SimplePage($response); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), false); - } - - function testHasEmptyFrameset() { - $page = &new SimplePage(new MockSimpleHttpResponse()); - $page->acceptFramesetStart(new SimpleTag('frameset', array())); - $page->acceptFramesetEnd(); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array()); - } - - function testFramesInPage() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://here')); - - $page = &new SimplePage($response); - $page->acceptFrame(new SimpleFrameTag(array('src' => '1.html'))); - $page->acceptFramesetStart(new SimpleTag('frameset', array())); - $page->acceptFrame(new SimpleFrameTag(array('src' => '2.html'))); - $page->acceptFrame(new SimpleFrameTag(array('src' => '3.html'))); - $page->acceptFramesetEnd(); - $page->acceptFrame(new SimpleFrameTag(array('src' => '4.html'))); - - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/2.html'), - 2 => new SimpleUrl('http://here/3.html'))); - } - - function testNamedFramesInPage() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://here')); - - $page = &new SimplePage($response); - $page->acceptFramesetStart(new SimpleTag('frameset', array())); - $page->acceptFrame(new SimpleFrameTag(array('src' => '1.html'))); - $page->acceptFrame(new SimpleFrameTag(array('src' => '2.html', 'name' => 'A'))); - $page->acceptFrame(new SimpleFrameTag(array('src' => '3.html', 'name' => 'B'))); - $page->acceptFrame(new SimpleFrameTag(array('src' => '4.html'))); - $page->acceptFramesetEnd(); - - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/1.html'), - 'A' => new SimpleUrl('http://here/2.html'), - 'B' => new SimpleUrl('http://here/3.html'), - 4 => new SimpleUrl('http://here/4.html'))); - } - - function testRelativeFramesRespectBaseTag() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', new SimpleUrl('http://here.com/')); - $page = &new SimplePage($response); - - $base = &new SimpleBaseTag(array('href' => 'https://there.com/stuff/')); - $page->AcceptTag($base); - - $page->acceptFramesetStart(new SimpleTag('frameset', array())); - $page->acceptFrame(new SimpleFrameTag(array('src' => '1.html'))); - $page->acceptFramesetEnd(); - $this->assertIdentical( - $page->getFrameset(), - array(1 => new SimpleUrl('https://there.com/stuff/1.html'))); - } -} - -class TestOfFormsCreatedFromEventStream extends UnitTestCase { - - function testFormCanBeSubmitted() { - $page = &new SimplePage(new MockSimpleHttpResponse()); - $page->acceptFormStart( - new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php'))); - $page->AcceptTag( - new SimpleSubmitTag(array('type' => 'submit', 'name' => 's'))); - $page->acceptFormEnd(); - $form = &$page->getFormBySubmit(new SimpleByLabel('Submit')); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('s' => 'Submit'))); - } - - function testInputFieldCanBeReadBack() { - $page = &new SimplePage(new MockSimpleHttpResponse()); - $page->acceptFormStart( - new SimpleFormTag(array("method" => "GET", "action" => "here.php"))); - $page->AcceptTag( - new SimpleTextTag(array("type" => "text", "name" => "a", "value" => "A"))); - $page->AcceptTag( - new SimpleSubmitTag(array("type" => "submit", "name" => "s"))); - $page->acceptFormEnd(); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - } - - function testInputFieldCanBeReadBackByLabel() { - $label = &new SimpleLabelTag(array()); - $page = &new SimplePage(new MockSimpleHttpResponse()); - $page->acceptFormStart( - new SimpleFormTag(array("method" => "GET", "action" => "here.php"))); - $page->acceptLabelStart($label); - $label->addContent('l'); - $page->AcceptTag( - new SimpleTextTag(array("type" => "text", "name" => "a", "value" => "A"))); - $page->acceptLabelEnd(); - $page->AcceptTag( - new SimpleSubmitTag(array("type" => "submit", "name" => "s"))); - $page->acceptFormEnd(); - $this->assertEqual($page->getField(new SimpleByLabel('l')), 'A'); - } -} - -class TestOfPageScraping extends UnitTestCase { - - function &parse($response) { - $builder = &new SimplePageBuilder(); - $page = &$builder->parse($response); - return $page; - } - - function testEmptyPage() { - $page = &new SimplePage(new MockSimpleHttpResponse()); - $this->assertIdentical($page->getUrls(), array()); - $this->assertIdentical($page->getTitle(), false); - } - - function testUninterestingPage() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', '

Stuff

'); - $page = &$this->parse($response); - $this->assertIdentical($page->getUrls(), array()); - } - - function testLinksPage() { - $raw = ''; - $raw .= '
There'; - $raw .= 'That page'; - $raw .= ''; - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $raw); - $response->setReturnValue('getUrl', new SimpleUrl('http://www.here.com/a/index.html')); - - $page = &$this->parse($response); - $this->assertIdentical( - $page->getUrls(), - array('http://www.here.com/a/there.html', 'http://there.com/that.html')); - $this->assertIdentical( - $page->getUrlsByLabel('There'), - array(new SimpleUrl('http://www.here.com/a/there.html'))); - $this->assertEqual( - $page->getUrlById('0'), - new SimpleUrl('http://there.com/that.html')); - } - - function testTitle() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', 'Me'); - $page = &$this->parse($response); - $this->assertEqual($page->getTitle(), 'Me'); - } - - function testNastyTitle() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue( - 'getContent', - ' <b>Me&Me '); - $page = &$this->parse($response); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testCompleteForm() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testUnclosedForm() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - ''); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testEmptyFrameset() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue( - 'getContent', - ''); - $page = &$this->parse($response); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array()); - } - - function testSingleFrame() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue( - 'getContent', - ''); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - - $page = &$this->parse($response); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical( - $page->getFrameset(), - array(1 => new SimpleUrl('http://host/a.html'))); - } - - function testSingleFrameInNestedFrameset() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '' . - '' . - ''); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - - $page = &$this->parse($response); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical( - $page->getFrameset(), - array(1 => new SimpleUrl('http://host/a.html'))); - } - - function testFrameWithNoSource() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue( - 'getContent', - ''); - $page = &$this->parse($response); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array()); - } - - function testFramesCollectedWithNestedFramesetTags() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '' . - '' . - '' . - '' . - ''); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - - $page = &$this->parse($response); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - 2 => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'))); - } - - function testNamedFrames() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '' . - '' . - '' . - '' . - '' . - ''); - $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); - - $page = &$this->parse($response); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - '_one' => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'), - '_two' => new SimpleUrl('http://host/d.html'))); - } - - function testFindFormByLabel() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue( - 'getContent', - '
'); - $page = &$this->parse($response); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('submit'))); - $this->assertNull($page->getFormBySubmit(new SimpleByName('submit'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('Submit')), - 'SimpleForm'); - } - - function testConfirmSubmitAttributesAreCaseSensitive() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue( - 'getContent', - '
'); - $page = &$this->parse($response); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('S')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('S')), - 'SimpleForm'); - } - - function testFindFormByImage() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertIsA( - $page->getFormByImage(new SimpleByLabel('Label')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleByName('me')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleById(100)), - 'SimpleForm'); - } - - function testFindFormByButtonTag() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('b'))); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('B'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('b')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('BBB')), - 'SimpleForm'); - } - - function testFindFormById() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue( - 'getContent', - '
'); - $page = &$this->parse($response); - $this->assertNull($page->getFormById(54)); - $this->assertIsA($page->getFormById(55), 'SimpleForm'); - } - - function testReadingTextField() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testReadingTextFieldIsCaseInsensitive() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testSettingTextField() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - $this->assertTrue($page->setField(new SimpleById(3), 'bbb')); - $this->assertEqual($page->getField(new SimpleBYId(3)), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('z'), 'zzz')); - $this->assertNull($page->getField(new SimpleByName('z'))); - } - - function testSettingTextFieldByEnclosingLabel() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByName('b')), 'B'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - } - - function testSettingTextFieldByExternalLabel() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testReadingTextArea() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testSettingTextArea() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertTrue($page->setField(new SimpleByName('a'), 'AAA')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'AAA'); - } - - function testSettingSelectionField() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByName('a')), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('a'), 'ccc')); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testSettingSelectionFieldByEnclosingLabel() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'B')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'B'); - } - - function testSettingRadioButtonByEnclosingLabel() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', - '
' . - '' . - '' . - '
'); - $page = &$this->parse($response); - $this->assertEqual($page->getField(new SimpleByLabel('A')), 'a'); - $this->assertTrue($page->setField(new SimpleBylabel('B'), 'b')); - $this->assertEqual($page->getField(new SimpleByLabel('B')), 'b'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/parse_error_test.php b/tests/simpletest/test/parse_error_test.php deleted file mode 100644 index c3ffb3d42..000000000 --- a/tests/simpletest/test/parse_error_test.php +++ /dev/null @@ -1,9 +0,0 @@ -addFile('test_with_parse_error.php'); -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/tests/simpletest/test/parser_test.php b/tests/simpletest/test/parser_test.php deleted file mode 100644 index 83268d9e1..000000000 --- a/tests/simpletest/test/parser_test.php +++ /dev/null @@ -1,551 +0,0 @@ -assertFalse($regex->match("Hello", $match)); - $this->assertEqual($match, ""); - } - - function testNoSubject() { - $regex = &new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("", $match)); - $this->assertEqual($match, ""); - } - - function testMatchAll() { - $regex = &new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("Hello", $match)); - $this->assertEqual($match, "Hello"); - } - - function testCaseSensitive() { - $regex = &new ParallelRegex(true); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "abc"); - } - - function testCaseInsensitive() { - $regex = &new ParallelRegex(false); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - } - - function testMatchMultiple() { - $regex = &new ParallelRegex(true); - $regex->addPattern("abc"); - $regex->addPattern("ABC"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - $this->assertFalse($regex->match("Hello", $match)); - } - - function testPatternLabels() { - $regex = &new ParallelRegex(false); - $regex->addPattern("abc", "letter"); - $regex->addPattern("123", "number"); - $this->assertIdentical($regex->match("abcdef", $match), "letter"); - $this->assertEqual($match, "abc"); - $this->assertIdentical($regex->match("0123456789", $match), "number"); - $this->assertEqual($match, "123"); - } -} - -class TestOfStateStack extends UnitTestCase { - - function testStartState() { - $stack = &new SimpleStateStack("one"); - $this->assertEqual($stack->getCurrent(), "one"); - } - - function testExhaustion() { - $stack = &new SimpleStateStack("one"); - $this->assertFalse($stack->leave()); - } - - function testStateMoves() { - $stack = &new SimpleStateStack("one"); - $stack->enter("two"); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("three"); - $this->assertEqual($stack->getCurrent(), "three"); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("third"); - $this->assertEqual($stack->getCurrent(), "third"); - $this->assertTrue($stack->leave()); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "one"); - } -} - -class TestParser { - - function accept() { - } - - function a() { - } - - function b() { - } -} -Mock::generate('TestParser'); - -class TestOfLexer extends UnitTestCase { - - function testEmptyPage() { - $handler = &new MockTestParser(); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $lexer = &new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("")); - } - - function testSinglePattern() { - $handler = &new MockTestParser(); - $handler->expectArgumentsAt(0, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectArgumentsAt(1, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(2, "accept", array("a", LEXER_MATCHED)); - $handler->expectArgumentsAt(3, "accept", array("yyy", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(4, "accept", array("a", LEXER_MATCHED)); - $handler->expectArgumentsAt(5, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(6, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectArgumentsAt(7, "accept", array("z", LEXER_UNMATCHED)); - $handler->expectCallCount("accept", 8); - $handler->setReturnValue("accept", true); - $lexer = &new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); - } - - function testMultiplePattern() { - $handler = &new MockTestParser(); - $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); - for ($i = 0; $i < count($target); $i++) { - $handler->expectArgumentsAt($i, "accept", array($target[$i], '*')); - } - $handler->expectCallCount("accept", count($target)); - $handler->setReturnValue("accept", true); - $lexer = &new SimpleLexer($handler); - $lexer->addPattern("a+"); - $lexer->addPattern("b+"); - $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); - } -} - -class TestOfLexerModes extends UnitTestCase { - - function testIsolatedPattern() { - $handler = &new MockTestParser(); - $handler->expectArgumentsAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectArgumentsAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(3, "a", array("bxb", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectArgumentsAt(5, "a", array("x", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(6, "a", array("aaaa", LEXER_MATCHED)); - $handler->expectArgumentsAt(7, "a", array("x", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 8); - $handler->setReturnValue("a", true); - $lexer = &new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); - } - - function testModeChange() { - $handler = &new MockTestParser(); - $handler->expectArgumentsAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectArgumentsAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectArgumentsAt(0, "b", array(":", LEXER_ENTER)); - $handler->expectArgumentsAt(1, "b", array("a", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(2, "b", array("b", LEXER_MATCHED)); - $handler->expectArgumentsAt(3, "b", array("a", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(4, "b", array("bb", LEXER_MATCHED)); - $handler->expectArgumentsAt(5, "b", array("a", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(6, "b", array("bbb", LEXER_MATCHED)); - $handler->expectArgumentsAt(7, "b", array("a", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 5); - $handler->expectCallCount("b", 8); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $lexer = &new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern(":", "a", "b"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); - } - - function testNesting() { - $handler = &new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(0, "b", array("(", LEXER_ENTER)); - $handler->expectArgumentsAt(1, "b", array("bb", LEXER_MATCHED)); - $handler->expectArgumentsAt(2, "b", array("a", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(3, "b", array("bb", LEXER_MATCHED)); - $handler->expectArgumentsAt(4, "b", array(")", LEXER_EXIT)); - $handler->expectArgumentsAt(4, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(5, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 6); - $handler->expectCallCount("b", 5); - $lexer = &new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern("(", "a", "b"); - $lexer->addPattern("b+", "b"); - $lexer->addExitPattern(")", "b"); - $this->assertTrue($lexer->parse("aabaab(bbabb)aab")); - } - - function testSingular() { - $handler = &new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(1, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(2, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(3, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(0, "b", array("b", LEXER_SPECIAL)); - $handler->expectArgumentsAt(1, "b", array("bbb", LEXER_SPECIAL)); - $handler->expectCallCount("a", 4); - $handler->expectCallCount("b", 2); - $lexer = &new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addSpecialPattern("b+", "a", "b"); - $this->assertTrue($lexer->parse("aabaaxxbbbxx")); - } - - function testUnwindTooFar() { - $handler = &new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(1, "a", array(")", LEXER_EXIT)); - $handler->expectCallCount("a", 2); - $lexer = &new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addExitPattern(")", "a"); - $this->assertFalse($lexer->parse("aa)aa")); - } -} - -class TestOfLexerHandlers extends UnitTestCase { - - function testModeMapping() { - $handler = &new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectArgumentsAt(1, "a", array("(", LEXER_ENTER)); - $handler->expectArgumentsAt(2, "a", array("bb", LEXER_MATCHED)); - $handler->expectArgumentsAt(3, "a", array("a", LEXER_UNMATCHED)); - $handler->expectArgumentsAt(4, "a", array("bb", LEXER_MATCHED)); - $handler->expectArgumentsAt(5, "a", array(")", LEXER_EXIT)); - $handler->expectArgumentsAt(6, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 7); - $lexer = &new SimpleLexer($handler, "mode_a"); - $lexer->addPattern("a+", "mode_a"); - $lexer->addEntryPattern("(", "mode_a", "mode_b"); - $lexer->addPattern("b+", "mode_b"); - $lexer->addExitPattern(")", "mode_b"); - $lexer->mapHandler("mode_a", "a"); - $lexer->mapHandler("mode_b", "a"); - $this->assertTrue($lexer->parse("aa(bbabb)b")); - } -} - -class TestOfSimpleHtmlLexer extends UnitTestCase { - - function &createParser() { - $parser = &new MockSimpleHtmlSaxParser(); - $parser->setReturnValue('acceptStartToken', true); - $parser->setReturnValue('acceptEndToken', true); - $parser->setReturnValue('acceptAttributeToken', true); - $parser->setReturnValue('acceptEntityToken', true); - $parser->setReturnValue('acceptTextToken', true); - $parser->setReturnValue('ignore', true); - return $parser; - } - - function testNoContent() { - $parser = &$this->createParser(); - $parser->expectNever('acceptStartToken'); - $parser->expectNever('acceptEndToken'); - $parser->expectNever('acceptAttributeToken'); - $parser->expectNever('acceptEntityToken'); - $parser->expectNever('acceptTextToken'); - $lexer = &new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testUninteresting() { - $parser = &$this->createParser(); - $parser->expectOnce('acceptTextToken', array('', '*')); - $lexer = &new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testSkipCss() { - $parser = &$this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = &new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipJavaScript() { - $parser = &$this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = &new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipHtmlComments() { - $parser = &$this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = &new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testTagWithNoAttributes() { - $parser = &$this->createParser(); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 2); - $parser->expectOnce('acceptTextToken', array('Hello', '*')); - $parser->expectOnce('acceptEndToken', array('', '*')); - $lexer = &new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('Hello')); - } - - function testTagWithAttributes() { - $parser = &$this->createParser(); - $parser->expectOnce('acceptTextToken', array('label', '*')); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('href', '*')); - $parser->expectAt(2, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 3); - $parser->expectAt(0, 'acceptAttributeToken', array('= "', '*')); - $parser->expectAt(1, 'acceptAttributeToken', array('here.html', '*')); - $parser->expectAt(2, 'acceptAttributeToken', array('"', '*')); - $parser->expectCallCount('acceptAttributeToken', 3); - $parser->expectOnce('acceptEndToken', array('', '*')); - $lexer = &new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('label')); - } -} - -class TestOfHtmlSaxParser extends UnitTestCase { - - function &createListener() { - $listener = &new MockSimpleSaxListener(); - $listener->setReturnValue('startElement', true); - $listener->setReturnValue('addContent', true); - $listener->setReturnValue('endElement', true); - return $listener; - } - - function testFramesetTag() { - $listener = &$this->createListener(); - $listener->expectOnce('startElement', array('frameset', array())); - $listener->expectOnce('addContent', array('Frames')); - $listener->expectOnce('endElement', array('frameset')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('Frames')); - } - - function testTagWithUnquotedAttributes() { - $listener = &$this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('name' => 'a.b.c', 'value' => 'd'))); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagInsideContent() { - $listener = &$this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectAt(0, 'addContent', array('')); - $listener->expectAt(1, 'addContent', array('')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagWithInternalContent() { - $listener = &$this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testLinkAddress() { - $listener = &$this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testEncodedAttribute() { - $listener = &$this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here&there.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testTagWithId() { - $listener = &$this->createListener(); - $listener->expectOnce('startElement', array('a', array('id' => '0'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testTagWithEmptyAttributes() { - $listener = &$this->createListener(); - $listener->expectOnce( - 'startElement', - array('option', array('value' => '', 'selected' => ''))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('option')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testComplexTagWithLotsOfCaseVariations() { - $listener = &$this->createListener(); - $listener->expectOnce( - 'startElement', - array('a', array('href' => 'here.html', 'style' => "'cool'"))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testXhtmlSelfClosingTag() { - $listener = &$this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('type' => 'submit', 'name' => 'N', 'value' => 'V'))); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testNestedFrameInFrameset() { - $listener = &$this->createListener(); - $listener->expectAt(0, 'startElement', array('frameset', array())); - $listener->expectAt(1, 'startElement', array('frame', array('src' => 'frame.html'))); - $listener->expectCallCount('startElement', 2); - $listener->expectOnce('addContent', array('Hello')); - $listener->expectOnce('endElement', array('frameset')); - $parser = &new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse( - 'Hello')); - } -} - -class TestOfTextExtraction extends UnitTestCase { - - function testImageSuppressionWhileKeepingParagraphsAndAltText() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise('

some text

bar'), - 'some text bar'); - - } - - function testSpaceNormalisation() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise("\nOne\tTwo \nThree\t"), - 'One Two Three'); - } - - function testMultilinesCommentSuppression() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise(''), - ''); - } - - function testCommentSuppression() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise(''), - ''); - } - - function testJavascriptSuppression() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise(''), - ''); - $this->assertEqual( - SimpleHtmlSaxParser::normalise(''), - ''); - $this->assertEqual( - SimpleHtmlSaxParser::normalise(''), - ''); - } - - function testTagSuppression() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise('Hello'), - 'Hello'); - } - - function testAdjoiningTagSuppression() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise('HelloGoodbye'), - 'HelloGoodbye'); - } - - function testExtractImageAltTextWithDifferentQuotes() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise('One\'Two\'Three'), - 'One Two Three'); - } - - function testExtractImageAltTextMultipleTimes() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise('OneTwoThree'), - 'One Two Three'); - } - - function testHtmlEntityTranslation() { - $this->assertEqual( - SimpleHtmlSaxParser::normalise('<>"&''), - '<>"&\''); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/reflection_php4_test.php b/tests/simpletest/test/reflection_php4_test.php deleted file mode 100644 index 8ee211b96..000000000 --- a/tests/simpletest/test/reflection_php4_test.php +++ /dev/null @@ -1,61 +0,0 @@ -assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testClassNonExistence() { - $reflection = new SimpleReflection('UnknownThing'); - $this->assertFalse($reflection->classOrInterfaceExists()); - $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testDetectionOfInterfacesAlwaysFalse() { - $reflection = new SimpleReflection('AnyOldThing'); - $this->assertFalse($reflection->isAbstract()); - $this->assertFalse($reflection->isInterface()); - } - - function testFindingParentClass() { - $reflection = new SimpleReflection('AnyOldChildThing'); - $this->assertEqual(strtolower($reflection->getParent()), 'anyoldthing'); - } - - function testMethodsListFromClass() { - $reflection = new SimpleReflection('AnyOldThing'); - $methods = $reflection->getMethods(); - $this->assertEqualIgnoringCase($methods[0], 'aMethod'); - } - - function testNoInterfacesForPHP4() { - $reflection = new SimpleReflection('AnyOldThing'); - $this->assertEqual( - $reflection->getInterfaces(), - array()); - } - - function testMostGeneralPossibleSignature() { - $reflection = new SimpleReflection('AnyOldThing'); - $this->assertEqualIgnoringCase( - $reflection->getSignature('aMethod'), - 'function &aMethod()'); - } - - function assertEqualIgnoringCase($a, $b) { - return $this->assertEqual(strtolower($a), strtolower($b)); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/reflection_php5_test.php b/tests/simpletest/test/reflection_php5_test.php deleted file mode 100644 index 3bfc6e85b..000000000 --- a/tests/simpletest/test/reflection_php5_test.php +++ /dev/null @@ -1,271 +0,0 @@ -assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertFalse($reflection->isAbstract()); - $this->assertFalse($reflection->isInterface()); - } - - function testClassNonExistence() { - $reflection = new SimpleReflection('UnknownThing'); - $this->assertFalse($reflection->classOrInterfaceExists()); - $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testDetectionOfAbstractClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertTrue($reflection->isAbstract()); - } - - function testDetectionOfFinalMethods() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertFalse($reflection->hasFinal()); - $reflection = new SimpleReflection('AnyOldLeafClassWithAFinal'); - $this->assertTrue($reflection->hasFinal()); - } - - function testFindingParentClass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual($reflection->getParent(), 'AnyOldImplementation'); - } - - function testInterfaceExistence() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertTrue($reflection->isInterface()); - } - - function testMethodsListFromClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testMethodsListFromInterface() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesASWell() { - $reflection = new SimpleReflection('AnyDescendentInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testCanSeparateInterfaceMethodsFromOthers() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesInAbstractClass() { - $reflection = new SimpleReflection('AnyAbstractImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testInterfaceHasOnlyItselfToImplement() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForClass() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForSubclass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testNoParameterCreationWhenNoInterface() { - $reflection = new SimpleReflection('AnyOldArgumentClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod()', strtolower($function)); - } else { - $this->assertEqual('function aMethod()', $function); - } - } - - function testParameterCreationWithoutTypeHinting() { - $reflection = new SimpleReflection('AnyOldArgumentImplementation'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testParameterCreationForTypeHinting() { - $reflection = new SimpleReflection('AnyOldTypeHintedClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testIssetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__isset'); - if (version_compare(phpversion(), '5.1.0', '>=')) { - $this->assertEqual('function __isset($key)', $function); - } else { - $this->assertEqual('function __isset()', $function); - } - } - - function testUnsetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__unset'); - if (version_compare(phpversion(), '5.1.0', '>=')) { - $this->assertEqual('function __unset($key)', $function); - } else { - $this->assertEqual('function __unset()', $function); - } - } - - function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() { - $reflection = new SimpleReflection('AnyDescendentImplementation'); - $interfaces = $reflection->getInterfaces(); - $this->assertEqual(1, count($interfaces)); - $this->assertEqual('AnyDescendentInterface', array_shift($interfaces)); - } - - function testCreatingSignatureForAbstractMethod() { - $reflection = new SimpleReflection('AnotherOldAbstractClass'); - $this->assertEqual($reflection->getSignature('aMethod'), 'function aMethod(AnyOldInterface $argument)'); - } - - function testCanProperlyGenerateStaticMethodSignatures() { - $reflection = new SimpleReflection('AnyOldClassWithStaticMethods'); - $this->assertEqual('static function aStatic()', $reflection->getSignature('aStatic')); - $this->assertEqual( - 'static function aStaticWithParameters($arg1, $arg2)', - $reflection->getSignature('aStaticWithParameters') - ); - } -} - -class TestOfReflectionWithTypeHints extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1.0', '<'), 'Reflection with type hints only tested for PHP 5.1.0 and above'); - } - - function testParameterCreationForTypeHintingWithArray() { - eval('interface AnyOldArrayTypeHintedInterface { - function amethod(array $argument); - } - class AnyOldArrayTypeHintedClass implements AnyOldArrayTypeHintedInterface { - function amethod(array $argument) {} - }'); - $reflection = new SimpleReflection('AnyOldArrayTypeHintedClass'); - $function = $reflection->getSignature('amethod'); - $this->assertEqual('function amethod(array $argument)', $function); - } -} - -class TestOfAbstractsWithAbstractMethods extends UnitTestCase { - function testCanProperlyGenerateAbstractMethods() { - $reflection = new SimpleReflection('AnyOldAbstractClassWithAbstractMethods'); - $this->assertEqual( - 'function anAbstract()', - $reflection->getSignature('anAbstract') - ); - $this->assertEqual( - 'function anAbstractWithParameter($foo)', - $reflection->getSignature('anAbstractWithParameter') - ); - $this->assertEqual( - 'function anAbstractWithMultipleParameters($foo, $bar)', - $reflection->getSignature('anAbstractWithMultipleParameters') - ); - } -} - -?> \ No newline at end of file diff --git a/tests/simpletest/test/remote_test.php b/tests/simpletest/test/remote_test.php deleted file mode 100644 index efcccaf05..000000000 --- a/tests/simpletest/test/remote_test.php +++ /dev/null @@ -1,20 +0,0 @@ -addTestCase(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes')); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/tests/simpletest/test/shell_test.php b/tests/simpletest/test/shell_test.php deleted file mode 100644 index 6199272a1..000000000 --- a/tests/simpletest/test/shell_test.php +++ /dev/null @@ -1,38 +0,0 @@ -assertIdentical($shell->execute('echo Hello'), 0); - $this->assertPattern('/Hello/', $shell->getOutput()); - } - - function testBadCommand() { - $shell = &new SimpleShell(); - $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0); - } -} - -class TestOfShellTesterAndShell extends ShellTestCase { - - function testEcho() { - $this->assertTrue($this->execute('echo Hello')); - $this->assertExitCode(0); - $this->assertoutput('Hello'); - } - - function testFileExistence() { - $this->assertFileExists(dirname(__FILE__) . '/all_tests.php'); - $this->assertFileNotExists('wibble'); - } - - function testFilePatterns() { - $this->assertFilePattern('/all[_ ]tests/i', dirname(__FILE__) . '/all_tests.php'); - $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/shell_tester_test.php b/tests/simpletest/test/shell_tester_test.php deleted file mode 100644 index e536dcebd..000000000 --- a/tests/simpletest/test/shell_tester_test.php +++ /dev/null @@ -1,42 +0,0 @@ -_mock_shell; - } - - function testGenericEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } - - function testExitCode() { - $this->_mock_shell = &new MockSimpleShell(); - $this->_mock_shell->setReturnValue('execute', 0); - $this->_mock_shell->expectOnce('execute', array('ls')); - $this->assertTrue($this->execute('ls')); - $this->assertExitCode(0); - } - - function testOutput() { - $this->_mock_shell = &new MockSimpleShell(); - $this->_mock_shell->setReturnValue('execute', 0); - $this->_mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutput("Line 1\nLine 2\n"); - } - - function testOutputPatterns() { - $this->_mock_shell = &new MockSimpleShell(); - $this->_mock_shell->setReturnValue('execute', 0); - $this->_mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutputPattern('/line/i'); - $this->assertNoOutputPattern('/line 2/'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/simpletest_test.php b/tests/simpletest/test/simpletest_test.php deleted file mode 100644 index bf98d9748..000000000 --- a/tests/simpletest/test/simpletest_test.php +++ /dev/null @@ -1,58 +0,0 @@ -fail('Should be ignored'); - } -} - -class ShouldNeverBeRunEither extends ShouldNeverBeRun { } - -class TestOfStackTrace extends UnitTestCase { - - function testCanFindAssertInTrace() { - $trace = new SimpleStackTrace(array('assert')); - $this->assertEqual( - $trace->traceMethod(array(array( - 'file' => '/my_test.php', - 'line' => 24, - 'function' => 'assertSomething'))), - ' at [/my_test.php line 24]'); - } -} - -class DummyResource { } - -class TestOfContext extends UnitTestCase { - - function testCurrentContextIsUnique() { - $this->assertReference( - SimpleTest::getContext(), - SimpleTest::getContext()); - } - - function testContextHoldsCurrentTestCase() { - $context = &SimpleTest::getContext(); - $this->assertReference($this, $context->getTest()); - } - - function testResourceIsSingleInstanceWithContext() { - $context = &new SimpleTestContext(); - $this->assertReference( - $context->get('DummyResource'), - $context->get('DummyResource')); - } - - function testClearingContextResetsResources() { - $context = &new SimpleTestContext(); - $resource = &$context->get('DummyResource'); - $context->clear(); - $this->assertClone($resource, $context->get('DummyResource')); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/socket_test.php b/tests/simpletest/test/socket_test.php deleted file mode 100644 index ce25be7d3..000000000 --- a/tests/simpletest/test/socket_test.php +++ /dev/null @@ -1,25 +0,0 @@ -assertFalse($error->isError()); - $error->_setError('Ouch'); - $this->assertTrue($error->isError()); - $this->assertEqual($error->getError(), 'Ouch'); - } - - function testClearingError() { - $error = new SimpleStickyError(); - $error->_setError('Ouch'); - $this->assertTrue($error->isError()); - $error->_clearError(); - $this->assertFalse($error->isError()); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/support/collector/collectable.1 b/tests/simpletest/test/support/collector/collectable.1 deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/simpletest/test/support/collector/collectable.2 b/tests/simpletest/test/support/collector/collectable.2 deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/simpletest/test/support/empty_test_file.php b/tests/simpletest/test/support/empty_test_file.php deleted file mode 100644 index 31e3f7bed..000000000 --- a/tests/simpletest/test/support/empty_test_file.php +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/tests/simpletest/test/support/latin1_sample b/tests/simpletest/test/support/latin1_sample deleted file mode 100644 index 190352577..000000000 --- a/tests/simpletest/test/support/latin1_sample +++ /dev/null @@ -1 +0,0 @@ -£¹²³¼½¾@¶øþðßæ«»¢µ \ No newline at end of file diff --git a/tests/simpletest/test/support/spl_examples.php b/tests/simpletest/test/support/spl_examples.php deleted file mode 100644 index 45add356c..000000000 --- a/tests/simpletest/test/support/spl_examples.php +++ /dev/null @@ -1,15 +0,0 @@ - \ No newline at end of file diff --git a/tests/simpletest/test/support/supplementary_upload_sample.txt b/tests/simpletest/test/support/supplementary_upload_sample.txt deleted file mode 100644 index d8aa9e810..000000000 --- a/tests/simpletest/test/support/supplementary_upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Some more text content \ No newline at end of file diff --git a/tests/simpletest/test/support/test1.php b/tests/simpletest/test/support/test1.php deleted file mode 100644 index b414586d6..000000000 --- a/tests/simpletest/test/support/test1.php +++ /dev/null @@ -1,7 +0,0 @@ -assertEqual(3,1+2, "pass1"); - } -} -?> diff --git a/tests/simpletest/test/support/upload_sample.txt b/tests/simpletest/test/support/upload_sample.txt deleted file mode 100644 index ec98d7c5e..000000000 --- a/tests/simpletest/test/support/upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Sample for testing file upload \ No newline at end of file diff --git a/tests/simpletest/test/tag_test.php b/tests/simpletest/test/tag_test.php deleted file mode 100644 index f81df64ea..000000000 --- a/tests/simpletest/test/tag_test.php +++ /dev/null @@ -1,554 +0,0 @@ - '1', 'b' => '')); - $this->assertEqual($tag->getTagName(), 'title'); - $this->assertIdentical($tag->getAttribute('a'), '1'); - $this->assertIdentical($tag->getAttribute('b'), ''); - $this->assertIdentical($tag->getAttribute('c'), false); - $this->assertIdentical($tag->getContent(), ''); - } - - function testTitleContent() { - $tag = &new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testMessyTitleContent() { - $tag = &new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testTagWithNoEnd() { - $tag = &new SimpleTextTag(array()); - $this->assertFalse($tag->expectEndTag()); - } - - function testAnchorHref() { - $tag = &new SimpleAnchorTag(array('href' => 'http://here/')); - $this->assertEqual($tag->getHref(), 'http://here/'); - - $tag = &new SimpleAnchorTag(array('href' => '')); - $this->assertIdentical($tag->getAttribute('href'), ''); - $this->assertIdentical($tag->getHref(), ''); - - $tag = &new SimpleAnchorTag(array()); - $this->assertIdentical($tag->getAttribute('href'), false); - $this->assertIdentical($tag->getHref(), ''); - } - - function testIsIdMatchesIdAttribute() { - $tag = &new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7)); - $this->assertIdentical($tag->getAttribute('id'), '7'); - $this->assertTrue($tag->isId(7)); - } -} - -class TestOfWidget extends UnitTestCase { - - function testTextEmptyDefault() { - $tag = &new SimpleTextTag(array('type' => 'text')); - $this->assertIdentical($tag->getDefault(), ''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSettingOfExternalLabel() { - $tag = &new SimpleTextTag(array('type' => 'text')); - $tag->setLabel('it'); - $this->assertTrue($tag->isLabel('it')); - } - - function testTextDefault() { - $tag = &new SimpleTextTag(array('value' => 'aaa')); - $this->assertEqual($tag->getDefault(), 'aaa'); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSettingTextValue() { - $tag = &new SimpleTextTag(array('value' => 'aaa')); - $tag->setValue('bbb'); - $this->assertEqual($tag->getValue(), 'bbb'); - $tag->resetValue(); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testFailToSetHiddenValue() { - $tag = &new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden')); - $this->assertFalse($tag->setValue('bbb')); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSubmitDefaults() { - $tag = &new SimpleSubmitTag(array('type' => 'submit')); - $this->assertIdentical($tag->getName(), false); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertFalse($tag->setValue('Cannot set this')); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertEqual($tag->getLabel(), 'Submit'); - - $encoding = &new MockSimpleMultipartEncoding(); - $encoding->expectNever('add'); - $tag->write($encoding); - } - - function testPopulatedSubmit() { - $tag = &new SimpleSubmitTag( - array('type' => 'submit', 'name' => 's', 'value' => 'Ok!')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'Ok!'); - $this->assertEqual($tag->getLabel(), 'Ok!'); - - $encoding = &new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'Ok!')); - $tag->write($encoding); - } - - function testImageSubmit() { - $tag = &new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getLabel(), 'Label'); - - $encoding = &new MockSimpleMultipartEncoding(); - $encoding->expectAt(0, 'add', array('s.x', 20)); - $encoding->expectAt(1, 'add', array('s.y', 30)); - $tag->write($encoding, 20, 30); - } - - function testImageSubmitTitlePreferredOverAltForLabel() { - $tag = &new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title')); - $this->assertEqual($tag->getLabel(), 'Title'); - } - - function testButton() { - $tag = &new SimpleButtonTag( - array('type' => 'submit', 'name' => 's', 'value' => 'do')); - $tag->addContent('I am a button'); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'do'); - $this->assertEqual($tag->getLabel(), 'I am a button'); - - $encoding = &new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'do')); - $tag->write($encoding); - } -} - -class TestOfTextArea extends UnitTestCase { - - function testDefault() { - $tag = &new SimpleTextAreaTag(array('name' => 'a')); - $tag->addContent('Some text'); - $this->assertEqual($tag->getName(), 'a'); - $this->assertEqual($tag->getDefault(), 'Some text'); - } - - function testWrapping() { - $tag = &new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical')); - $tag->addContent("Lot's of text that should be wrapped"); - $this->assertEqual( - $tag->getDefault(), - "Lot's of\r\ntext that\r\nshould be\r\nwrapped"); - $tag->setValue("New long text\r\nwith two lines"); - $this->assertEqual( - $tag->getValue(), - "New long\r\ntext\r\nwith two\r\nlines"); - } - - function testWrappingRemovesLeadingcariageReturn() { - $tag = &new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical')); - $tag->addContent("\rStuff"); - $this->assertEqual($tag->getDefault(), 'Stuff'); - $tag->setValue("\nNew stuff\n"); - $this->assertEqual($tag->getValue(), "New stuff\r\n"); - } - - function testBreaksAreNewlineAndCarriageReturn() { - $tag = &new SimpleTextAreaTag(array('cols' => '10')); - $tag->addContent("Some\nText\rwith\r\nbreaks"); - $this->assertEqual($tag->getValue(), "Some\r\nText\r\nwith\r\nbreaks"); - } -} - -class TestOfCheckbox extends UnitTestCase { - - function testCanSetCheckboxToNamedValueWithBooleanTrue() { - $tag = &new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A')); - $this->assertEqual($tag->getValue(), false); - $tag->setValue(true); - $this->assertIdentical($tag->getValue(), 'A'); - } -} - -class TestOfSelection extends UnitTestCase { - - function testEmpty() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSingle() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $option = &new SimpleOptionTag(array()); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleDefault() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $option = &new SimpleOptionTag(array('selected' => '')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleMappedDefault() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $option = &new SimpleOptionTag(array('selected' => '', 'value' => 'aaa')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testStartsWithDefault() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $a = &new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = &new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testSettingOption() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $a = &new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = &new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSettingMappedOption() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $a = &new SimpleOptionTag(array('value' => 'aaa')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array('value' => 'bbb', 'selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = &new SimpleOptionTag(array('value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'aaa'); - $tag->setValue('ccc'); - $this->assertEqual($tag->getValue(), 'ccc'); - } - - function testSelectionDespiteSpuriousWhitespace() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $a = &new SimpleOptionTag(array()); - $a->addContent(' AAA '); - $tag->addTag($a); - $b = &new SimpleOptionTag(array('selected' => '')); - $b->addContent(' BBB '); - $tag->addTag($b); - $c = &new SimpleOptionTag(array()); - $c->addContent(' CCC '); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), ' BBB '); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), ' AAA '); - } - - function testFailToSetIllegalOption() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $a = &new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = &new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertFalse($tag->setValue('Not present')); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testNastyOptionValuesThatLookLikeFalse() { - $tag = &new SimpleSelectionTag(array('name' => 'a')); - $a = &new SimpleOptionTag(array('value' => '1')); - $a->addContent('One'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array('value' => '0')); - $b->addContent('Zero'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), '1'); - $tag->setValue('Zero'); - $this->assertIdentical($tag->getValue(), '0'); - } - - function testBlankOption() { - $tag = &new SimpleSelectionTag(array('name' => 'A')); - $a = &new SimpleOptionTag(array()); - $tag->addTag($a); - $b = &new SimpleOptionTag(array()); - $b->addContent('b'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), ''); - $tag->setValue('b'); - $this->assertIdentical($tag->getValue(), 'b'); - $tag->setValue(''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testMultipleDefaultWithNoSelections() { - $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = &new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array()); - $this->assertIdentical($tag->getValue(), array()); - } - - function testMultipleDefaultWithSelections() { - $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = &new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array('AAA', 'BBB')); - $this->assertIdentical($tag->getValue(), array('AAA', 'BBB')); - } - - function testSettingMultiple() { - $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = &new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $c = &new SimpleOptionTag(array('selected' => '', 'value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertIdentical($tag->getDefault(), array('AAA', 'ccc')); - $this->assertTrue($tag->setValue(array('BBB', 'ccc'))); - $this->assertIdentical($tag->getValue(), array('BBB', 'ccc')); - $this->assertTrue($tag->setValue(array())); - $this->assertIdentical($tag->getValue(), array()); - } - - function testFailToSetIllegalOptionsInMultiple() { - $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = &new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = &new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertFalse($tag->setValue(array('CCC'))); - $this->assertTrue($tag->setValue(array('AAA', 'BBB'))); - $this->assertFalse($tag->setValue(array('AAA', 'CCC'))); - } -} - -class TestOfRadioGroup extends UnitTestCase { - - function testEmptyGroup() { - $group = &new SimpleRadioGroup(); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - $this->assertFalse($group->setValue('a')); - } - - function testReadingSingleButtonGroup() { - $group = &new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'A'); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testReadingMultipleButtonGroup() { - $group = &new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testFailToSetUnlistedValue() { - $group = &new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag(array('value' => 'z'))); - $this->assertFalse($group->setValue('a')); - $this->assertIdentical($group->getValue(), false); - } - - function testSettingNewValueClearsTheOldOne() { - $group = &new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testIsIdMatchesAnyWidgetInSet() { - $group = &new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'id' => 'i1'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'id' => 'i2'))); - $this->assertFalse($group->isId('i0')); - $this->assertTrue($group->isId('i1')); - $this->assertTrue($group->isId('i2')); - } - - function testIsLabelMatchesAnyWidgetInSet() { - $group = &new SimpleRadioGroup(); - $button1 = &new SimpleRadioButtonTag(array('value' => 'A')); - $button1->setLabel('one'); - $group->addWidget($button1); - $button2 = &new SimpleRadioButtonTag(array('value' => 'B')); - $button2->setLabel('two'); - $group->addWidget($button2); - $this->assertFalse($group->isLabel('three')); - $this->assertTrue($group->isLabel('one')); - $this->assertTrue($group->isLabel('two')); - } -} - -class TestOfTagGroup extends UnitTestCase { - - function testReadingMultipleCheckboxGroup() { - $group = &new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testReadingMultipleUncheckedItems() { - $group = &new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - } - - function testReadingMultipleCheckedItems() { - $group = &new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'A', 'checked' => ''))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), array('A', 'B')); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingSingleValue() { - $group = &new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - $this->assertTrue($group->setValue('B')); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testSettingMultipleValues() { - $group = &new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(array('A', 'B'))); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingNoValue() { - $group = &new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(false)); - $this->assertIdentical($group->getValue(), false); - } - - function testIsIdMatchesAnyIdInSet() { - $group = &new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B'))); - $this->assertFalse($group->isId(0)); - $this->assertTrue($group->isId(1)); - $this->assertTrue($group->isId(2)); - } -} - -class TestOfUploadWidget extends UnitTestCase { - - function testValueIsFilePath() { - $upload = &new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt'); - } - - function testSubmitsFileContents() { - $encoding = &new MockSimpleMultipartEncoding(); - $encoding->expectOnce('attach', array( - 'a', - 'Sample for testing file upload', - 'upload_sample.txt')); - $upload = &new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $upload->write($encoding); - } -} - -class TestOfLabelTag extends UnitTestCase { - - function testLabelShouldHaveAnEndTag() { - $label = &new SimpleLabelTag(array()); - $this->assertTrue($label->expectEndTag()); - } - - function testContentIsTextOnly() { - $label = &new SimpleLabelTag(array()); - $label->addContent('Here are words'); - $this->assertEqual($label->getText(), 'Here are words'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/test_with_parse_error.php b/tests/simpletest/test/test_with_parse_error.php deleted file mode 100644 index ca0238b48..000000000 --- a/tests/simpletest/test/test_with_parse_error.php +++ /dev/null @@ -1,8 +0,0 @@ - \ No newline at end of file diff --git a/tests/simpletest/test/unit_tester_test.php b/tests/simpletest/test/unit_tester_test.php deleted file mode 100644 index 5fe78fe91..000000000 --- a/tests/simpletest/test/unit_tester_test.php +++ /dev/null @@ -1,55 +0,0 @@ -assertTrue($this->assertTrue(true)); - } - - function testAssertFalseReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertFalse(false)); - } - - function testAssertEqualReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertEqual(5, 5)); - } - - function testAssertIdenticalReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertIdentical(5, 5)); - } - - function testCoreAssertionsDoNotThrowErrors() { - $this->assertIsA($this, 'UnitTestCase'); - $this->assertNotA($this, 'WebTestCase'); - } - - function testReferenceAssertionOnObjects() { - $a = &new ReferenceForTesting(); - $b = &$a; - $this->assertReference($a, $b); - } - - function testReferenceAssertionOnScalars() { - $a = 25; - $b = &$a; - $this->assertReference($a, $b); - } - - function testCloneOnObjects() { - $a = &new ReferenceForTesting(); - $b = &new ReferenceForTesting(); - $this->assertClone($a, $b); - } - - function testCloneOnScalars() { - $a = 25; - $b = 25; - $this->assertClone($a, $b); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/unit_tests.php b/tests/simpletest/test/unit_tests.php deleted file mode 100644 index 04dbc46ca..000000000 --- a/tests/simpletest/test/unit_tests.php +++ /dev/null @@ -1,55 +0,0 @@ -TestSuite('Unit tests'); - $path = dirname(__FILE__); - $this->addFile($path . '/errors_test.php'); - if (version_compare(phpversion(), '5') >= 0) { - $this->addFile($path . '/exceptions_test.php'); - } - $this->addFile($path . '/autorun_test.php'); - $this->addFile($path . '/compatibility_test.php'); - $this->addFile($path . '/simpletest_test.php'); - $this->addFile($path . '/dumper_test.php'); - $this->addFile($path . '/expectation_test.php'); - $this->addFile($path . '/unit_tester_test.php'); - if (version_compare(phpversion(), '5', '>=')) { - $this->addFile($path . '/reflection_php5_test.php'); - } else { - $this->addFile($path . '/reflection_php4_test.php'); - } - $this->addFile($path . '/mock_objects_test.php'); - if (version_compare(phpversion(), '5', '>=')) { - $this->addFile($path . '/interfaces_test.php'); - } - $this->addFile($path . '/collector_test.php'); - $this->addFile($path . '/adapter_test.php'); - $this->addFile($path . '/socket_test.php'); - $this->addFile($path . '/encoding_test.php'); - $this->addFile($path . '/url_test.php'); - $this->addFile($path . '/cookies_test.php'); - $this->addFile($path . '/http_test.php'); - $this->addFile($path . '/authentication_test.php'); - $this->addFile($path . '/user_agent_test.php'); - $this->addFile($path . '/parser_test.php'); - $this->addFile($path . '/tag_test.php'); - $this->addFile($path . '/form_test.php'); - $this->addFile($path . '/page_test.php'); - $this->addFile($path . '/frames_test.php'); - $this->addFile($path . '/browser_test.php'); - $this->addFile($path . '/web_tester_test.php'); - $this->addFile($path . '/shell_tester_test.php'); - $this->addFile($path . '/xml_test.php'); - $this->addFile($path . '/../extensions/testdox/test.php'); - } -} -?> diff --git a/tests/simpletest/test/url_test.php b/tests/simpletest/test/url_test.php deleted file mode 100644 index 550717038..000000000 --- a/tests/simpletest/test/url_test.php +++ /dev/null @@ -1,443 +0,0 @@ -assertEqual($url->getScheme(), ''); - $this->assertEqual($url->getHost(), ''); - $this->assertEqual($url->getScheme('http'), 'http'); - $this->assertEqual($url->getHost('localhost'), 'localhost'); - $this->assertEqual($url->getPath(), ''); - } - - function testBasicParsing() { - $url = new SimpleUrl('https://www.lastcraft.com/test/'); - $this->assertEqual($url->getScheme(), 'https'); - $this->assertEqual($url->getHost(), 'www.lastcraft.com'); - $this->assertEqual($url->getPath(), '/test/'); - } - - function testRelativeUrls() { - $url = new SimpleUrl('../somewhere.php'); - $this->assertEqual($url->getScheme(), false); - $this->assertEqual($url->getHost(), false); - $this->assertEqual($url->getPath(), '../somewhere.php'); - } - - function testParseBareParameter() { - $url = new SimpleUrl('?a'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseEmptyParameter() { - $url = new SimpleUrl('?a='); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a='); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseParameterPair() { - $url = new SimpleUrl('?a=A'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&x=X'); - } - - function testParseMultipleParameters() { - $url = new SimpleUrl('?a=A&b=B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X'); - } - - function testParsingParameterMixture() { - $url = new SimpleUrl('?a=A&b=&c'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X'); - } - - function testAddParametersFromScratch() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('b', 'B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('a', 'aaa'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa'); - } - - function testClearingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $url->clearRequest(); - $this->assertIdentical($url->getEncodedRequest(), ''); - } - - function testEncodingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', '?!"\'#~@[]{}:;<>,./|£$%^&*()_+-='); - $this->assertIdentical( - $request = $url->getEncodedRequest(), - '?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%A3%24%25%5E%26%2A%28%29_%2B-%3D'); - } - - function testDecodingParameters() { - $url = new SimpleUrl('?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%A3%24%25%5E%26%2A%28%29_%2B-%3D'); - $this->assertEqual( - $url->getEncodedRequest(), - '?a=' . urlencode('?!"\'#~@[]{}:;<>,./|£$%^&*()_+-=')); - } - - function testUrlInQueryDoesNotConfuseParsing() { - $url = new SimpleUrl('wibble/login.php?url=http://www.google.com/moo/'); - $this->assertFalse($url->getScheme()); - $this->assertFalse($url->getHost()); - $this->assertEqual($url->getPath(), 'wibble/login.php'); - $this->assertEqual($url->getEncodedRequest(), '?url=http://www.google.com/moo/'); - } - - function testSettingCordinates() { - $url = new SimpleUrl(''); - $url->setCoordinates('32', '45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), ''); - } - - function testParseCordinates() { - $url = new SimpleUrl('?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - } - - function testClearingCordinates() { - $url = new SimpleUrl('?32,45'); - $url->setCoordinates(); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - } - - function testParsingParameterCordinateMixture() { - $url = new SimpleUrl('?a=A&b=&c?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - } - - function testParsingParameterWithBadCordinates() { - $url = new SimpleUrl('?a=A&b=&c?32'); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32'); - } - - function testPageSplitting() { - $url = new SimpleUrl('./here/../there/somewhere.php'); - $this->assertEqual($url->getPath(), './here/../there/somewhere.php'); - $this->assertEqual($url->getPage(), 'somewhere.php'); - $this->assertEqual($url->getBasePath(), './here/../there/'); - } - - function testAbsolutePathPageSplitting() { - $url = new SimpleUrl("http://host.com/here/there/somewhere.php"); - $this->assertEqual($url->getPath(), "/here/there/somewhere.php"); - $this->assertEqual($url->getPage(), "somewhere.php"); - $this->assertEqual($url->getBasePath(), "/here/there/"); - } - - function testSplittingUrlWithNoPageGivesEmptyPage() { - $url = new SimpleUrl('/here/there/'); - $this->assertEqual($url->getPath(), '/here/there/'); - $this->assertEqual($url->getPage(), ''); - $this->assertEqual($url->getBasePath(), '/here/there/'); - } - - function testPathNormalisation() { - $this->assertEqual( - SimpleUrl::normalisePath('https://host.com/I/am/here/../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1535407 - function testPathNormalisationWithSinglePeriod() { - $this->assertEqual( - SimpleUrl::normalisePath('https://host.com/I/am/here/./../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1852413 - function testHostnameExtractedFromUContainingAtSign() { - $url = new SimpleUrl("http://localhost/name@example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name@example.com"); - } - - function testHostnameInLocalhost() { - $url = new SimpleUrl("http://localhost/name/example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name/example.com"); - } - - function testUsernameAndPasswordAreUrlDecoded() { - $url = new SimpleUrl('http://' . urlencode('test@test') . - ':' . urlencode('$!£@*&%') . '@www.lastcraft.com'); - $this->assertEqual($url->getUsername(), 'test@test'); - $this->assertEqual($url->getPassword(), '$!£@*&%'); - } - - function testBlitz() { - $this->assertUrl( - "https://username:password@www.somewhere.com:243/this/that/here.php?a=1&b=2#anchor", - array("https", "username", "password", "www.somewhere.com", 243, "/this/that/here.php", "com", "?a=1&b=2", "anchor"), - array("a" => "1", "b" => "2")); - $this->assertUrl( - "username:password@www.somewhere.com/this/that/here.php?a=1", - array(false, "username", "password", "www.somewhere.com", false, "/this/that/here.php", "com", "?a=1", false), - array("a" => "1")); - $this->assertUrl( - "username:password@somewhere.com:243?1,2", - array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false), - array(), - array(1, 2)); - $this->assertUrl( - "https://www.somewhere.com", - array("https", false, false, "www.somewhere.com", false, "/", "com", "", false)); - $this->assertUrl( - "username@www.somewhere.com:243#anchor", - array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor")); - $this->assertUrl( - "/this/that/here.php?a=1&b=2?3,4", - array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2"), - array(3, 4)); - $this->assertUrl( - "username@/here.php?a=1&b=2", - array(false, "username", false, false, false, "/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2")); - } - - function testAmbiguousHosts() { - $this->assertUrl( - "tigger", - array(false, false, false, false, false, "tigger", false, "", false)); - $this->assertUrl( - "/tigger", - array(false, false, false, false, false, "/tigger", false, "", false)); - $this->assertUrl( - "//tigger", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "//tigger/", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "tigger.com", - array(false, false, false, "tigger.com", false, "/", "com", "", false)); - $this->assertUrl( - "me.net/tigger", - array(false, false, false, "me.net", false, "/tigger", "net", "", false)); - } - - function testAsString() { - $this->assertPreserved('https://www.here.com'); - $this->assertPreserved('http://me:secret@www.here.com'); - $this->assertPreserved('http://here/there'); - $this->assertPreserved('http://here/there?a=A&b=B'); - $this->assertPreserved('http://here/there?a=1&a=2'); - $this->assertPreserved('http://here/there?a=1&a=2?9,8'); - $this->assertPreserved('http://host?a=1&a=2'); - $this->assertPreserved('http://host#stuff'); - $this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6'); - $this->assertPreserved('http://www.here.com/?a=A__b=B'); - } - - function assertUrl($raw, $parts, $params = false, $coords = false) { - if (! is_array($params)) { - $params = array(); - } - $url = new SimpleUrl($raw); - $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s"); - $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s"); - $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s"); - $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s"); - $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s"); - $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s"); - $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s"); - $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s"); - $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s"); - if ($coords) { - $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s"); - $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s"); - } - } - - function testUrlWithTwoSlashesInPath() { - $url = new SimpleUrl('/article/categoryedit/insert//'); - $this->assertEqual($url->getPath(), '/article/categoryedit/insert//'); - } - - function assertPreserved($string) { - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - } -} - -class TestOfAbsoluteUrls extends UnitTestCase { - - function testDirectoriesAfterFilename() { - $string = '../../index.php/foo/bar'; - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - - $absolute = $url->makeAbsolute('http://www.domain.com/some/path/'); - $this->assertEqual($absolute->asString(), 'http://www.domain.com/index.php/foo/bar'); - } - - function testMakingAbsolute() { - $url = new SimpleUrl('../there/somewhere.php'); - $this->assertEqual($url->getPath(), '../there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com:1234/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPort(), 1234); - $this->assertEqual($absolute->getPath(), '/I/am/there/somewhere.php'); - } - - function testMakingAnEmptyUrlAbsolute() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/page.html'); - } - - function testMakingAnEmptyUrlAbsoluteWithMissingPageName() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - } - - function testMakingAShortQueryUrlAbsolute() { - $url = new SimpleUrl('?a#b'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a'); - $this->assertEqual($absolute->getFragment(), 'b'); - } - - function testMakingADirectoryUrlAbsolute() { - $url = new SimpleUrl('hello/'); - $this->assertEqual($url->getPath(), 'hello/'); - $this->assertEqual($url->getBasePath(), 'hello/'); - $this->assertEqual($url->getPage(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/I/am/here/hello/'); - } - - function testMakingARootUrlAbsolute() { - $url = new SimpleUrl('/'); - $this->assertEqual($url->getPath(), '/'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/'); - } - - function testMakingARootPageUrlAbsolute() { - $url = new SimpleUrl('/here.html'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/here.html'); - } - - function testCarryAuthenticationFromRootPage() { - $url = new SimpleUrl('here.html'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/'); - $this->assertEqual($absolute->getPath(), '/here.html'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingCoordinateUrlAbsolute() { - $url = new SimpleUrl('?1,2'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getX(), 1); - $this->assertEqual($absolute->getY(), 2); - } - - function testMakingAbsoluteAppendedPath() { - $url = new SimpleUrl('./there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteBadlyFormedAppendedPath() { - $url = new SimpleUrl('there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteHasNoEffectWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://test:secret@www.lastcraft.com:321/stuff/?a=1#f'); - $absolute = $url->makeAbsolute('http://host.com/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getPort(), 321); - $this->assertEqual($absolute->getPath(), '/stuff/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a=1'); - $this->assertEqual($absolute->getFragment(), 'f'); - } - - function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://www.lastcraft.com'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/here/'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() { - $url = new SimpleUrl('http://www.lastcraft.com'); - $absolute = $url->makeAbsolute('https://host.com:81/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertIdentical($absolute->getPort(), false); - $this->assertEqual($absolute->getPath(), '/'); - } -} - -class TestOfFrameUrl extends UnitTestCase { - - function testTargetAttachment() { - $url = new SimpleUrl('http://www.site.com/home.html'); - $this->assertIdentical($url->getTarget(), false); - $url->setTarget('A frame'); - $this->assertIdentical($url->getTarget(), 'A frame'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/user_agent_test.php b/tests/simpletest/test/user_agent_test.php deleted file mode 100644 index 657c7e155..000000000 --- a/tests/simpletest/test/user_agent_test.php +++ /dev/null @@ -1,358 +0,0 @@ -_headers = &new MockSimpleHttpHeaders(); - - $this->_response = &new MockSimpleHttpResponse(); - $this->_response->setReturnValue('isError', false); - $this->_response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $this->_request = &new MockSimpleHttpRequest(); - $this->_request->setReturnReference('fetch', $this->_response); - } - - function testGetRequestWithoutIncidentGivesNoErrors() { - $url = new SimpleUrl('http://test:secret@this.com/page.html'); - $url->addRequestParameters(array('a' => 'A', 'b' => 'B')); - - $agent = &new MockRequestUserAgent(); - $agent->setReturnReference('_createHttpRequest', $this->_request); - $agent->SimpleUserAgent(); - - $response = &$agent->fetchResponse( - new SimpleUrl('http://test:secret@this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A', 'b' => 'B'))); - $this->assertFalse($response->isError()); - } -} - -class TestOfAdditionalHeaders extends UnitTestCase { - - function testAdditionalHeaderAddedToRequest() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = &new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('User-Agent: SimpleTest')); - - $agent = &new MockRequestUserAgent(); - $agent->setReturnReference('_createHttpRequest', $request); - $agent->SimpleUserAgent(); - $agent->addHeader('User-Agent: SimpleTest'); - $response = &$agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding()); - } -} - -class TestOfBrowserCookies extends UnitTestCase { - - function &_createStandardResponse() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnValue("getContent", "stuff"); - $response->setReturnReference("getHeaders", new MockSimpleHttpHeaders()); - return $response; - } - - function &_createCookieSite($header_lines) { - $headers = &new SimpleHttpHeaders($header_lines); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnReference("getHeaders", $headers); - $response->setReturnValue("getContent", "stuff"); - - $request = &new MockSimpleHttpRequest(); - $request->setReturnReference("fetch", $response); - return $request; - } - - function &_createMockedRequestUserAgent(&$request) { - $agent = &new MockRequestUserAgent(); - $agent->setReturnReference('_createHttpRequest', $request); - $agent->SimpleUserAgent(); - return $agent; - } - - function testCookieJarIsSentToRequest() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = &new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $this->_createStandardResponse()); - $request->expectOnce('readCookiesFromJar', array($jar, '*')); - - $agent = &$this->_createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testNoCookieJarIsSentToRequestWhenCookiesAreDisabled() { - $request = &new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $this->_createStandardResponse()); - $request->expectNever('readCookiesFromJar'); - - $agent = &$this->_createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testReadingNewCookie() { - $request = &$this->_createCookieSite('Set-cookie: a=AAAA'); - $agent = &$this->_createMockedRequestUserAgent($request); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testIgnoringNewCookieWhenCookiesDisabled() { - $request = &$this->_createCookieSite('Set-cookie: a=AAAA'); - $agent = &$this->_createMockedRequestUserAgent($request); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical($agent->getCookieValue("this.com", "this/path/", "a"), false); - } - - function testOverwriteCookieThatAlreadyExists() { - $request = &$this->_createCookieSite('Set-cookie: a=AAAA'); - $agent = &$this->_createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testClearCookieBySettingExpiry() { - $request = &$this->_createCookieSite('Set-cookie: a=b'); - $agent = &$this->_createMockedRequestUserAgent($request); - - $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "b"); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testAgeingAndClearing() { - $request = &$this->_createCookieSite('Set-cookie: a=A; expires=Wed, 25-Dec-02 04:24:21 GMT; path=/this/path'); - $agent = &$this->_createMockedRequestUserAgent($request); - - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "A"); - $agent->ageCookies(2); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testReadingIncomingAndSettingNewCookies() { - $request = &$this->_createCookieSite('Set-cookie: a=AAA'); - $agent = &$this->_createMockedRequestUserAgent($request); - - $this->assertNull($agent->getBaseCookieValue("a", false)); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->setCookie("b", "BBB", "this.com", "this/path/"); - $this->assertEqual( - $agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')), - "AAA"); - $this->assertEqual( - $agent->getBaseCookieValue("b", new SimpleUrl('http://this.com/this/path/page.html')), - "BBB"); - } -} - -class TestOfHttpRedirects extends UnitTestCase { - - function &createRedirect($content, $redirect) { - $headers = &new MockSimpleHttpHeaders(); - $headers->setReturnValue('isRedirect', (boolean)$redirect); - $headers->setReturnValue('getLocation', $redirect); - - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnReference('getHeaders', $headers); - - $request = &new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testDisabledRedirects() { - $agent = &new MockRequestUserAgent(); - $agent->setReturnReference( - '_createHttpRequest', - $this->createRedirect('stuff', 'there.html')); - $agent->expectOnce('_createHttpRequest'); - $agent->SimpleUserAgent(); - - $agent->setMaximumRedirects(0); - $response = &$agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'stuff'); - } - - function testSingleRedirect() { - $agent = &new MockRequestUserAgent(); - $agent->setReturnReferenceAt( - 0, - '_createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->setReturnReferenceAt( - 1, - '_createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectCallCount('_createHttpRequest', 2); - $agent->SimpleUserAgent(); - - $agent->setMaximumRedirects(1); - $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testDoubleRedirect() { - $agent = &new MockRequestUserAgent(); - $agent->setReturnReferenceAt( - 0, - '_createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->setReturnReferenceAt( - 1, - '_createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->setReturnReferenceAt( - 2, - '_createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('_createHttpRequest', 3); - $agent->SimpleUserAgent(); - - $agent->setMaximumRedirects(2); - $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'third'); - } - - function testSuccessAfterRedirect() { - $agent = &new MockRequestUserAgent(); - $agent->setReturnReferenceAt( - 0, - '_createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->setReturnReferenceAt( - 1, - '_createHttpRequest', - $this->createRedirect('second', false)); - $agent->setReturnReferenceAt( - 2, - '_createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('_createHttpRequest', 2); - $agent->SimpleUserAgent(); - - $agent->setMaximumRedirects(2); - $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testRedirectChangesPostToGet() { - $agent = &new MockRequestUserAgent(); - $agent->setReturnReferenceAt( - 0, - '_createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->expectArgumentsAt(0, '_createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding'))); - $agent->setReturnReferenceAt( - 1, - '_createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectArgumentsAt(1, '_createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding'))); - $agent->expectCallCount('_createHttpRequest', 2); - $agent->SimpleUserAgent(); - $agent->setMaximumRedirects(1); - $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding()); - } -} - -class TestOfBadHosts extends UnitTestCase { - - function &_createSimulatedBadHost() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnValue('isError', true); - $response->setReturnValue('getError', 'Bad socket'); - $response->setReturnValue('getContent', false); - - $request = &new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testUntestedHost() { - $request = &$this->_createSimulatedBadHost(); - - $agent = &new MockRequestUserAgent(); - $agent->setReturnReference('_createHttpRequest', $request); - $agent->SimpleUserAgent(); - - $response = &$agent->fetchResponse( - new SimpleUrl('http://this.host/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - } -} - -class TestOfAuthorisation extends UnitTestCase { - - function testAuthenticateHeaderAdded() { - $response = &new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = &new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('Authorization: Basic ' . base64_encode('test:secret'))); - - $agent = &new MockRequestUserAgent(); - $agent->setReturnReference('_createHttpRequest', $request); - $agent->SimpleUserAgent(); - $response = &$agent->fetchResponse( - new SimpleUrl('http://test:secret@this.host'), - new SimpleGetEncoding()); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/visual_test.php b/tests/simpletest/test/visual_test.php deleted file mode 100644 index 13781bb65..000000000 --- a/tests/simpletest/test/visual_test.php +++ /dev/null @@ -1,495 +0,0 @@ -_a = $a; - } - } - - class PassingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->pass('Pass'); - } - - function testTrue() { - $this->assertTrue(true); - } - - function testFalse() { - $this->assertFalse(false); - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 25, 'My assert message : %s'); - } - - function testNull() { - $this->assertNull(null, "%s -> Pass"); - $this->assertNotNull(false, "%s -> Pass"); - } - - function testType() { - $this->assertIsA("hello", "string", "%s -> Pass"); - $this->assertIsA($this, "PassingUnitTestCaseOutput", "%s -> Pass"); - $this->assertIsA($this, "UnitTestCase", "%s -> Pass"); - } - - function testTypeEquality() { - $this->assertEqual("0", 0, "%s -> Pass"); - } - - function testNullEquality() { - $this->assertNotEqual(null, 1, "%s -> Pass"); - $this->assertNotEqual(1, null, "%s -> Pass"); - } - - function testIntegerEquality() { - $this->assertNotEqual(1, 2, "%s -> Pass"); - } - - function testStringEquality() { - $this->assertEqual("a", "a", "%s -> Pass"); - $this->assertNotEqual("aa", "ab", "%s -> Pass"); - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass"); - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass"); - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertIdentical($a, $b, "%s -> Pass"); - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertNotIdentical($a, $b, "%s -> Pass"); - } - - function testNullIdentity() { - $this->assertNotIdentical(null, 1, "%s -> Pass"); - $this->assertNotIdentical(1, null, "%s -> Pass"); - } - - function testHashIdentity() { - } - - function testObjectEquality() { - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass"); - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Pass"); - } - - function testObjectIndentity() { - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Pass"); - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass"); - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertReference($a, $b, "%s -> Pass"); - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $b, "%s -> Pass"); - } - - function testPatterns() { - $this->assertPattern('/hello/i', "Hello there", "%s -> Pass"); - $this->assertNoPattern('/hello/', "Hello there", "%s -> Pass"); - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text, $text); - } - } - - class FailingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->fail('Fail'); // Fail. - } - - function testTrue() { - $this->assertTrue(false); // Fail. - } - - function testFalse() { - $this->assertFalse(true); // Fail. - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 24, 'My assert message : %s'); // Fail. - } - - function testNull() { - $this->assertNull(false, "%s -> Fail"); // Fail. - $this->assertNotNull(null, "%s -> Fail"); // Fail. - } - - function testType() { - $this->assertIsA(14, "string", "%s -> Fail"); // Fail. - $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail. - $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail. - } - - function testTypeEquality() { - $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail. - } - - function testNullEquality() { - $this->assertEqual(null, 1, "%s -> Fail"); // Fail. - $this->assertEqual(1, null, "%s -> Fail"); // Fail. - } - - function testIntegerEquality() { - $this->assertEqual(1, 2, "%s -> Fail"); // Fail. - } - - function testStringEquality() { - $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail. - $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail. - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Fail"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail. - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail. - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testNullIdentity() { - $this->assertIdentical(null, 1, "%s -> Fail"); // Fail. - $this->assertIdentical(1, null, "%s -> Fail"); // Fail. - } - - function testHashIdentity() { - $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail. - } - - function testObjectEquality() { - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail. - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail. - } - - function testObjectIndentity() { - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Fail"); // Fail. - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail. - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertClone($a, $b, "%s -> Fail"); // Fail. - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $c, "%s -> Fail"); // Fail. - } - - function testPatterns() { - $this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail. - $this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail. - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text . $text, $text . "a" . $text); // Fail. - } - } - - class Dummy { - function Dummy() { - } - - function a() { - } - } - Mock::generate('Dummy'); - - class TestOfMockObjectsOutput extends UnitTestCase { - - function testCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectCallCount('a', 1, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testMinimumCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectMinimumCallCount('a', 2, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testEmptyMatching() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array()); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testEmptyMatchingWithCustomMessage() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array(), 'My expectation message: %s'); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testNullMatching() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array(null)); - $dummy->a(null); - $dummy->a(); // Fail. - } - - function testBooleanMatching() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array(true, false)); - $dummy->a(true, false); - $dummy->a(true, true); // Fail. - } - - function testIntegerMatching() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array(32, 33)); - $dummy->a(32, 33); - $dummy->a(32, 34); // Fail. - } - - function testFloatMatching() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array(3.2, 3.3)); - $dummy->a(3.2, 3.3); - $dummy->a(3.2, 3.4); // Fail. - } - - function testStringMatching() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array('32', '33')); - $dummy->a('32', '33'); - $dummy->a('32', '34'); // Fail. - } - - function testEmptyMatchingWithCustomExpectationMessage() { - $dummy = &new MockDummy(); - $dummy->expectArguments( - 'a', - array(new EqualExpectation('A', 'My part expectation message: %s')), - 'My expectation message: %s'); - $dummy->a('A'); - $dummy->a('B'); // Fail. - } - - function testArrayMatching() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array(array(32), array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } - - function testObjectMatching() { - $a = new Dummy(); - $a->a = 'a'; - $b = new Dummy(); - $b->b = 'b'; - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array($a, $b)); - $dummy->a($a, $b); - $dummy->a($a, $a); // Fail. - } - - function testBigList() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array(false, 0, 1, 1.0)); - $dummy->a(false, 0, 1, 1.0); - $dummy->a(true, false, 2, 2.0); // Fail. - } - } - - class TestOfPastBugs extends UnitTestCase { - - function testMixedTypes() { - $this->assertEqual(array(), null, "%s -> Pass"); - $this->assertIdentical(array(), null, "%s -> Fail"); // Fail. - } - - function testMockWildcards() { - $dummy = &new MockDummy(); - $dummy->expectArguments('a', array('*', array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } - } - - class TestOfVisualShell extends ShellTestCase { - - function testDump() { - $this->execute('ls'); - $this->dumpOutput(); - $this->execute('dir'); - $this->dumpOutput(); - } - - function testDumpOfList() { - $this->execute('ls'); - $this->dump($this->getOutputAsList()); - } - } - - class PassesAsWellReporter extends HtmlReporter { - - function _getCss() { - return parent::_getCss() . ' .pass { color: darkgreen; }'; - } - - function paintPass($message) { - parent::paintPass($message); - print "Pass: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities($message) . "
\n"; - } - - function paintSignal($type, &$payload) { - print "$type: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities(serialize($payload)) . "
\n"; - } - } - - class TestOfSkippingNoMatterWhat extends UnitTestCase { - function skip() { - $this->skipIf(true, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } - } - - class TestOfSkippingOrElse extends UnitTestCase { - function skip() { - $this->skipUnless(false, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } - } - - class TestOfSkippingTwiceOver extends UnitTestCase { - function skip() { - $this->skipIf(true, 'First reason -> %s'); - $this->skipIf(true, 'Second reason -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } - } - - class TestThatShouldNotBeSkipped extends UnitTestCase { - function skip() { - $this->skipIf(false); - $this->skipUnless(true); - } - - function testFail() { - $this->fail('We should see this message'); - } - - function testPass() { - $this->pass('We should see this message'); - } - } - - $test = &new TestSuite('Visual test with 46 passes, 47 fails and 0 exceptions'); - $test->addTestCase(new PassingUnitTestCaseOutput()); - $test->addTestCase(new FailingUnitTestCaseOutput()); - $test->addTestCase(new TestOfMockObjectsOutput()); - $test->addTestCase(new TestOfPastBugs()); - $test->addTestCase(new TestOfVisualShell()); - $test->addTestCase(new TestOfSkippingNoMatterWhat()); - $test->addTestCase(new TestOfSkippingOrElse()); - $test->addTestCase(new TestOfSkippingTwiceOver()); - $test->addTestCase(new TestThatShouldNotBeSkipped()); - - if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) { - $reporter = &new XmlReporter(); - } elseif (TextReporter::inCli()) { - $reporter = &new TextReporter(); - } else { - $reporter = &new PassesAsWellReporter(); - } - if (isset($_GET['dry']) || in_array('dry', (isset($argv) ? $argv : array()))) { - $reporter->makeDry(); - } - exit ($test->run($reporter) ? 0 : 1); -?> \ No newline at end of file diff --git a/tests/simpletest/test/web_tester_test.php b/tests/simpletest/test/web_tester_test.php deleted file mode 100644 index 01f7d3c8c..000000000 --- a/tests/simpletest/test/web_tester_test.php +++ /dev/null @@ -1,156 +0,0 @@ -assertTrue($expectation->test('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertFalse($expectation->test('A')); - } - - function testMatchesInteger() { - $expectation = new FieldExpectation('1'); - $this->assertTrue($expectation->test('1')); - $this->assertTrue($expectation->test(1)); - $this->assertTrue($expectation->test(array('1'))); - $this->assertTrue($expectation->test(array(1))); - } - - function testNonStringFailsExpectation() { - $expectation = new FieldExpectation('a'); - $this->assertFalse($expectation->test(null)); - } - - function testUnsetFieldCanBeTestedFor() { - $expectation = new FieldExpectation(false); - $this->assertTrue($expectation->test(false)); - } - - function testMultipleValuesCanBeInAnyOrder() { - $expectation = new FieldExpectation(array('a', 'b')); - $this->assertTrue($expectation->test(array('a', 'b'))); - $this->assertTrue($expectation->test(array('b', 'a'))); - $this->assertFalse($expectation->test(array('a', 'a'))); - $this->assertFalse($expectation->test('a')); - } - - function testSingleItemCanBeArrayOrString() { - $expectation = new FieldExpectation(array('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertTrue($expectation->test('a')); - } -} - -class TestOfHeaderExpectations extends UnitTestCase { - - function testExpectingOnlyTheHeaderName() { - $expectation = new HttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('a: B'), true); - $this->assertIdentical($expectation->test(' a : A '), true); - } - - function testHeaderValueAsWell() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), false); - } - - function testHeaderValueWithColons() { - $expectation = new HttpHeaderExpectation('a', 'A:B:C'); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('a: A:B'), false); - $this->assertIdentical($expectation->test('a: A:B:C'), true); - $this->assertIdentical($expectation->test('a: A:B:C:D'), false); - } - - function testMultilineSearch() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false); - $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true); - } - - function testMultilineSearchWithPadding() { - $expectation = new HttpHeaderExpectation('a', ' A '); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true); - } - - function testPatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/')); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), true); - } - - function testCaseInsensitivePatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i')); - $this->assertIdentical($expectation->test('a: a'), true); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : BAB '), true); - $this->assertIdentical($expectation->test(' a : bab '), true); - } - - function testUnwantedHeader() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('stuff'), true); - $this->assertIdentical($expectation->test('b: B'), true); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('A: A'), false); - } - - function testMultilineUnwantedSearch() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false); - } - - function testLocationHeaderSplitsCorrectly() { - $expectation = new HttpHeaderExpectation('Location', 'http://here/'); - $this->assertIdentical($expectation->test('Location: http://here/'), true); - } -} - -class TestOfTextExpectations extends UnitTestCase { - - function testMatchingSubString() { - $expectation = new TextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), false); - $this->assertIdentical($expectation->test('Wanted'), false); - $this->assertIdentical($expectation->test('wanted'), true); - $this->assertIdentical($expectation->test('the wanted text is here'), true); - } - - function testNotMatchingSubString() { - $expectation = new NoTextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('Wanted'), true); - $this->assertIdentical($expectation->test('wanted'), false); - $this->assertIdentical($expectation->test('the wanted text is here'), false); - } -} - -class TestOfGenericAssertionsInWebTester extends WebTestCase { - - function testEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test/xml_test.php b/tests/simpletest/test/xml_test.php deleted file mode 100644 index 91985b5d5..000000000 --- a/tests/simpletest/test/xml_test.php +++ /dev/null @@ -1,187 +0,0 @@ - 2)); - $this->assertEqual($nesting->getSize(), 2); - } -} - -class TestOfXmlStructureParsing extends UnitTestCase { - function testValidXml() { - $listener = &new MockSimpleScorer(); - $listener->expectNever('paintGroupStart'); - $listener->expectNever('paintGroupEnd'); - $listener->expectNever('paintCaseStart'); - $listener->expectNever('paintCaseEnd'); - $parser = &new SimpleTestXmlParser($listener); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - } - - function testEmptyGroup() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintGroupStart', array('a_group', 7)); - $listener->expectOnce('paintGroupEnd', array('a_group')); - $parser = &new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyCase() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $parser = &new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_case\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyMethod() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $listener->expectOnce('paintMethodStart', array('a_method')); - $listener->expectOnce('paintMethodEnd', array('a_method')); - $parser = &new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_method\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testNestedGroup() { - $listener = &new MockSimpleScorer(); - $listener->expectArgumentsAt(0, 'paintGroupStart', array('a_group', 7)); - $listener->expectArgumentsAt(1, 'paintGroupStart', array('b_group', 3)); - $listener->expectCallCount('paintGroupStart', 2); - $listener->expectArgumentsAt(0, 'paintGroupEnd', array('b_group')); - $listener->expectArgumentsAt(1, 'paintGroupEnd', array('a_group')); - $listener->expectCallCount('paintGroupEnd', 2); - - $parser = &new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("b_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } -} - -class AnyOldSignal { - var $stuff = true; -} - -class TestOfXmlResultsParsing extends UnitTestCase { - - function sendValidStart(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $parser->parse("\n"); - $parser->parse("a_method\n"); - } - - function sendValidEnd(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testPass() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintPass', array('a_message')); - $parser = &new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFail() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintFail', array('a_message')); - $parser = &new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testException() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintError', array('a_message')); - $parser = &new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSkip() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintSkip', array('a_message')); - $parser = &new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSignal() { - $signal = new AnyOldSignal(); - $signal->stuff = "Hello"; - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintSignal', array('a_signal', $signal)); - $parser = &new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse( - "\n")); - $this->sendValidEnd($parser); - } - - function testMessage() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintMessage', array('a_message')); - $parser = &new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFormattedMessage() { - $listener = &new MockSimpleScorer(); - $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); - $parser = &new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("\n")); - $this->sendValidEnd($parser); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/test_case.php b/tests/simpletest/test_case.php deleted file mode 100644 index e5b229833..000000000 --- a/tests/simpletest/test_case.php +++ /dev/null @@ -1,708 +0,0 @@ -= 0) { - require_once(dirname(__FILE__) . '/exceptions.php'); - require_once(dirname(__FILE__) . '/reflection_php5.php'); -} else { - require_once(dirname(__FILE__) . '/reflection_php4.php'); -} -if (! defined('SIMPLE_TEST')) { - /** - * @ignore - */ - define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR); -} -/**#@-*/ - -/** - * Basic test case. This is the smallest unit of a test - * suite. It searches for - * all methods that start with the the string "test" and - * runs them. Working test cases extend this class. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleTestCase { - var $_label = false; - var $_reporter; - var $_observers; - var $_should_skip = false; - - /** - * Sets up the test with no display. - * @param string $label If no test name is given then - * the class name is used. - * @access public - */ - function SimpleTestCase($label = false) { - if ($label) { - $this->_label = $label; - } - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->_label ? $this->_label : get_class($this); - } - - /** - * This is a placeholder for skipping tests. In this - * method you place skipIf() and skipUnless() calls to - * set the skipping state. - * @access public - */ - function skip() { - } - - /** - * Will issue a message to the reporter and tell the test - * case to skip if the incoming flag is true. - * @param string $should_skip Condition causing the tests to be skipped. - * @param string $message Text of skip condition. - * @access public - */ - function skipIf($should_skip, $message = '%s') { - if ($should_skip && ! $this->_should_skip) { - $this->_should_skip = true; - $message = sprintf($message, 'Skipping [' . get_class($this) . ']'); - $this->_reporter->paintSkip($message . $this->getAssertionLine()); - } - } - - /** - * Will issue a message to the reporter and tell the test - * case to skip if the incoming flag is false. - * @param string $shouldnt_skip Condition causing the tests to be run. - * @param string $message Text of skip condition. - * @access public - */ - function skipUnless($shouldnt_skip, $message = false) { - $this->skipIf(! $shouldnt_skip, $message); - } - - /** - * Used to invoke the single tests. - * @return SimpleInvoker Individual test runner. - * @access public - */ - function &createInvoker() { - $invoker = &new SimpleErrorTrappingInvoker(new SimpleInvoker($this)); - if (version_compare(phpversion(), '5') >= 0) { - $invoker = &new SimpleExceptionTrappingInvoker($invoker); - } - return $invoker; - } - - /** - * Uses reflection to run every method within itself - * starting with the string "test" unless a method - * is specified. - * @param SimpleReporter $reporter Current test reporter. - * @return boolean True if all tests passed. - * @access public - */ - function run(&$reporter) { - $context = &SimpleTest::getContext(); - $context->setTest($this); - $context->setReporter($reporter); - $this->_reporter = &$reporter; - $started = false; - foreach ($this->getTests() as $method) { - if ($reporter->shouldInvoke($this->getLabel(), $method)) { - $this->skip(); - if ($this->_should_skip) { - break; - } - if (! $started) { - $reporter->paintCaseStart($this->getLabel()); - $started = true; - } - $invoker = &$this->_reporter->createInvoker($this->createInvoker()); - $invoker->before($method); - $invoker->invoke($method); - $invoker->after($method); - } - } - if ($started) { - $reporter->paintCaseEnd($this->getLabel()); - } - unset($this->_reporter); - return $reporter->getStatus(); - } - - /** - * Gets a list of test names. Normally that will - * be all internal methods that start with the - * name "test". This method should be overridden - * if you want a different rule. - * @return array List of test names. - * @access public - */ - function getTests() { - $methods = array(); - foreach (get_class_methods(get_class($this)) as $method) { - if ($this->_isTest($method)) { - $methods[] = $method; - } - } - return $methods; - } - - /** - * Tests to see if the method is a test that should - * be run. Currently any method that starts with 'test' - * is a candidate unless it is the constructor. - * @param string $method Method name to try. - * @return boolean True if test method. - * @access protected - */ - function _isTest($method) { - if (strtolower(substr($method, 0, 4)) == 'test') { - return ! SimpleTestCompatibility::isA($this, strtolower($method)); - } - return false; - } - - /** - * Announces the start of the test. - * @param string $method Test method just started. - * @access public - */ - function before($method) { - $this->_reporter->paintMethodStart($method); - $this->_observers = array(); - } - - /** - * Sets up unit test wide variables at the start - * of each test method. To be overridden in - * actual user test cases. - * @access public - */ - function setUp() { - } - - /** - * Clears the data set in the setUp() method call. - * To be overridden by the user in actual user test cases. - * @access public - */ - function tearDown() { - } - - /** - * Announces the end of the test. Includes private clean up. - * @param string $method Test method just finished. - * @access public - */ - function after($method) { - for ($i = 0; $i < count($this->_observers); $i++) { - $this->_observers[$i]->atTestEnd($method, $this); - } - $this->_reporter->paintMethodEnd($method); - } - - /** - * Sets up an observer for the test end. - * @param object $observer Must have atTestEnd() - * method. - * @access public - */ - function tell(&$observer) { - $this->_observers[] = &$observer; - } - - /** - * @deprecated - */ - function pass($message = "Pass") { - if (! isset($this->_reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->_reporter->paintPass( - $message . $this->getAssertionLine()); - return true; - } - - /** - * Sends a fail event with a message. - * @param string $message Message to send. - * @access public - */ - function fail($message = "Fail") { - if (! isset($this->_reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->_reporter->paintFail( - $message . $this->getAssertionLine()); - return false; - } - - /** - * Formats a PHP error and dispatches it to the - * reporter. - * @param integer $severity PHP error code. - * @param string $message Text of error. - * @param string $file File error occoured in. - * @param integer $line Line number of error. - * @access public - */ - function error($severity, $message, $file, $line) { - if (! isset($this->_reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->_reporter->paintError( - "Unexpected PHP error [$message] severity [$severity] in [$file line $line]"); - } - - /** - * Formats an exception and dispatches it to the - * reporter. - * @param Exception $exception Object thrown. - * @access public - */ - function exception($exception) { - $this->_reporter->paintException($exception); - } - - /** - * @deprecated - */ - function signal($type, &$payload) { - if (! isset($this->_reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->_reporter->paintSignal($type, $payload); - } - - /** - * Runs an expectation directly, for extending the - * tests with new expectation classes. - * @param SimpleExpectation $expectation Expectation subclass. - * @param mixed $compare Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assert(&$expectation, $compare, $message = '%s') { - if ($expectation->test($compare)) { - return $this->pass(sprintf( - $message, - $expectation->overlayMessage($compare, $this->_reporter->getDumper()))); - } else { - return $this->fail(sprintf( - $message, - $expectation->overlayMessage($compare, $this->_reporter->getDumper()))); - } - } - - /** - * @deprecated - */ - function assertExpectation(&$expectation, $compare, $message = '%s') { - return $this->assert($expectation, $compare, $message); - } - - /** - * Uses a stack trace to find the line of an assertion. - * @return string Line number of first assert* - * method embedded in format string. - * @access public - */ - function getAssertionLine() { - $trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip')); - return $trace->traceMethod(); - } - - /** - * Sends a formatted dump of a variable to the - * test suite for those emergency debugging - * situations. - * @param mixed $variable Variable to display. - * @param string $message Message to display. - * @return mixed The original variable. - * @access public - */ - function dump($variable, $message = false) { - $dumper = $this->_reporter->getDumper(); - $formatted = $dumper->dump($variable); - if ($message) { - $formatted = $message . "\n" . $formatted; - } - $this->_reporter->paintFormattedMessage($formatted); - return $variable; - } - - /** - * @deprecated - */ - function sendMessage($message) { - $this->_reporter->PaintMessage($message); - } - - /** - * Accessor for the number of subtests including myelf. - * @return integer Number of test cases. - * @access public - * @static - */ - function getSize() { - return 1; - } -} - -/** - * Helps to extract test cases automatically from a file. - */ -class SimpleFileLoader { - - /** - * Builds a test suite from a library of test cases. - * The new suite is composed into this one. - * @param string $test_file File name of library with - * test case classes. - * @return TestSuite The new test suite. - * @access public - */ - function &load($test_file) { - $existing_classes = get_declared_classes(); - $existing_globals = get_defined_vars(); - include_once($test_file); - $new_globals = get_defined_vars(); - $this->_makeFileVariablesGlobal($existing_globals, $new_globals); - $new_classes = array_diff(get_declared_classes(), $existing_classes); - if (empty($new_classes)) { - $new_classes = $this->_scrapeClassesFromFile($test_file); - } - $classes = $this->selectRunnableTests($new_classes); - $suite = &$this->createSuiteFromClasses($test_file, $classes); - return $suite; - } - - /** - * Imports new variables into the global namespace. - * @param hash $existing Variables before the file was loaded. - * @param hash $new Variables after the file was loaded. - * @access private - */ - function _makeFileVariablesGlobal($existing, $new) { - $globals = array_diff(array_keys($new), array_keys($existing)); - foreach ($globals as $global) { - $_GLOBALS[$global] = $new[$global]; - } - } - - /** - * Lookup classnames from file contents, in case the - * file may have been included before. - * Note: This is probably too clever by half. Figuring this - * out after a failed test case is going to be tricky for us, - * never mind the user. A test case should not be included - * twice anyway. - * @param string $test_file File name with classes. - * @access private - */ - function _scrapeClassesFromFile($test_file) { - preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi', - file_get_contents($test_file), - $matches ); - return $matches[1]; - } - - /** - * Calculates the incoming test cases. Skips abstract - * and ignored classes. - * @param array $candidates Candidate classes. - * @return array New classes which are test - * cases that shouldn't be ignored. - * @access public - */ - function selectRunnableTests($candidates) { - $classes = array(); - foreach ($candidates as $class) { - if (TestSuite::getBaseTestCase($class)) { - $reflection = new SimpleReflection($class); - if ($reflection->isAbstract()) { - SimpleTest::ignore($class); - } else { - $classes[] = $class; - } - } - } - return $classes; - } - - /** - * Builds a test suite from a class list. - * @param string $title Title of new group. - * @param array $classes Test classes. - * @return TestSuite Group loaded with the new - * test cases. - * @access public - */ - function &createSuiteFromClasses($title, $classes) { - if (count($classes) == 0) { - $suite = &new BadTestSuite($title, "No runnable test cases in [$title]"); - return $suite; - } - SimpleTest::ignoreParentsIfIgnored($classes); - $suite = &new TestSuite($title); - foreach ($classes as $class) { - if (! SimpleTest::isIgnored($class)) { - $suite->addTestClass($class); - } - } - return $suite; - } -} - -/** - * This is a composite test class for combining - * test cases and other RunnableTest classes into - * a group test. - * @package SimpleTest - * @subpackage UnitTester - */ -class TestSuite { - var $_label; - var $_test_cases; - - /** - * Sets the name of the test suite. - * @param string $label Name sent at the start and end - * of the test. - * @access public - */ - function TestSuite($label = false) { - $this->_label = $label; - $this->_test_cases = array(); - } - - /** - * Accessor for the test name for subclasses. If the suite - * wraps a single test case the label defaults to the name of that test. - * @return string Name of the test. - * @access public - */ - function getLabel() { - if (! $this->_label) { - return ($this->getSize() == 1) ? - get_class($this->_test_cases[0]) : get_class($this); - } else { - return $this->_label; - } - } - - /** - * @deprecated - */ - function addTestCase(&$test_case) { - $this->_test_cases[] = &$test_case; - } - - /** - * @deprecated - */ - function addTestClass($class) { - if (TestSuite::getBaseTestCase($class) == 'testsuite') { - $this->_test_cases[] = &new $class(); - } else { - $this->_test_cases[] = $class; - } - } - - /** - * Adds a test into the suite by instance or class. The class will - * be instantiated if it's a test suite. - * @param SimpleTestCase $test_case Suite or individual test - * case implementing the - * runnable test interface. - * @access public - */ - function add(&$test_case) { - if (! is_string($test_case)) { - $this->_test_cases[] = &$test_case; - } elseif (TestSuite::getBaseTestCase($class) == 'testsuite') { - $this->_test_cases[] = &new $class(); - } else { - $this->_test_cases[] = $class; - } - } - - /** - * @deprecated - */ - function addTestFile($test_file) { - $this->addFile($test_file); - } - - /** - * Builds a test suite from a library of test cases. - * The new suite is composed into this one. - * @param string $test_file File name of library with - * test case classes. - * @access public - */ - function addFile($test_file) { - $extractor = new SimpleFileLoader(); - $this->add($extractor->load($test_file)); - } - - /** - * Delegates to a visiting collector to add test - * files. - * @param string $path Path to scan from. - * @param SimpleCollector $collector Directory scanner. - * @access public - */ - function collect($path, &$collector) { - $collector->collect($this, $path); - } - - /** - * Invokes run() on all of the held test cases, instantiating - * them if necessary. - * @param SimpleReporter $reporter Current test reporter. - * @access public - */ - function run(&$reporter) { - $reporter->paintGroupStart($this->getLabel(), $this->getSize()); - for ($i = 0, $count = count($this->_test_cases); $i < $count; $i++) { - if (is_string($this->_test_cases[$i])) { - $class = $this->_test_cases[$i]; - $test = &new $class(); - $test->run($reporter); - unset($test); - } else { - $this->_test_cases[$i]->run($reporter); - } - } - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - /** - * Number of contained test cases. - * @return integer Total count of cases in the group. - * @access public - */ - function getSize() { - $count = 0; - foreach ($this->_test_cases as $case) { - if (is_string($case)) { - if (! SimpleTest::isIgnored($case)) { - $count++; - } - } else { - $count += $case->getSize(); - } - } - return $count; - } - - /** - * Test to see if a class is derived from the - * SimpleTestCase class. - * @param string $class Class name. - * @access public - * @static - */ - function getBaseTestCase($class) { - while ($class = get_parent_class($class)) { - $class = strtolower($class); - if ($class == 'simpletestcase' || $class == 'testsuite') { - return $class; - } - } - return false; - } -} - -/** - * @package SimpleTest - * @subpackage UnitTester - * @deprecated - */ -class GroupTest extends TestSuite { } - -/** - * This is a failing group test for when a test suite hasn't - * loaded properly. - * @package SimpleTest - * @subpackage UnitTester - */ -class BadTestSuite { - var $_label; - var $_error; - - /** - * Sets the name of the test suite and error message. - * @param string $label Name sent at the start and end - * of the test. - * @access public - */ - function BadTestSuite($label, $error) { - $this->_label = $label; - $this->_error = $error; - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->_label; - } - - /** - * Sends a single error to the reporter. - * @param SimpleReporter $reporter Current test reporter. - * @access public - */ - function run(&$reporter) { - $reporter->paintGroupStart($this->getLabel(), $this->getSize()); - $reporter->paintFail('Bad TestSuite [' . $this->getLabel() . - '] with error [' . $this->_error . ']'); - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - /** - * Number of contained test cases. Always zero. - * @return integer Total count of cases in the group. - * @access public - */ - function getSize() { - return 0; - } -} - -/** - * @package SimpleTest - * @subpackage UnitTester - * @deprecated - */ -class BadGroupTest extends BadTestSuite { } -?> diff --git a/tests/simpletest/unit_tester.php b/tests/simpletest/unit_tester.php deleted file mode 100644 index 8bb757d4e..000000000 --- a/tests/simpletest/unit_tester.php +++ /dev/null @@ -1,420 +0,0 @@ -SimpleTestCase($label); - } - - /** - * Called from within the test methods to register - * passes and failures. - * @param boolean $result Pass on true. - * @param string $message Message to display describing - * the test state. - * @return boolean True on pass - * @access public - */ - function assertTrue($result, $message = false) { - return $this->assert(new TrueExpectation(), $result, $message); - } - - /** - * Will be true on false and vice versa. False - * is the PHP definition of false, so that null, - * empty strings, zero and an empty array all count - * as false. - * @param boolean $result Pass on false. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertFalse($result, $message = '%s') { - return $this->assert(new FalseExpectation(), $result, $message); - } - - /** - * Will be true if the value is null. - * @param null $value Supposedly null value. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNull($value, $message = '%s') { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($value) . '] should be null'); - return $this->assertTrue(! isset($value), $message); - } - - /** - * Will be true if the value is set. - * @param mixed $value Supposedly set value. - * @param string $message Message to display. - * @return boolean True on pass. - * @access public - */ - function assertNotNull($value, $message = '%s') { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($value) . '] should not be null'); - return $this->assertTrue(isset($value), $message); - } - - /** - * Type and class test. Will pass if class - * matches the type name or is a subclass or - * if not an object, but the type is correct. - * @param mixed $object Object to test. - * @param string $type Type name as string. - * @param string $message Message to display. - * @return boolean True on pass. - * @access public - */ - function assertIsA($object, $type, $message = '%s') { - return $this->assert( - new IsAExpectation($type), - $object, - $message); - } - - /** - * Type and class mismatch test. Will pass if class - * name or underling type does not match the one - * specified. - * @param mixed $object Object to test. - * @param string $type Type name as string. - * @param string $message Message to display. - * @return boolean True on pass. - * @access public - */ - function assertNotA($object, $type, $message = '%s') { - return $this->assert( - new NotAExpectation($type), - $object, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value only. Otherwise a fail. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertEqual($first, $second, $message = '%s') { - return $this->assert( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * a different value. Otherwise a fail. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotEqual($first, $second, $message = '%s') { - return $this->assert( - new NotEqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the if the first parameter - * is near enough to the second by the margin. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param mixed $margin Fuzziness of match. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertWithinMargin($first, $second, $margin, $message = '%s') { - return $this->assert( - new WithinMarginExpectation($first, $margin), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters differ - * by more than the margin. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param mixed $margin Fuzziness of match. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertOutsideMargin($first, $second, $margin, $message = '%s') { - return $this->assert( - new OutsideMarginExpectation($first, $margin), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value and same type. Otherwise a fail. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertIdentical($first, $second, $message = '%s') { - return $this->assert( - new IdenticalExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * the different value or different type. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotIdentical($first, $second, $message = '%s') { - return $this->assert( - new NotIdenticalExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if both parameters refer - * to the same object. Fail otherwise. - * @param mixed $first Object reference to check. - * @param mixed $second Hopefully the same object. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertReference(&$first, &$second, $message = '%s') { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($first) . - '] and [' . $dumper->describeValue($second) . - '] should reference the same object'); - return $this->assertTrue( - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Will trigger a pass if both parameters refer - * to different objects. Fail otherwise. The objects - * have to be identical though. - * @param mixed $first Object reference to check. - * @param mixed $second Hopefully not the same object. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertClone(&$first, &$second, $message = '%s') { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($first) . - '] and [' . $dumper->describeValue($second) . - '] should not be the same object'); - $identical = &new IdenticalExpectation($first); - return $this->assertTrue( - $identical->test($second) && - ! SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * @deprecated - */ - function assertCopy(&$first, &$second, $message = "%s") { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should not be the same object"); - return $this->assertFalse( - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Will trigger a pass if the Perl regex pattern - * is found in the subject. Fail otherwise. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $subject String to search in. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertPattern($pattern, $subject, $message = '%s') { - return $this->assert( - new PatternExpectation($pattern), - $subject, - $message); - } - - /** - * @deprecated - */ - function assertWantedPattern($pattern, $subject, $message = '%s') { - return $this->assertPattern($pattern, $subject, $message); - } - - /** - * Will trigger a pass if the perl regex pattern - * is not present in subject. Fail if found. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $subject String to search in. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNoPattern($pattern, $subject, $message = '%s') { - return $this->assert( - new NoPatternExpectation($pattern), - $subject, - $message); - } - - /** - * @deprecated - */ - function assertNoUnwantedPattern($pattern, $subject, $message = '%s') { - return $this->assertNoPattern($pattern, $subject, $message); - } - - /** - * @deprecated - */ - function swallowErrors() { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - $queue->clear(); - } - - /** - * @deprecated - */ - function assertNoErrors($message = '%s') { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - return $queue->assertNoErrors($message); - } - - /** - * @deprecated - */ - function assertError($expected = false, $message = '%s') { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - return $queue->assertError($this->_coerceExpectation($expected), $message); - } - - /** - * Prepares for an error. If the error mismatches it - * passes through, otherwise it is swallowed. Any - * left over errors trigger failures. - * @param SimpleExpectation/string $expected The error to match. - * @param string $message Message on failure. - * @access public - */ - function expectError($expected = false, $message = '%s') { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleErrorQueue'); - $queue->expectError($this->_coerceExpectation($expected), $message); - } - - /** - * Prepares for an exception. If the error mismatches it - * passes through, otherwise it is swallowed. Any - * left over errors trigger failures. - * @param SimpleExpectation/Exception $expected The error to match. - * @param string $message Message on failure. - * @access public - */ - function expectException($expected = false, $message = '%s') { - $context = &SimpleTest::getContext(); - $queue = &$context->get('SimpleExceptionTrap'); - // :HACK: Directly substituting in seems to cause a segfault with - // Zend Optimizer on some systems - $line = $this->getAssertionLine(); - $queue->expectException($expected, $message . $line); - } - - /** - * Creates an equality expectation if the - * object/value is not already some type - * of expectation. - * @param mixed $expected Expected value. - * @return SimpleExpectation Expectation object. - * @access private - */ - function _coerceExpectation($expected) { - if ($expected == false) { - return new TrueExpectation(); - } - if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { - return $expected; - } - return new EqualExpectation( - is_string($expected) ? str_replace('%', '%%', $expected) : $expected); - } - - /** - * @deprecated - */ - function assertErrorPattern($pattern, $message = '%s') { - return $this->assertError(new PatternExpectation($pattern), $message); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/url.php b/tests/simpletest/url.php deleted file mode 100644 index 0ea220409..000000000 --- a/tests/simpletest/url.php +++ /dev/null @@ -1,528 +0,0 @@ -_chompCoordinates($url); - $this->setCoordinates($x, $y); - $this->_scheme = $this->_chompScheme($url); - list($this->_username, $this->_password) = $this->_chompLogin($url); - $this->_host = $this->_chompHost($url); - $this->_port = false; - if (preg_match('/(.*?):(.*)/', $this->_host, $host_parts)) { - $this->_host = $host_parts[1]; - $this->_port = (integer)$host_parts[2]; - } - $this->_path = $this->_chompPath($url); - $this->_request = $this->_parseRequest($this->_chompRequest($url)); - $this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); - $this->_target = false; - } - - /** - * Extracts the X, Y coordinate pair from an image map. - * @param string $url URL so far. The coordinates will be - * removed. - * @return array X, Y as a pair of integers. - * @access private - */ - function _chompCoordinates(&$url) { - if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) { - $url = $matches[1]; - return array((integer)$matches[2], (integer)$matches[3]); - } - return array(false, false); - } - - /** - * Extracts the scheme part of an incoming URL. - * @param string $url URL so far. The scheme will be - * removed. - * @return string Scheme part or false. - * @access private - */ - function _chompScheme(&$url) { - if (preg_match('/^([^\/:]*):(\/\/)(.*)/', $url, $matches)) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } - return false; - } - - /** - * Extracts the username and password from the - * incoming URL. The // prefix will be reattached - * to the URL after the doublet is extracted. - * @param string $url URL so far. The username and - * password are removed. - * @return array Two item list of username and - * password. Will urldecode() them. - * @access private - */ - function _chompLogin(&$url) { - $prefix = ''; - if (preg_match('/^(\/\/)(.*)/', $url, $matches)) { - $prefix = $matches[1]; - $url = $matches[2]; - } - if (preg_match('/^([^\/]*)@(.*)/', $url, $matches)) { - $url = $prefix . $matches[2]; - $parts = split(":", $matches[1]); - return array( - urldecode($parts[0]), - isset($parts[1]) ? urldecode($parts[1]) : false); - } - $url = $prefix . $url; - return array(false, false); - } - - /** - * Extracts the host part of an incoming URL. - * Includes the port number part. Will extract - * the host if it starts with // or it has - * a top level domain or it has at least two - * dots. - * @param string $url URL so far. The host will be - * removed. - * @return string Host part guess or false. - * @access private - */ - function _chompHost(&$url) { - if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) { - $url = $matches[3]; - return $matches[2]; - } - if (preg_match('/(.*?)(\.\.\/|\.\/|\/|\?|#|$)(.*)/', $url, $matches)) { - $tlds = SimpleUrl::getAllTopLevelDomains(); - if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } elseif (preg_match('/[a-z0-9\-]+\.[a-z0-9\-]+\.[a-z0-9\-]+/i', $matches[1])) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } - } - return false; - } - - /** - * Extracts the path information from the incoming - * URL. Strips this path from the URL. - * @param string $url URL so far. The host will be - * removed. - * @return string Path part or '/'. - * @access private - */ - function _chompPath(&$url) { - if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) { - $url = $matches[2] . $matches[3]; - return ($matches[1] ? $matches[1] : ''); - } - return ''; - } - - /** - * Strips off the request data. - * @param string $url URL so far. The request will be - * removed. - * @return string Raw request part. - * @access private - */ - function _chompRequest(&$url) { - if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } - return ''; - } - - /** - * Breaks the request down into an object. - * @param string $raw Raw request. - * @return SimpleFormEncoding Parsed data. - * @access private - */ - function _parseRequest($raw) { - $this->_raw = $raw; - $request = new SimpleGetEncoding(); - foreach (split("&", $raw) as $pair) { - if (preg_match('/(.*?)=(.*)/', $pair, $matches)) { - $request->add($matches[1], urldecode($matches[2])); - } elseif ($pair) { - $request->add($pair, ''); - } - } - return $request; - } - - /** - * Accessor for protocol part. - * @param string $default Value to use if not present. - * @return string Scheme name, e.g "http". - * @access public - */ - function getScheme($default = false) { - return $this->_scheme ? $this->_scheme : $default; - } - - /** - * Accessor for user name. - * @return string Username preceding host. - * @access public - */ - function getUsername() { - return $this->_username; - } - - /** - * Accessor for password. - * @return string Password preceding host. - * @access public - */ - function getPassword() { - return $this->_password; - } - - /** - * Accessor for hostname and port. - * @param string $default Value to use if not present. - * @return string Hostname only. - * @access public - */ - function getHost($default = false) { - return $this->_host ? $this->_host : $default; - } - - /** - * Accessor for top level domain. - * @return string Last part of host. - * @access public - */ - function getTld() { - $path_parts = pathinfo($this->getHost()); - return (isset($path_parts['extension']) ? $path_parts['extension'] : false); - } - - /** - * Accessor for port number. - * @return integer TCP/IP port number. - * @access public - */ - function getPort() { - return $this->_port; - } - - /** - * Accessor for path. - * @return string Full path including leading slash if implied. - * @access public - */ - function getPath() { - if (! $this->_path && $this->_host) { - return '/'; - } - return $this->_path; - } - - /** - * Accessor for page if any. This may be a - * directory name if ambiguious. - * @return Page name. - * @access public - */ - function getPage() { - if (! preg_match('/([^\/]*?)$/', $this->getPath(), $matches)) { - return false; - } - return $matches[1]; - } - - /** - * Gets the path to the page. - * @return string Path less the page. - * @access public - */ - function getBasePath() { - if (! preg_match('/(.*\/)[^\/]*?$/', $this->getPath(), $matches)) { - return false; - } - return $matches[1]; - } - - /** - * Accessor for fragment at end of URL after the "#". - * @return string Part after "#". - * @access public - */ - function getFragment() { - return $this->_fragment; - } - - /** - * Sets image coordinates. Set to false to clear - * them. - * @param integer $x Horizontal position. - * @param integer $y Vertical position. - * @access public - */ - function setCoordinates($x = false, $y = false) { - if (($x === false) || ($y === false)) { - $this->_x = $this->_y = false; - return; - } - $this->_x = (integer)$x; - $this->_y = (integer)$y; - } - - /** - * Accessor for horizontal image coordinate. - * @return integer X value. - * @access public - */ - function getX() { - return $this->_x; - } - - /** - * Accessor for vertical image coordinate. - * @return integer Y value. - * @access public - */ - function getY() { - return $this->_y; - } - - /** - * Accessor for current request parameters - * in URL string form. Will return teh original request - * if at all possible even if it doesn't make much - * sense. - * @return string Form is string "?a=1&b=2", etc. - * @access public - */ - function getEncodedRequest() { - if ($this->_raw) { - $encoded = $this->_raw; - } else { - $encoded = $this->_request->asUrlRequest(); - } - if ($encoded) { - return '?' . preg_replace('/^\?/', '', $encoded); - } - return ''; - } - - /** - * Adds an additional parameter to the request. - * @param string $key Name of parameter. - * @param string $value Value as string. - * @access public - */ - function addRequestParameter($key, $value) { - $this->_raw = false; - $this->_request->add($key, $value); - } - - /** - * Adds additional parameters to the request. - * @param hash/SimpleFormEncoding $parameters Additional - * parameters. - * @access public - */ - function addRequestParameters($parameters) { - $this->_raw = false; - $this->_request->merge($parameters); - } - - /** - * Clears down all parameters. - * @access public - */ - function clearRequest() { - $this->_raw = false; - $this->_request = &new SimpleGetEncoding(); - } - - /** - * Gets the frame target if present. Although - * not strictly part of the URL specification it - * acts as similarily to the browser. - * @return boolean/string Frame name or false if none. - * @access public - */ - function getTarget() { - return $this->_target; - } - - /** - * Attaches a frame target. - * @param string $frame Name of frame. - * @access public - */ - function setTarget($frame) { - $this->_raw = false; - $this->_target = $frame; - } - - /** - * Renders the URL back into a string. - * @return string URL in canonical form. - * @access public - */ - function asString() { - $path = $this->_path; - $scheme = $identity = $host = $encoded = $fragment = ''; - if ($this->_username && $this->_password) { - $identity = $this->_username . ':' . $this->_password . '@'; - } - if ($this->getHost()) { - $scheme = $this->getScheme() ? $this->getScheme() : 'http'; - $scheme .= "://"; - $host = $this->getHost(); - } - if (substr($this->_path, 0, 1) == '/') { - $path = $this->normalisePath($this->_path); - } - $encoded = $this->getEncodedRequest(); - $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; - $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); - return "$scheme$identity$host$path$encoded$fragment$coords"; - } - - /** - * Replaces unknown sections to turn a relative - * URL into an absolute one. The base URL can - * be either a string or a SimpleUrl object. - * @param string/SimpleUrl $base Base URL. - * @access public - */ - function makeAbsolute($base) { - if (! is_object($base)) { - $base = new SimpleUrl($base); - } - if ($this->getHost()) { - $scheme = $this->getScheme(); - $host = $this->getHost(); - $port = $this->getPort() ? ':' . $this->getPort() : ''; - $identity = $this->getIdentity() ? $this->getIdentity() . '@' : ''; - if (! $identity) { - $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; - } - } else { - $scheme = $base->getScheme(); - $host = $base->getHost(); - $port = $base->getPort() ? ':' . $base->getPort() : ''; - $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; - } - $path = $this->normalisePath($this->_extractAbsolutePath($base)); - $encoded = $this->getEncodedRequest(); - $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; - $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); - return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords"); - } - - /** - * Replaces unknown sections of the path with base parts - * to return a complete absolute one. - * @param string/SimpleUrl $base Base URL. - * @param string Absolute path. - * @access private - */ - function _extractAbsolutePath($base) { - if ($this->getHost()) { - return $this->_path; - } - if (! $this->_isRelativePath($this->_path)) { - return $this->_path; - } - if ($this->_path) { - return $base->getBasePath() . $this->_path; - } - return $base->getPath(); - } - - /** - * Simple test to see if a path part is relative. - * @param string $path Path to test. - * @return boolean True if starts with a "/". - * @access private - */ - function _isRelativePath($path) { - return (substr($path, 0, 1) != '/'); - } - - /** - * Extracts the username and password for use in rendering - * a URL. - * @return string/boolean Form of username:password or false. - * @access public - */ - function getIdentity() { - if ($this->_username && $this->_password) { - return $this->_username . ':' . $this->_password; - } - return false; - } - - /** - * Replaces . and .. sections of the path. - * @param string $path Unoptimised path. - * @return string Path with dots removed if possible. - * @access public - */ - function normalisePath($path) { - $path = preg_replace('|/\./|', '/', $path); - return preg_replace('|/[^/]+/\.\./|', '/', $path); - } - - /** - * A pipe seperated list of all TLDs that result in two part - * domain names. - * @return string Pipe separated list. - * @access public - * @static - */ - function getAllTopLevelDomains() { - return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum'; - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/user_agent.php b/tests/simpletest/user_agent.php deleted file mode 100644 index b3f6f057e..000000000 --- a/tests/simpletest/user_agent.php +++ /dev/null @@ -1,332 +0,0 @@ -_cookie_jar = &new SimpleCookieJar(); - $this->_authenticator = &new SimpleAuthenticator(); - } - - /** - * Removes expired and temporary cookies as if - * the browser was closed and re-opened. Authorisation - * has to be obtained again as well. - * @param string/integer $date Time when session restarted. - * If omitted then all persistent - * cookies are kept. - * @access public - */ - function restart($date = false) { - $this->_cookie_jar->restartSession($date); - $this->_authenticator->restartSession(); - } - - /** - * Adds a header to every fetch. - * @param string $header Header line to add to every - * request until cleared. - * @access public - */ - function addHeader($header) { - $this->_additional_headers[] = $header; - } - - /** - * Ages the cookies by the specified time. - * @param integer $interval Amount in seconds. - * @access public - */ - function ageCookies($interval) { - $this->_cookie_jar->agePrematurely($interval); - } - - /** - * Sets an additional cookie. If a cookie has - * the same name and path it is replaced. - * @param string $name Cookie key. - * @param string $value Value of cookie. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $this->_cookie_jar->setCookie($name, $value, $host, $path, $expiry); - } - - /** - * Reads the most specific cookie value from the - * browser cookies. - * @param string $host Host to search. - * @param string $path Applicable path. - * @param string $name Name of cookie to read. - * @return string False if not present, else the - * value as a string. - * @access public - */ - function getCookieValue($host, $path, $name) { - return $this->_cookie_jar->getCookieValue($host, $path, $name); - } - - /** - * Reads the current cookies within the base URL. - * @param string $name Key of cookie to find. - * @param SimpleUrl $base Base URL to search from. - * @return string/boolean Null if there is no base URL, false - * if the cookie is not set. - * @access public - */ - function getBaseCookieValue($name, $base) { - if (! $base) { - return null; - } - return $this->getCookieValue($base->getHost(), $base->getPath(), $name); - } - - /** - * Switches off cookie sending and recieving. - * @access public - */ - function ignoreCookies() { - $this->_cookies_enabled = false; - } - - /** - * Switches back on the cookie sending and recieving. - * @access public - */ - function useCookies() { - $this->_cookies_enabled = true; - } - - /** - * Sets the socket timeout for opening a connection. - * @param integer $timeout Maximum time in seconds. - * @access public - */ - function setConnectionTimeout($timeout) { - $this->_connection_timeout = $timeout; - } - - /** - * Sets the maximum number of redirects before - * a page will be loaded anyway. - * @param integer $max Most hops allowed. - * @access public - */ - function setMaximumRedirects($max) { - $this->_max_redirects = $max; - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set URL - * to false to disable. - * @param string $proxy Proxy URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - * @access public - */ - function useProxy($proxy, $username, $password) { - if (! $proxy) { - $this->_proxy = false; - return; - } - if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) { - $proxy = 'http://'. $proxy; - } - $this->_proxy = &new SimpleUrl($proxy); - $this->_proxy_username = $username; - $this->_proxy_password = $password; - } - - /** - * Test to see if the redirect limit is passed. - * @param integer $redirects Count so far. - * @return boolean True if over. - * @access private - */ - function _isTooManyRedirects($redirects) { - return ($redirects > $this->_max_redirects); - } - - /** - * Sets the identity for the current realm. - * @param string $host Host to which realm applies. - * @param string $realm Full name of realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @access public - */ - function setIdentity($host, $realm, $username, $password) { - $this->_authenticator->setIdentityForRealm($host, $realm, $username, $password); - } - - /** - * Fetches a URL as a response object. Will keep trying if redirected. - * It will also collect authentication realm information. - * @param string/SimpleUrl $url Target to fetch. - * @param SimpleEncoding $encoding Additional parameters for request. - * @return SimpleHttpResponse Hopefully the target page. - * @access public - */ - function &fetchResponse($url, $encoding) { - if ($encoding->getMethod() != 'POST') { - $url->addRequestParameters($encoding); - $encoding->clear(); - } - $response = &$this->_fetchWhileRedirected($url, $encoding); - if ($headers = $response->getHeaders()) { - if ($headers->isChallenge()) { - $this->_authenticator->addRealm( - $url, - $headers->getAuthentication(), - $headers->getRealm()); - } - } - return $response; - } - - /** - * Fetches the page until no longer redirected or - * until the redirect limit runs out. - * @param SimpleUrl $url Target to fetch. - * @param SimpelFormEncoding $encoding Additional parameters for request. - * @return SimpleHttpResponse Hopefully the target page. - * @access private - */ - function &_fetchWhileRedirected($url, $encoding) { - $redirects = 0; - do { - $response = &$this->_fetch($url, $encoding); - if ($response->isError()) { - return $response; - } - $headers = $response->getHeaders(); - $location = new SimpleUrl($headers->getLocation()); - $url = $location->makeAbsolute($url); - if ($this->_cookies_enabled) { - $headers->writeCookiesToJar($this->_cookie_jar, $url); - } - if (! $headers->isRedirect()) { - break; - } - $encoding = new SimpleGetEncoding(); - } while (! $this->_isTooManyRedirects(++$redirects)); - return $response; - } - - /** - * Actually make the web request. - * @param SimpleUrl $url Target to fetch. - * @param SimpleFormEncoding $encoding Additional parameters for request. - * @return SimpleHttpResponse Headers and hopefully content. - * @access protected - */ - function &_fetch($url, $encoding) { - $request = &$this->_createRequest($url, $encoding); - $response = &$request->fetch($this->_connection_timeout); - return $response; - } - - /** - * Creates a full page request. - * @param SimpleUrl $url Target to fetch as url object. - * @param SimpleFormEncoding $encoding POST/GET parameters. - * @return SimpleHttpRequest New request. - * @access private - */ - function &_createRequest($url, $encoding) { - $request = &$this->_createHttpRequest($url, $encoding); - $this->_addAdditionalHeaders($request); - if ($this->_cookies_enabled) { - $request->readCookiesFromJar($this->_cookie_jar, $url); - } - $this->_authenticator->addHeaders($request, $url); - return $request; - } - - /** - * Builds the appropriate HTTP request object. - * @param SimpleUrl $url Target to fetch as url object. - * @param SimpleFormEncoding $parameters POST/GET parameters. - * @return SimpleHttpRequest New request object. - * @access protected - */ - function &_createHttpRequest($url, $encoding) { - $request = &new SimpleHttpRequest($this->_createRoute($url), $encoding); - return $request; - } - - /** - * Sets up either a direct route or via a proxy. - * @param SimpleUrl $url Target to fetch as url object. - * @return SimpleRoute Route to take to fetch URL. - * @access protected - */ - function &_createRoute($url) { - if ($this->_proxy) { - $route = &new SimpleProxyRoute( - $url, - $this->_proxy, - $this->_proxy_username, - $this->_proxy_password); - } else { - $route = &new SimpleRoute($url); - } - return $route; - } - - /** - * Adds additional manual headers. - * @param SimpleHttpRequest $request Outgoing request. - * @access private - */ - function _addAdditionalHeaders(&$request) { - foreach ($this->_additional_headers as $header) { - $request->addHeaderLine($header); - } - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/web_tester.php b/tests/simpletest/web_tester.php deleted file mode 100644 index 40b161291..000000000 --- a/tests/simpletest/web_tester.php +++ /dev/null @@ -1,1541 +0,0 @@ -SimpleExpectation($message); - if (is_array($value)) { - sort($value); - } - $this->_value = $value; - } - - /** - * Tests the expectation. True if it matches - * a string value or an array value in any order. - * @param mixed $compare Comparison value. False for - * an unset field. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - if ($this->_value === false) { - return ($compare === false); - } - if ($this->_isSingle($this->_value)) { - return $this->_testSingle($compare); - } - if (is_array($this->_value)) { - return $this->_testMultiple($compare); - } - return false; - } - - /** - * Tests for valid field comparisons with a single option. - * @param mixed $value Value to type check. - * @return boolean True if integer, string or float. - * @access private - */ - function _isSingle($value) { - return is_string($value) || is_integer($value) || is_float($value); - } - - /** - * String comparison for simple field with a single option. - * @param mixed $compare String to test against. - * @returns boolean True if matching. - * @access private - */ - function _testSingle($compare) { - if (is_array($compare) && count($compare) == 1) { - $compare = $compare[0]; - } - if (! $this->_isSingle($compare)) { - return false; - } - return ($this->_value == $compare); - } - - /** - * List comparison for multivalue field. - * @param mixed $compare List in any order to test against. - * @returns boolean True if matching. - * @access private - */ - function _testMultiple($compare) { - if (is_string($compare)) { - $compare = array($compare); - } - if (! is_array($compare)) { - return false; - } - sort($compare); - return ($this->_value === $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = &$this->_getDumper(); - if (is_array($compare)) { - sort($compare); - } - if ($this->test($compare)) { - return "Field expectation [" . $dumper->describeValue($this->_value) . "]"; - } else { - return "Field expectation [" . $dumper->describeValue($this->_value) . - "] fails with [" . - $dumper->describeValue($compare) . "] " . - $dumper->describeDifference($this->_value, $compare); - } - } -} - -/** - * Test for a specific HTTP header within a header block. - * @package SimpleTest - * @subpackage WebTester - */ -class HttpHeaderExpectation extends SimpleExpectation { - var $_expected_header; - var $_expected_value; - - /** - * Sets the field and value to compare against. - * @param string $header Case insenstive trimmed header name. - * @param mixed $value Optional value to compare. If not - * given then any value will match. If - * an expectation object then that will - * be used instead. - * @param string $message Optiona message override. Can use %s as - * a placeholder for the original message. - */ - function HttpHeaderExpectation($header, $value = false, $message = '%s') { - $this->SimpleExpectation($message); - $this->_expected_header = $this->_normaliseHeader($header); - $this->_expected_value = $value; - } - - /** - * Accessor for aggregated object. - * @return mixed Expectation set in constructor. - * @access protected - */ - function _getExpectation() { - return $this->_expected_value; - } - - /** - * Removes whitespace at ends and case variations. - * @param string $header Name of header. - * @param string Trimmed and lowecased header - * name. - * @access private - */ - function _normaliseHeader($header) { - return strtolower(trim($header)); - } - - /** - * Tests the expectation. True if it matches - * a string value or an array value in any order. - * @param mixed $compare Raw header block to search. - * @return boolean True if header present. - * @access public - */ - function test($compare) { - return is_string($this->_findHeader($compare)); - } - - /** - * Searches the incoming result. Will extract the matching - * line as text. - * @param mixed $compare Raw header block to search. - * @return string Matching header line. - * @access protected - */ - function _findHeader($compare) { - $lines = split("\r\n", $compare); - foreach ($lines as $line) { - if ($this->_testHeaderLine($line)) { - return $line; - } - } - return false; - } - - /** - * Compares a single header line against the expectation. - * @param string $line A single line to compare. - * @return boolean True if matched. - * @access private - */ - function _testHeaderLine($line) { - if (count($parsed = split(':', $line, 2)) < 2) { - return false; - } - list($header, $value) = $parsed; - if ($this->_normaliseHeader($header) != $this->_expected_header) { - return false; - } - return $this->_testHeaderValue($value, $this->_expected_value); - } - - /** - * Tests the value part of the header. - * @param string $value Value to test. - * @param mixed $expected Value to test against. - * @return boolean True if matched. - * @access protected - */ - function _testHeaderValue($value, $expected) { - if ($expected === false) { - return true; - } - if (SimpleExpectation::isExpectation($expected)) { - return $expected->test(trim($value)); - } - return (trim($value) == trim($expected)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Raw header block to search. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if (SimpleExpectation::isExpectation($this->_expected_value)) { - $message = $this->_expected_value->overlayMessage($compare, $this->_getDumper()); - } else { - $message = $this->_expected_header . - ($this->_expected_value ? ': ' . $this->_expected_value : ''); - } - if (is_string($line = $this->_findHeader($compare))) { - return "Searching for header [$message] found [$line]"; - } else { - return "Failed to find header [$message]"; - } - } -} - -/** - * Test for a specific HTTP header within a header block that - * should not be found. - * @package SimpleTest - * @subpackage WebTester - */ -class NoHttpHeaderExpectation extends HttpHeaderExpectation { - var $_expected_header; - var $_expected_value; - - /** - * Sets the field and value to compare against. - * @param string $unwanted Case insenstive trimmed header name. - * @param string $message Optiona message override. Can use %s as - * a placeholder for the original message. - */ - function NoHttpHeaderExpectation($unwanted, $message = '%s') { - $this->HttpHeaderExpectation($unwanted, false, $message); - } - - /** - * Tests that the unwanted header is not found. - * @param mixed $compare Raw header block to search. - * @return boolean True if header present. - * @access public - */ - function test($compare) { - return ($this->_findHeader($compare) === false); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Raw header block to search. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $expectation = $this->_getExpectation(); - if (is_string($line = $this->_findHeader($compare))) { - return "Found unwanted header [$expectation] with [$line]"; - } else { - return "Did not find unwanted header [$expectation]"; - } - } -} - -/** - * Test for a text substring. - * @package SimpleTest - * @subpackage UnitTester - */ -class TextExpectation extends SimpleExpectation { - var $_substring; - - /** - * Sets the value to compare against. - * @param string $substring Text to search for. - * @param string $message Customised message on failure. - * @access public - */ - function TextExpectation($substring, $message = '%s') { - $this->SimpleExpectation($message); - $this->_substring = $substring; - } - - /** - * Accessor for the substring. - * @return string Text to match. - * @access protected - */ - function _getSubstring() { - return $this->_substring; - } - - /** - * Tests the expectation. True if the text contains the - * substring. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (strpos($compare, $this->_substring) !== false); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return $this->_describeTextMatch($this->_getSubstring(), $compare); - } else { - $dumper = &$this->_getDumper(); - return "Text [" . $this->_getSubstring() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } - } - - /** - * Describes a pattern match including the string - * found and it's position. - * @param string $substring Text to search for. - * @param string $subject Subject to search. - * @access protected - */ - function _describeTextMatch($substring, $subject) { - $position = strpos($subject, $substring); - $dumper = &$this->_getDumper(); - return "Text [$substring] detected at character [$position] in [" . - $dumper->describeValue($subject) . "] in region [" . - $dumper->clipString($subject, 100, $position) . "]"; - } -} - -/** - * Fail if a substring is detected within the - * comparison text. - * @package SimpleTest - * @subpackage UnitTester - */ -class NoTextExpectation extends TextExpectation { - - /** - * Sets the reject pattern - * @param string $substring Text to search for. - * @param string $message Customised message on failure. - * @access public - */ - function NoTextExpectation($substring, $message = '%s') { - $this->TextExpectation($substring, $message); - } - - /** - * Tests the expectation. False if the substring appears - * in the text. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param string $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - $dumper = &$this->_getDumper(); - return "Text [" . $this->_getSubstring() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } else { - return $this->_describeTextMatch($this->_getSubstring(), $compare); - } - } -} - -/** - * Test case for testing of web pages. Allows - * fetching of pages, parsing of HTML and - * submitting forms. - * @package SimpleTest - * @subpackage WebTester - */ -class WebTestCase extends SimpleTestCase { - var $_browser; - var $_ignore_errors = false; - - /** - * Creates an empty test case. Should be subclassed - * with test methods for a functional test case. - * @param string $label Name of test case. Will use - * the class name if none specified. - * @access public - */ - function WebTestCase($label = false) { - $this->SimpleTestCase($label); - } - - /** - * Announces the start of the test. - * @param string $method Test method just started. - * @access public - */ - function before($method) { - parent::before($method); - $this->setBrowser($this->createBrowser()); - } - - /** - * Announces the end of the test. Includes private clean up. - * @param string $method Test method just finished. - * @access public - */ - function after($method) { - $this->unsetBrowser(); - parent::after($method); - } - - /** - * Gets a current browser reference for setting - * special expectations or for detailed - * examination of page fetches. - * @return SimpleBrowser Current test browser object. - * @access public - */ - function &getBrowser() { - return $this->_browser; - } - - /** - * Gets a current browser reference for setting - * special expectations or for detailed - * examination of page fetches. - * @param SimpleBrowser $browser New test browser object. - * @access public - */ - function setBrowser(&$browser) { - return $this->_browser = &$browser; - } - - /** - * Clears the current browser reference to help the - * PHP garbage collector. - * @access public - */ - function unsetBrowser() { - unset($this->_browser); - } - - /** - * Creates a new default web browser object. - * Will be cleared at the end of the test method. - * @return TestBrowser New browser. - * @access public - */ - function &createBrowser() { - $browser = &new SimpleBrowser(); - return $browser; - } - - /** - * Gets the last response error. - * @return string Last low level HTTP error. - * @access public - */ - function getTransportError() { - return $this->_browser->getTransportError(); - } - - /** - * Accessor for the currently selected URL. - * @return string Current location or false if - * no page yet fetched. - * @access public - */ - function getUrl() { - return $this->_browser->getUrl(); - } - - /** - * Dumps the current request for debugging. - * @access public - */ - function showRequest() { - $this->dump($this->_browser->getRequest()); - } - - /** - * Dumps the current HTTP headers for debugging. - * @access public - */ - function showHeaders() { - $this->dump($this->_browser->getHeaders()); - } - - /** - * Dumps the current HTML source for debugging. - * @access public - */ - function showSource() { - $this->dump($this->_browser->getContent()); - } - - /** - * Dumps the visible text only for debugging. - * @access public - */ - function showText() { - $this->dump(wordwrap($this->_browser->getContentAsText(), 80)); - } - - /** - * Simulates the closing and reopening of the browser. - * Temporary cookies will be discarded and timed - * cookies will be expired if later than the - * specified time. - * @param string/integer $date Time when session restarted. - * If ommitted then all persistent - * cookies are kept. Time is either - * Cookie format string or timestamp. - * @access public - */ - function restart($date = false) { - if ($date === false) { - $date = time(); - } - $this->_browser->restart($date); - } - - /** - * Moves cookie expiry times back into the past. - * Useful for testing timeouts and expiries. - * @param integer $interval Amount to age in seconds. - * @access public - */ - function ageCookies($interval) { - $this->_browser->ageCookies($interval); - } - - /** - * Disables frames support. Frames will not be fetched - * and the frameset page will be used instead. - * @access public - */ - function ignoreFrames() { - $this->_browser->ignoreFrames(); - } - - /** - * Switches off cookie sending and recieving. - * @access public - */ - function ignoreCookies() { - $this->_browser->ignoreCookies(); - } - - /** - * Skips errors for the next request only. You might - * want to confirm that a page is unreachable for - * example. - * @access public - */ - function ignoreErrors() { - $this->_ignore_errors = true; - } - - /** - * Issues a fail if there is a transport error anywhere - * in the current frameset. Only one such error is - * reported. - * @param string/boolean $result HTML or failure. - * @return string/boolean $result Passes through result. - * @access private - */ - function _failOnError($result) { - if (! $this->_ignore_errors) { - if ($error = $this->_browser->getTransportError()) { - $this->fail($error); - } - } - $this->_ignore_errors = false; - return $result; - } - - /** - * Adds a header to every fetch. - * @param string $header Header line to add to every - * request until cleared. - * @access public - */ - function addHeader($header) { - $this->_browser->addHeader($header); - } - - /** - * Sets the maximum number of redirects before - * the web page is loaded regardless. - * @param integer $max Maximum hops. - * @access public - */ - function setMaximumRedirects($max) { - if (! $this->_browser) { - trigger_error( - 'Can only set maximum redirects in a test method, setUp() or tearDown()'); - } - $this->_browser->setMaximumRedirects($max); - } - - /** - * Sets the socket timeout for opening a connection and - * receiving at least one byte of information. - * @param integer $timeout Maximum time in seconds. - * @access public - */ - function setConnectionTimeout($timeout) { - $this->_browser->setConnectionTimeout($timeout); - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set URL - * to false to disable. - * @param string $proxy Proxy URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - * @access public - */ - function useProxy($proxy, $username = false, $password = false) { - $this->_browser->useProxy($proxy, $username, $password); - } - - /** - * Fetches a page into the page buffer. If - * there is no base for the URL then the - * current base URL is used. After the fetch - * the base URL reflects the new location. - * @param string $url URL to fetch. - * @param hash $parameters Optional additional GET data. - * @return boolean/string Raw page on success. - * @access public - */ - function get($url, $parameters = false) { - return $this->_failOnError($this->_browser->get($url, $parameters)); - } - - /** - * Fetches a page by POST into the page buffer. - * If there is no base for the URL then the - * current base URL is used. After the fetch - * the base URL reflects the new location. - * @param string $url URL to fetch. - * @param hash $parameters Optional additional GET data. - * @return boolean/string Raw page on success. - * @access public - */ - function post($url, $parameters = false) { - return $this->_failOnError($this->_browser->post($url, $parameters)); - } - - /** - * Does a HTTP HEAD fetch, fetching only the page - * headers. The current base URL is unchanged by this. - * @param string $url URL to fetch. - * @param hash $parameters Optional additional GET data. - * @return boolean True on success. - * @access public - */ - function head($url, $parameters = false) { - return $this->_failOnError($this->_browser->head($url, $parameters)); - } - - /** - * Equivalent to hitting the retry button on the - * browser. Will attempt to repeat the page fetch. - * @return boolean True if fetch succeeded. - * @access public - */ - function retry() { - return $this->_failOnError($this->_browser->retry()); - } - - /** - * Equivalent to hitting the back button on the - * browser. - * @return boolean True if history entry and - * fetch succeeded. - * @access public - */ - function back() { - return $this->_failOnError($this->_browser->back()); - } - - /** - * Equivalent to hitting the forward button on the - * browser. - * @return boolean True if history entry and - * fetch succeeded. - * @access public - */ - function forward() { - return $this->_failOnError($this->_browser->forward()); - } - - /** - * Retries a request after setting the authentication - * for the current realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @return boolean/string HTML on successful fetch. Note - * that authentication may still have - * failed. - * @access public - */ - function authenticate($username, $password) { - return $this->_failOnError( - $this->_browser->authenticate($username, $password)); - } - - /** - * Gets the cookie value for the current browser context. - * @param string $name Name of cookie. - * @return string Value of cookie or false if unset. - * @access public - */ - function getCookie($name) { - return $this->_browser->getCurrentCookieValue($name); - } - - /** - * Sets a cookie in the current browser. - * @param string $name Name of cookie. - * @param string $value Cookie value. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $this->_browser->setCookie($name, $value, $host, $path, $expiry); - } - - /** - * Accessor for current frame focus. Will be - * false if no frame has focus. - * @return integer/string/boolean Label if any, otherwise - * the position in the frameset - * or false if none. - * @access public - */ - function getFrameFocus() { - return $this->_browser->getFrameFocus(); - } - - /** - * Sets the focus by index. The integer index starts from 1. - * @param integer $choice Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocusByIndex($choice) { - return $this->_browser->setFrameFocusByIndex($choice); - } - - /** - * Sets the focus by name. - * @param string $name Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocus($name) { - return $this->_browser->setFrameFocus($name); - } - - /** - * Clears the frame focus. All frames will be searched - * for content. - * @access public - */ - function clearFrameFocus() { - return $this->_browser->clearFrameFocus(); - } - - /** - * Clicks a visible text item. Will first try buttons, - * then links and then images. - * @param string $label Visible text or alt text. - * @return string/boolean Raw page or false. - * @access public - */ - function click($label) { - return $this->_failOnError($this->_browser->click($label)); - } - - /** - * Checks for a click target. - * @param string $label Visible text or alt text. - * @return boolean True if click target. - * @access public - */ - function assertClickable($label, $message = '%s') { - return $this->assertTrue( - $this->_browser->isClickable($label), - sprintf($message, "Click target [$label] should exist")); - } - - /** - * Clicks the submit button by label. The owning - * form will be submitted by this. - * @param string $label Button label. An unlabeled - * button can be triggered by 'Submit'. - * @param hash $additional Additional form values. - * @return boolean/string Page on success, else false. - * @access public - */ - function clickSubmit($label = 'Submit', $additional = false) { - return $this->_failOnError( - $this->_browser->clickSubmit($label, $additional)); - } - - /** - * Clicks the submit button by name attribute. The owning - * form will be submitted by this. - * @param string $name Name attribute of button. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickSubmitByName($name, $additional = false) { - return $this->_failOnError( - $this->_browser->clickSubmitByName($name, $additional)); - } - - /** - * Clicks the submit button by ID attribute. The owning - * form will be submitted by this. - * @param string $id ID attribute of button. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickSubmitById($id, $additional = false) { - return $this->_failOnError( - $this->_browser->clickSubmitById($id, $additional)); - } - - /** - * Checks for a valid button label. - * @param string $label Visible text. - * @return boolean True if click target. - * @access public - */ - function assertSubmit($label, $message = '%s') { - return $this->assertTrue( - $this->_browser->isSubmit($label), - sprintf($message, "Submit button [$label] should exist")); - } - - /** - * Clicks the submit image by some kind of label. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $label Alt attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickImage($label, $x = 1, $y = 1, $additional = false) { - return $this->_failOnError( - $this->_browser->clickImage($label, $x, $y, $additional)); - } - - /** - * Clicks the submit image by the name. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $name Name attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickImageByName($name, $x = 1, $y = 1, $additional = false) { - return $this->_failOnError( - $this->_browser->clickImageByName($name, $x, $y, $additional)); - } - - /** - * Clicks the submit image by ID attribute. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param integer/string $id ID attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickImageById($id, $x = 1, $y = 1, $additional = false) { - return $this->_failOnError( - $this->_browser->clickImageById($id, $x, $y, $additional)); - } - - /** - * Checks for a valid image with atht alt text or title. - * @param string $label Visible text. - * @return boolean True if click target. - * @access public - */ - function assertImage($label, $message = '%s') { - return $this->assertTrue( - $this->_browser->isImage($label), - sprintf($message, "Image with text [$label] should exist")); - } - - /** - * Submits a form by the ID. - * @param string $id Form ID. No button information - * is submitted this way. - * @return boolean/string Page on success. - * @access public - */ - function submitFormById($id) { - return $this->_failOnError($this->_browser->submitFormById($id)); - } - - /** - * Follows a link by name. Will click the first link - * found with this link text by default, or a later - * one if an index is given. Match is case insensitive - * with normalised space. - * @param string $label Text between the anchor tags. - * @param integer $index Link position counting from zero. - * @return boolean/string Page on success. - * @access public - */ - function clickLink($label, $index = 0) { - return $this->_failOnError($this->_browser->clickLink($label, $index)); - } - - /** - * Follows a link by id attribute. - * @param string $id ID attribute value. - * @return boolean/string Page on success. - * @access public - */ - function clickLinkById($id) { - return $this->_failOnError($this->_browser->clickLinkById($id)); - } - - /** - * Tests for the presence of a link label. Match is - * case insensitive with normalised space. - * @param string $label Text between the anchor tags. - * @param mixed $expected Expected URL or expectation object. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link present. - * @access public - */ - function assertLink($label, $expected = true, $message = '%s') { - $url = $this->_browser->getLink($label); - if ($expected === true || ($expected !== true && $url === false)) { - return $this->assertTrue($url !== false, sprintf($message, "Link [$label] should exist")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $expected = new IdenticalExpectation($expected); - } - return $this->assert($expected, $url->asString(), sprintf($message, "Link [$label] should match")); - } - - /** - * Tests for the non-presence of a link label. Match is - * case insensitive with normalised space. - * @param string/integer $label Text between the anchor tags - * or ID attribute. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link missing. - * @access public - */ - function assertNoLink($label, $message = '%s') { - return $this->assertTrue( - $this->_browser->getLink($label) === false, - sprintf($message, "Link [$label] should not exist")); - } - - /** - * Tests for the presence of a link id attribute. - * @param string $id Id attribute value. - * @param mixed $expected Expected URL or expectation object. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link present. - * @access public - */ - function assertLinkById($id, $expected = true, $message = '%s') { - $url = $this->_browser->getLinkById($id); - if ($expected === true) { - return $this->assertTrue($url !== false, sprintf($message, "Link ID [$id] should exist")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $expected = new IdenticalExpectation($expected); - } - return $this->assert($expected, $url->asString(), sprintf($message, "Link ID [$id] should match")); - } - - /** - * Tests for the non-presence of a link label. Match is - * case insensitive with normalised space. - * @param string $id Id attribute value. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link missing. - * @access public - */ - function assertNoLinkById($id, $message = '%s') { - return $this->assertTrue( - $this->_browser->getLinkById($id) === false, - sprintf($message, "Link ID [$id] should not exist")); - } - - /** - * Sets all form fields with that label, or name if there - * is no label attached. - * @param string $name Name of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setField($label, $value, $position=false) { - return $this->_browser->setField($label, $value, $position); - } - - /** - * Sets all form fields with that name. - * @param string $name Name of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldByName($name, $value, $position=false) { - return $this->_browser->setFieldByName($name, $value, $position); - } - - /** - * Sets all form fields with that id. - * @param string/integer $id Id of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldById($id, $value) { - return $this->_browser->setFieldById($id, $value); - } - - /** - * Confirms that the form element is currently set - * to the expected value. A missing form will always - * fail. If no value is given then only the existence - * of the field is checked. - * @param string $name Name of field in forms. - * @param mixed $expected Expected string/array value or - * false for unset fields. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertField($label, $expected = true, $message = '%s') { - $value = $this->_browser->getField($label); - return $this->_assertFieldValue($label, $value, $expected, $message); - } - - /** - * Confirms that the form element is currently set - * to the expected value. A missing form element will always - * fail. If no value is given then only the existence - * of the field is checked. - * @param string $name Name of field in forms. - * @param mixed $expected Expected string/array value or - * false for unset fields. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertFieldByName($name, $expected = true, $message = '%s') { - $value = $this->_browser->getFieldByName($name); - return $this->_assertFieldValue($name, $value, $expected, $message); - } - - /** - * Confirms that the form element is currently set - * to the expected value. A missing form will always - * fail. If no ID is given then only the existence - * of the field is checked. - * @param string/integer $id Name of field in forms. - * @param mixed $expected Expected string/array value or - * false for unset fields. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertFieldById($id, $expected = true, $message = '%s') { - $value = $this->_browser->getFieldById($id); - return $this->_assertFieldValue($id, $value, $expected, $message); - } - - /** - * Tests the field value against the expectation. - * @param string $identifier Name, ID or label. - * @param mixed $value Current field value. - * @param mixed $expected Expected value to match. - * @param string $message Failure message. - * @return boolean True if pass - * @access protected - */ - function _assertFieldValue($identifier, $value, $expected, $message) { - if ($expected === true) { - return $this->assertTrue( - isset($value), - sprintf($message, "Field [$identifier] should exist")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $identifier = str_replace('%', '%%', $identifier); - $expected = new FieldExpectation( - $expected, - "Field [$identifier] should match with [%s]"); - } - return $this->assert($expected, $value, $message); - } - - /** - * Checks the response code against a list - * of possible values. - * @param array $responses Possible responses for a pass. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertResponse($responses, $message = '%s') { - $responses = (is_array($responses) ? $responses : array($responses)); - $code = $this->_browser->getResponseCode(); - $message = sprintf($message, "Expecting response in [" . - implode(", ", $responses) . "] got [$code]"); - return $this->assertTrue(in_array($code, $responses), $message); - } - - /** - * Checks the mime type against a list - * of possible values. - * @param array $types Possible mime types for a pass. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertMime($types, $message = '%s') { - $types = (is_array($types) ? $types : array($types)); - $type = $this->_browser->getMimeType(); - $message = sprintf($message, "Expecting mime type in [" . - implode(", ", $types) . "] got [$type]"); - return $this->assertTrue(in_array($type, $types), $message); - } - - /** - * Attempt to match the authentication type within - * the security realm we are currently matching. - * @param string $authentication Usually basic. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertAuthentication($authentication = false, $message = '%s') { - if (! $authentication) { - $message = sprintf($message, "Expected any authentication type, got [" . - $this->_browser->getAuthentication() . "]"); - return $this->assertTrue( - $this->_browser->getAuthentication(), - $message); - } else { - $message = sprintf($message, "Expected authentication [$authentication] got [" . - $this->_browser->getAuthentication() . "]"); - return $this->assertTrue( - strtolower($this->_browser->getAuthentication()) == strtolower($authentication), - $message); - } - } - - /** - * Checks that no authentication is necessary to view - * the desired page. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoAuthentication($message = '%s') { - $message = sprintf($message, "Expected no authentication type, got [" . - $this->_browser->getAuthentication() . "]"); - return $this->assertFalse($this->_browser->getAuthentication(), $message); - } - - /** - * Attempts to match the current security realm. - * @param string $realm Name of security realm. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertRealm($realm, $message = '%s') { - if (! SimpleExpectation::isExpectation($realm)) { - $realm = new EqualExpectation($realm); - } - return $this->assert( - $realm, - $this->_browser->getRealm(), - "Expected realm -> $message"); - } - - /** - * Checks each header line for the required value. If no - * value is given then only an existence check is made. - * @param string $header Case insensitive header name. - * @param mixed $value Case sensitive trimmed string to - * match against. An expectation object - * can be used for pattern matching. - * @return boolean True if pass. - * @access public - */ - function assertHeader($header, $value = false, $message = '%s') { - return $this->assert( - new HttpHeaderExpectation($header, $value), - $this->_browser->getHeaders(), - $message); - } - - /** - * @deprecated - */ - function assertHeaderPattern($header, $pattern, $message = '%s') { - return $this->assert( - new HttpHeaderExpectation($header, new PatternExpectation($pattern)), - $this->_browser->getHeaders(), - $message); - } - - /** - * Confirms that the header type has not been received. - * Only the landing page is checked. If you want to check - * redirect pages, then you should limit redirects so - * as to capture the page you want. - * @param string $header Case insensitive header name. - * @return boolean True if pass. - * @access public - */ - function assertNoHeader($header, $message = '%s') { - return $this->assert( - new NoHttpHeaderExpectation($header), - $this->_browser->getHeaders(), - $message); - } - - /** - * @deprecated - */ - function assertNoUnwantedHeader($header, $message = '%s') { - return $this->assertNoHeader($header, $message); - } - - /** - * Tests the text between the title tags. - * @param string/SimpleExpectation $title Expected title. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertTitle($title = false, $message = '%s') { - if (! SimpleExpectation::isExpectation($title)) { - $title = new EqualExpectation($title); - } - return $this->assert($title, $this->_browser->getTitle(), $message); - } - - /** - * Will trigger a pass if the text is found in the plain - * text form of the page. - * @param string $text Text to look for. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertText($text, $message = '%s') { - return $this->assert( - new TextExpectation($text), - $this->_browser->getContentAsText(), - $message); - } - - /** - * @deprecated - */ - function assertWantedText($text, $message = '%s') { - return $this->assertText($text, $message); - } - - /** - * Will trigger a pass if the text is not found in the plain - * text form of the page. - * @param string $text Text to look for. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoText($text, $message = '%s') { - return $this->assert( - new NoTextExpectation($text), - $this->_browser->getContentAsText(), - $message); - } - - /** - * @deprecated - */ - function assertNoUnwantedText($text, $message = '%s') { - return $this->assertNoText($text, $message); - } - - /** - * Will trigger a pass if the Perl regex pattern - * is found in the raw content. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertPattern($pattern, $message = '%s') { - return $this->assert( - new PatternExpectation($pattern), - $this->_browser->getContent(), - $message); - } - - /** - * @deprecated - */ - function assertWantedPattern($pattern, $message = '%s') { - return $this->assertPattern($pattern, $message); - } - - /** - * Will trigger a pass if the perl regex pattern - * is not present in raw content. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoPattern($pattern, $message = '%s') { - return $this->assert( - new NoPatternExpectation($pattern), - $this->_browser->getContent(), - $message); - } - - /** - * @deprecated - */ - function assertNoUnwantedPattern($pattern, $message = '%s') { - return $this->assertNoPattern($pattern, $message); - } - - /** - * Checks that a cookie is set for the current page - * and optionally checks the value. - * @param string $name Name of cookie to test. - * @param string $expected Expected value as a string or - * false if any value will do. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertCookie($name, $expected = false, $message = '%s') { - $value = $this->getCookie($name); - if (! $expected) { - return $this->assertTrue( - $value, - sprintf($message, "Expecting cookie [$name]")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $expected = new EqualExpectation($expected); - } - return $this->assert($expected, $value, "Expecting cookie [$name] -> $message"); - } - - /** - * Checks that no cookie is present or that it has - * been successfully cleared. - * @param string $name Name of cookie to test. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoCookie($name, $message = '%s') { - return $this->assertTrue( - $this->getCookie($name) === false, - sprintf($message, "Not expecting cookie [$name]")); - } - - /** - * Called from within the test methods to register - * passes and failures. - * @param boolean $result Pass on true. - * @param string $message Message to display describing - * the test state. - * @return boolean True on pass - * @access public - */ - function assertTrue($result, $message = false) { - return $this->assert(new TrueExpectation(), $result, $message); - } - - /** - * Will be true on false and vice versa. False - * is the PHP definition of false, so that null, - * empty strings, zero and an empty array all count - * as false. - * @param boolean $result Pass on false. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertFalse($result, $message = '%s') { - return $this->assert(new FalseExpectation(), $result, $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value only. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertEqual($first, $second, $message = '%s') { - return $this->assert( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * a different value. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotEqual($first, $second, $message = '%s') { - return $this->assert( - new NotEqualExpectation($first), - $second, - $message); - } - - /** - * Uses a stack trace to find the line of an assertion. - * @return string Line number of first assert* - * method embedded in format string. - * @access public - */ - function getAssertionLine() { - $trace = new SimpleStackTrace(array('assert', 'click', 'pass', 'fail')); - return $trace->traceMethod(); - } -} -?> \ No newline at end of file diff --git a/tests/simpletest/xml.php b/tests/simpletest/xml.php deleted file mode 100644 index 1666cb930..000000000 --- a/tests/simpletest/xml.php +++ /dev/null @@ -1,647 +0,0 @@ -SimpleReporter(); - $this->_namespace = ($namespace ? $namespace . ':' : ''); - $this->_indent = $indent; - } - - /** - * Calculates the pretty printing indent level - * from the current level of nesting. - * @param integer $offset Extra indenting level. - * @return string Leading space. - * @access protected - */ - function _getIndent($offset = 0) { - return str_repeat( - $this->_indent, - count($this->getTestList()) + $offset); - } - - /** - * Converts character string to parsed XML - * entities string. - * @param string text Unparsed character data. - * @return string Parsed character data. - * @access public - */ - function toParsedXml($text) { - return str_replace( - array('&', '<', '>', '"', '\''), - array('&', '<', '>', '"', '''), - $text); - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test that is starting. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - parent::paintGroupStart($test_name, $size); - print $this->_getIndent(); - print "<" . $this->_namespace . "group size=\"$size\">\n"; - print $this->_getIndent(1); - print "<" . $this->_namespace . "name>" . - $this->toParsedXml($test_name) . - "_namespace . "name>\n"; - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintGroupEnd($test_name) { - print $this->_getIndent(); - print "_namespace . "group>\n"; - parent::paintGroupEnd($test_name); - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintCaseStart($test_name) { - parent::paintCaseStart($test_name); - print $this->_getIndent(); - print "<" . $this->_namespace . "case>\n"; - print $this->_getIndent(1); - print "<" . $this->_namespace . "name>" . - $this->toParsedXml($test_name) . - "_namespace . "name>\n"; - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintCaseEnd($test_name) { - print $this->_getIndent(); - print "_namespace . "case>\n"; - parent::paintCaseEnd($test_name); - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintMethodStart($test_name) { - parent::paintMethodStart($test_name); - print $this->_getIndent(); - print "<" . $this->_namespace . "test>\n"; - print $this->_getIndent(1); - print "<" . $this->_namespace . "name>" . - $this->toParsedXml($test_name) . - "_namespace . "name>\n"; - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test that is ending. - * @param integer $progress Number of test cases ending. - * @access public - */ - function paintMethodEnd($test_name) { - print $this->_getIndent(); - print "_namespace . "test>\n"; - parent::paintMethodEnd($test_name); - } - - /** - * Paints pass as XML. - * @param string $message Message to encode. - * @access public - */ - function paintPass($message) { - parent::paintPass($message); - print $this->_getIndent(1); - print "<" . $this->_namespace . "pass>"; - print $this->toParsedXml($message); - print "_namespace . "pass>\n"; - } - - /** - * Paints failure as XML. - * @param string $message Message to encode. - * @access public - */ - function paintFail($message) { - parent::paintFail($message); - print $this->_getIndent(1); - print "<" . $this->_namespace . "fail>"; - print $this->toParsedXml($message); - print "_namespace . "fail>\n"; - } - - /** - * Paints error as XML. - * @param string $message Message to encode. - * @access public - */ - function paintError($message) { - parent::paintError($message); - print $this->_getIndent(1); - print "<" . $this->_namespace . "exception>"; - print $this->toParsedXml($message); - print "_namespace . "exception>\n"; - } - - /** - * Paints exception as XML. - * @param Exception $exception Exception to encode. - * @access public - */ - function paintException($exception) { - parent::paintException($exception); - print $this->_getIndent(1); - print "<" . $this->_namespace . "exception>"; - $message = 'Unexpected exception of type [' . get_class($exception) . - '] with message ['. $exception->getMessage() . - '] in ['. $exception->getFile() . - ' line ' . $exception->getLine() . ']'; - print $this->toParsedXml($message); - print "_namespace . "exception>\n"; - } - - /** - * Paints the skipping message and tag. - * @param string $message Text to display in skip tag. - * @access public - */ - function paintSkip($message) { - parent::paintSkip($message); - print $this->_getIndent(1); - print "<" . $this->_namespace . "skip>"; - print $this->toParsedXml($message); - print "_namespace . "skip>\n"; - } - - /** - * Paints a simple supplementary message. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - parent::paintMessage($message); - print $this->_getIndent(1); - print "<" . $this->_namespace . "message>"; - print $this->toParsedXml($message); - print "_namespace . "message>\n"; - } - - /** - * Paints a formatted ASCII message such as a - * variable dump. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - parent::paintFormattedMessage($message); - print $this->_getIndent(1); - print "<" . $this->_namespace . "formatted>"; - print ""; - print "_namespace . "formatted>\n"; - } - - /** - * Serialises the event object. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @access public - */ - function paintSignal($type, $payload) { - parent::paintSignal($type, $payload); - print $this->_getIndent(1); - print "<" . $this->_namespace . "signal type=\"$type\">"; - print ""; - print "_namespace . "signal>\n"; - } - - /** - * Paints the test document header. - * @param string $test_name First test top level - * to start. - * @access public - * @abstract - */ - function paintHeader($test_name) { - if (! SimpleReporter::inCli()) { - header('Content-type: text/xml'); - } - print "_namespace) { - print " xmlns:" . $this->_namespace . - "=\"www.lastcraft.com/SimpleTest/Beta3/Report\""; - } - print "?>\n"; - print "<" . $this->_namespace . "run>\n"; - } - - /** - * Paints the test document footer. - * @param string $test_name The top level test. - * @access public - * @abstract - */ - function paintFooter($test_name) { - print "_namespace . "run>\n"; - } -} - -/** - * Accumulator for incoming tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingXmlTag { - var $_name; - var $_attributes; - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingXmlTag($attributes) { - $this->_name = false; - $this->_attributes = $attributes; - } - - /** - * Sets the test case/method name. - * @param string $name Name of test. - * @access public - */ - function setName($name) { - $this->_name = $name; - } - - /** - * Accessor for name. - * @return string Name of test. - * @access public - */ - function getName() { - return $this->_name; - } - - /** - * Accessor for attributes. - * @return hash All attributes. - * @access protected - */ - function _getAttributes() { - return $this->_attributes; - } -} - -/** - * Accumulator for incoming method tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingMethodTag extends NestingXmlTag { - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingMethodTag($attributes) { - $this->NestingXmlTag($attributes); - } - - /** - * Signals the appropriate start event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintStart(&$listener) { - $listener->paintMethodStart($this->getName()); - } - - /** - * Signals the appropriate end event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintEnd(&$listener) { - $listener->paintMethodEnd($this->getName()); - } -} - -/** - * Accumulator for incoming case tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingCaseTag extends NestingXmlTag { - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingCaseTag($attributes) { - $this->NestingXmlTag($attributes); - } - - /** - * Signals the appropriate start event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintStart(&$listener) { - $listener->paintCaseStart($this->getName()); - } - - /** - * Signals the appropriate end event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintEnd(&$listener) { - $listener->paintCaseEnd($this->getName()); - } -} - -/** - * Accumulator for incoming group tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingGroupTag extends NestingXmlTag { - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingGroupTag($attributes) { - $this->NestingXmlTag($attributes); - } - - /** - * Signals the appropriate start event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintStart(&$listener) { - $listener->paintGroupStart($this->getName(), $this->getSize()); - } - - /** - * Signals the appropriate end event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintEnd(&$listener) { - $listener->paintGroupEnd($this->getName()); - } - - /** - * The size in the attributes. - * @return integer Value of size attribute or zero. - * @access public - */ - function getSize() { - $attributes = $this->_getAttributes(); - if (isset($attributes['SIZE'])) { - return (integer)$attributes['SIZE']; - } - return 0; - } -} - -/** - * Parser for importing the output of the XmlReporter. - * Dispatches that output to another reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleTestXmlParser { - var $_listener; - var $_expat; - var $_tag_stack; - var $_in_content_tag; - var $_content; - var $_attributes; - - /** - * Loads a listener with the SimpleReporter - * interface. - * @param SimpleReporter $listener Listener of tag events. - * @access public - */ - function SimpleTestXmlParser(&$listener) { - $this->_listener = &$listener; - $this->_expat = &$this->_createParser(); - $this->_tag_stack = array(); - $this->_in_content_tag = false; - $this->_content = ''; - $this->_attributes = array(); - } - - /** - * Parses a block of XML sending the results to - * the listener. - * @param string $chunk Block of text to read. - * @return boolean True if valid XML. - * @access public - */ - function parse($chunk) { - if (! xml_parse($this->_expat, $chunk)) { - trigger_error('XML parse error with ' . - xml_error_string(xml_get_error_code($this->_expat))); - return false; - } - return true; - } - - /** - * Sets up expat as the XML parser. - * @return resource Expat handle. - * @access protected - */ - function &_createParser() { - $expat = xml_parser_create(); - xml_set_object($expat, $this); - xml_set_element_handler($expat, '_startElement', '_endElement'); - xml_set_character_data_handler($expat, '_addContent'); - xml_set_default_handler($expat, '_default'); - return $expat; - } - - /** - * Opens a new test nesting level. - * @return NestedXmlTag The group, case or method tag - * to start. - * @access private - */ - function _pushNestingTag($nested) { - array_unshift($this->_tag_stack, $nested); - } - - /** - * Accessor for current test structure tag. - * @return NestedXmlTag The group, case or method tag - * being parsed. - * @access private - */ - function &_getCurrentNestingTag() { - return $this->_tag_stack[0]; - } - - /** - * Ends a nesting tag. - * @return NestedXmlTag The group, case or method tag - * just finished. - * @access private - */ - function _popNestingTag() { - return array_shift($this->_tag_stack); - } - - /** - * Test if tag is a leaf node with only text content. - * @param string $tag XML tag name. - * @return @boolean True if leaf, false if nesting. - * @private - */ - function _isLeaf($tag) { - return in_array($tag, array( - 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL')); - } - - /** - * Handler for start of event element. - * @param resource $expat Parser handle. - * @param string $tag Element name. - * @param hash $attributes Name value pairs. - * Attributes without content - * are marked as true. - * @access protected - */ - function _startElement($expat, $tag, $attributes) { - $this->_attributes = $attributes; - if ($tag == 'GROUP') { - $this->_pushNestingTag(new NestingGroupTag($attributes)); - } elseif ($tag == 'CASE') { - $this->_pushNestingTag(new NestingCaseTag($attributes)); - } elseif ($tag == 'TEST') { - $this->_pushNestingTag(new NestingMethodTag($attributes)); - } elseif ($this->_isLeaf($tag)) { - $this->_in_content_tag = true; - $this->_content = ''; - } - } - - /** - * End of element event. - * @param resource $expat Parser handle. - * @param string $tag Element name. - * @access protected - */ - function _endElement($expat, $tag) { - $this->_in_content_tag = false; - if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) { - $nesting_tag = $this->_popNestingTag(); - $nesting_tag->paintEnd($this->_listener); - } elseif ($tag == 'NAME') { - $nesting_tag = &$this->_getCurrentNestingTag(); - $nesting_tag->setName($this->_content); - $nesting_tag->paintStart($this->_listener); - } elseif ($tag == 'PASS') { - $this->_listener->paintPass($this->_content); - } elseif ($tag == 'FAIL') { - $this->_listener->paintFail($this->_content); - } elseif ($tag == 'EXCEPTION') { - $this->_listener->paintError($this->_content); - } elseif ($tag == 'SKIP') { - $this->_listener->paintSkip($this->_content); - } elseif ($tag == 'SIGNAL') { - $this->_listener->paintSignal( - $this->_attributes['TYPE'], - unserialize($this->_content)); - } elseif ($tag == 'MESSAGE') { - $this->_listener->paintMessage($this->_content); - } elseif ($tag == 'FORMATTED') { - $this->_listener->paintFormattedMessage($this->_content); - } - } - - /** - * Content between start and end elements. - * @param resource $expat Parser handle. - * @param string $text Usually output messages. - * @access protected - */ - function _addContent($expat, $text) { - if ($this->_in_content_tag) { - $this->_content .= $text; - } - return true; - } - - /** - * XML and Doctype handler. Discards all such content. - * @param resource $expat Parser handle. - * @param string $default Text of default content. - * @access protected - */ - function _default($expat, $default) { - } -} -?> From 5d1eb1c21e2d7569963bb10d5d5576481a62387c Mon Sep 17 00:00:00 2001 From: lickawtl Date: Thu, 30 Jun 2011 15:01:45 +0000 Subject: [PATCH 51/82] new DBClasses for SQLite3 and Firebird databases. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8555 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 20 ++--- classes/db/DBFirebird.class.php | 80 +++++++++++++++++--- classes/db/DBMssql.class.php | 29 +++---- classes/db/DBMysql.class.php | 47 ++++++------ classes/db/DBSqlite3_pdo.class.php | 104 +++++++++++++++++++++++--- classes/db/queryparts/Query.class.php | 1 - modules/install/script/ko.install.php | 2 +- 7 files changed, 218 insertions(+), 65 deletions(-) diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index d87904abe..b91eace42 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -449,7 +449,6 @@ if (!file_exists ($file_name)) return; // read xml file $buff = FileHandler::readFile ($file_name); - return $this->_createTable ($buff); } @@ -629,10 +628,14 @@ if(is_a($query, 'Object')) return; $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); - if ($this->isError ()) { - if ($limit && $output->limit->isPageHandler()){ + + if ($this->isError ()) return $this->queryError($queryObject); + else return $this->queryPageLimit($queryObject, $result); + } + + function queryError($queryObject){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ $buff = new Object (); $buff->total_count = 0; $buff->total_page = 0; @@ -642,9 +645,10 @@ return $buff; }else return; - } - - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + } + + function queryPageLimit($queryObject, $result){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); if ($queryObject->getGroupByString() != '') { @@ -661,7 +665,6 @@ $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; } else $total_page = 1; - $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; $data = $this->_fetch($result, $virtual_no); @@ -676,7 +679,6 @@ $buff = new Object (); $buff->data = $data; } - return $buff; } diff --git a/classes/db/DBFirebird.class.php b/classes/db/DBFirebird.class.php index 209731755..a73d183fc 100644 --- a/classes/db/DBFirebird.class.php +++ b/classes/db/DBFirebird.class.php @@ -291,7 +291,7 @@ // Notify to start a query execution $this->actStart($query); // Execute the query statement - $result = ibase_query($this->fd, $query); + $result = @ibase_query($this->fd, $query); } else { // Notify to start a query execution @@ -592,6 +592,7 @@ } } + if($auto_increment_list) foreach($auto_increment_list as $increment) { $schema = sprintf('CREATE GENERATOR GEN_%s_ID;', $table_name); $output = $this->_query($schema); @@ -620,22 +621,28 @@ /** * @brief Handle the insertAct **/ - function _executeInsertAct($output) { - + function _executeInsertAct($queryObject) { + $query = $this->getInsertSql($queryObject); + if(is_a($query, 'Object')) return; + return $this->_query($query); } /** * @brief handles updateAct **/ - function _executeUpdateAct($output) { - + function _executeUpdateAct($queryObject) { + $query = $this->getUpdateSql($queryObject); + if(is_a($query, 'Object')) return; + return $this->_query($query); } /** * @brief handles deleteAct **/ - function _executeDeleteAct($output) { - + function _executeDeleteAct($queryObject) { + $query = $this->getDeleteSql($queryObject); + if(is_a($query, 'Object')) return; + return $this->_query($query); } /** @@ -644,9 +651,64 @@ * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($output) { - + function _executeSelectAct($queryObject) { + $query = $this->getSelectSql($queryObject); + + if(is_a($query, 'Object')) return; + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; + $result = $this->_query ($query); + + if ($this->isError ()) return $this->queryError($queryObject); + else return $this->queryPageLimit($queryObject, $result); } + + function queryError($queryObject){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + }else + return; + } + + function queryPageLimit($queryObject, $result){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } + + $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result_count = $this->_query($count_query); + $count_output = $this->_fetch($result_count); + $total_count = (int)$count_output->count; + + // Total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; + } else $total_page = 1; + + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; + $data = $this->_fetch($result, $virtual_no); + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $queryObject->getLimit()->page; + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + }else{ + $data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } + return $buff; + } } diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index 7f7d28e3a..bf9fca64a 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -489,8 +489,16 @@ $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; $result = $this->_query($query); - if ($this->isError ()) { - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ + if ($this->isError ()) return $this->queryError($queryObject); + else return $this->queryPageLimit($queryObject, $result); + } + + function getParser(){ + return new DBParser("[", "]"); + } + + function queryError($queryObject){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ $buff = new Object (); $buff->total_count = 0; $buff->total_page = 0; @@ -500,9 +508,10 @@ return $buff; }else return; - } - - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + } + + function queryPageLimit($queryObject, $result){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); if ($queryObject->getGroupByString() != '') { @@ -519,7 +528,6 @@ $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; } else $total_page = 1; - $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; $data = $this->_fetch($result, $virtual_no); @@ -534,13 +542,8 @@ $buff = new Object (); $buff->data = $data; } - - return $buff; - } - - function getParser(){ - return new DBParser("[", "]"); - } + return $buff; + } } diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index a9bdc9c8c..507a343de 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -438,8 +438,26 @@ // TODO Add code for pagination $result = $this->_query ($query); - if ($this->isError ()) { - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ + if ($this->isError ()) return $this->queryError($queryObject); + else return $this->queryPageLimit($queryObject, $result); + } + + function db_insert_id() + { + return mysql_insert_id($this->fd); + } + + function db_fetch_object(&$result) + { + return mysql_fetch_object($result); + } + + function getParser(){ + return new DBParser('`'); + } + + function queryError($queryObject){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ $buff = new Object (); $buff->total_count = 0; $buff->total_page = 0; @@ -449,9 +467,10 @@ return $buff; }else return; - } - - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + } + + function queryPageLimit($queryObject, $result){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); if ($queryObject->getGroupByString() != '') { @@ -468,7 +487,6 @@ $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; } else $total_page = 1; - $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; $data = $this->_fetch($result, $virtual_no); @@ -483,22 +501,7 @@ $buff = new Object (); $buff->data = $data; } - - return $buff; - } - - function db_insert_id() - { - return mysql_insert_id($this->fd); - } - - function db_fetch_object(&$result) - { - return mysql_fetch_object($result); - } - - function getParser(){ - return new DBParser('`'); + return $buff; } } diff --git a/classes/db/DBSqlite3_pdo.class.php b/classes/db/DBSqlite3_pdo.class.php index 35f496679..0e3d31ef6 100644 --- a/classes/db/DBSqlite3_pdo.class.php +++ b/classes/db/DBSqlite3_pdo.class.php @@ -402,8 +402,11 @@ /** * @brief insertAct **/ - function _executeInsertAct($output) { - $this->_prepare($query); + function _executeInsertAct($queryObject) { + $query = $this->getInsertSql($queryObject); + if(is_a($query, 'Object')) return; + + $this->_prepare($query); $val_count = count($val_list); for($i=0;$i<$val_count;$i++) $this->_bind($val_list[$i]); @@ -414,16 +417,22 @@ /** * @brief updateAct **/ - function _executeUpdateAct($output) { - $this->_prepare($query); + function _executeUpdateAct($queryObject) { + $query = $this->getUpdateSql($queryObject); + if(is_a($query, 'Object')) return; + + $this->_prepare($query); return $this->_execute(); } /** * @brief deleteAct **/ - function _executeDeleteAct($output) { - $this->_prepare($query); + function _executeDeleteAct($queryObject) { + $query = $this->getDeleteSql($queryObject); + if(is_a($query, 'Object')) return; + + $this->_prepare($query); return $this->_execute(); } @@ -433,11 +442,86 @@ * To fetch a list of the page conveniently when selecting, \n * navigation method supported **/ - function _executeSelectAct($output) { - $buff = new Object(); - $buff->data = $data; - return $buff; + function _executeSelectAct($queryObject) { + $query = $this->getSelectSql($queryObject); + if(is_a($query, 'Object')) return; + + $this->_prepare($query); + $data = $this->_execute(); + if($this->isError()) return; + + if ($this->isError ()) return $this->queryError($queryObject); + else return $this->queryPageLimit($queryObject, $data); } + + function queryError($queryObject){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array (); + $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values + return $buff; + }else + return; + } + + function queryPageLimit($queryObject, $data){ + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } + + $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $this->_prepare($count_query); + $count_output = $this->_execute(); + $total_count = (int)$count_output->count; + + // Total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; + } else $total_page = 1; + + $this->_prepare($this->getSelectSql($queryObject)); + $this->stmt->execute(); + if($this->stmt->errorCode() != '00000') { + $this->setError($this->stmt->errorCode(), print_r($this->stmt->errorInfo(),true)); + $this->actFinish(); + return $buff; + } + + $output = null; + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; + //$data = $this->_fetch($result, $virtual_no); + while($tmp = $this->stmt->fetch(PDO::FETCH_ASSOC)) { + unset($obj); + foreach($tmp as $key => $val) { + $pos = strpos($key, '.'); + if($pos) $key = substr($key, $pos+1); + $obj->{$key} = $val; + } + $data[$virtual_no--] = $obj; + } + + $this->stmt = null; + $this->actFinish(); + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $queryObject->getLimit()->page; + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + }else{ + //$data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } + return $buff; + } } return new DBSqlite3_pdo; diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 7612622a8..eba1f8879 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -133,7 +133,6 @@ function getSelectString($with_values = true){ $select = ''; foreach($this->columns as $column){ - var_dump($column); if($column->show()) if(is_a($column, 'Subquery')){ $oDB = &DB::getInstance(); diff --git a/modules/install/script/ko.install.php b/modules/install/script/ko.install.php index 7222774ca..56f228bc1 100644 --- a/modules/install/script/ko.install.php +++ b/modules/install/script/ko.install.php @@ -1,4 +1,4 @@ - Date: Thu, 30 Jun 2011 15:36:03 +0000 Subject: [PATCH 52/82] Added unit tests for correlated subqueries - select, from, where. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8556 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 1 + classes/db/DBMssql.class.php | 10 +- classes/db/queryparts/Query.class.php | 9 +- classes/db/queryparts/Subquery.class.php | 19 ++- .../queryparts/condition/Condition.class.php | 116 +++++++-------- classes/db/queryparts/table/Table.class.php | 3 +- classes/xml/XmlQueryParser.class.php | 26 +++- .../tags/column/SelectColumnsTag.class.php | 3 +- .../condition/ConditionGroupTag.class.php | 10 +- .../tags/condition/ConditionTag.class.php | 27 ++-- .../tags/condition/ConditionsTag.class.php | 10 +- .../xmlquery/tags/query/QueryTag.class.php | 23 +-- .../xmlquery/tags/table/TableTag.class.php | 12 +- .../xmlquery/tags/table/TablesTag.class.php | 40 ++++-- config/config.inc.php | 2 +- nbproject/project.properties | 14 ++ nbproject/project.xml | 9 ++ test-phpUnit/Helper.class.php | 8 +- test-phpUnit/QueryTester.class.php | 8 +- .../xml/xmlquery/tags/table/TableTagTest.php | 134 ++++++++++++++++++ .../xmlquery/tags/table/data/table_name.xml | 1 + .../tags/table/data/table_name_alias.xml | 1 + .../tags/table/data/table_name_alias_type.xml | 5 + test-phpUnit/{ => config}/config.inc.php | 14 +- test-phpUnit/db/CubridTest.php | 24 ++++ test-phpUnit/db/DBTest.php | 54 +++++++ test-phpUnit/db/ExpressionParserTest.php | 2 +- test-phpUnit/db/MssqlTest.php | 24 ++++ .../db/xml_query/cubrid/CubridDeleteTest.php | 24 +--- .../db/xml_query/cubrid/CubridInsertTest.php | 24 +--- .../db/xml_query/cubrid/CubridSelectTest.php | 28 +--- .../xml_query/cubrid/CubridSubqueryTest.php | 77 ++++++++++ .../db/xml_query/cubrid/CubridUpdateTest.php | 24 +--- .../db/xml_query/cubrid/config.cubrid.inc.php | 8 -- .../cubrid/data/from_uncorrelated1.xml | 19 +++ .../cubrid/data/select_uncorrelated1.xml | 19 +++ .../cubrid/data/select_uncorrelated2.xml | 24 ++++ .../cubrid/data/where_uncorrelated1.xml | 18 +++ .../db/xml_query/mssql/MssqlSelectTest.php | 32 +---- .../db/xml_query/mssql/config.mssql.inc.php | 8 -- test-phpUnit/debug.php | 3 +- 41 files changed, 661 insertions(+), 256 deletions(-) create mode 100644 nbproject/project.properties create mode 100644 nbproject/project.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias_type.xml rename test-phpUnit/{ => config}/config.inc.php (77%) create mode 100644 test-phpUnit/db/CubridTest.php create mode 100644 test-phpUnit/db/DBTest.php create mode 100644 test-phpUnit/db/MssqlTest.php create mode 100644 test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php delete mode 100644 test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php create mode 100644 test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated1.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated2.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/where_uncorrelated1.xml delete mode 100644 test-phpUnit/db/xml_query/mssql/config.mssql.inc.php diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 40f966c2e..ca9333f85 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -319,6 +319,7 @@ require_once(_XE_PATH_.'classes/db/queryparts/order/OrderByColumn.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/Query.class.php'); + require_once(_XE_PATH_.'classes/db/queryparts/Subquery.class.php'); $output = include($cache_file); diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index bf9fca64a..7cac092b1 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -199,7 +199,7 @@ /** * @brief Fetch results **/ - function _fetch($result) { + function _fetch($result, $arrayIndexEndValue = NULL) { if(!$this->isConnected() || $this->isError() || !$result) return; $c = sqlsrv_num_fields($result); @@ -212,10 +212,14 @@ for($i=0;$i<$c;$i++){ $row->{$m[$i]['Name']} = sqlsrv_get_field( $result, $i, SQLSRV_PHPTYPE_STRING( 'utf-8' )); } - $output[] = $row; + if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $row; + else $output[] = $row; } - if(count($output)==1) return $output[0]; + if(count($output)==1) { + if(isset($arrayIndexEndValue)) return $output; + else return $output[0]; + } return $output; } diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index eba1f8879..93f36f739 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -135,8 +135,7 @@ foreach($this->columns as $column){ if($column->show()) if(is_a($column, 'Subquery')){ - $oDB = &DB::getInstance(); - $select .= '(' .$oDB->getSelectSql($column, $with_values) . ') as \''. $column->getAlias().'\', '; + $select .= $column->toString($with_values) . ' as '. $column->getAlias() .', '; } else $select .= $column->getExpression($with_values) . ', '; @@ -169,12 +168,18 @@ return $this->tables; } + // from table_a + // from table_a inner join table_b on x=y + // from (select * from table a) as x + // from (select * from table t) as x inner join table y on y.x function getFromString($with_values = true){ $from = ''; $simple_table_count = 0; foreach($this->tables as $table){ if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString($with_values) . ' '; else $from .= ', '.$table->toString($with_values) . ' '; + if(!$table->isJoinTable()) $from .= $table->getAlias() ? ' as ' . $table->getAlias() . ' ' : ' '; + $simple_table_count++; } if(trim($from) == '') return ''; diff --git a/classes/db/queryparts/Subquery.class.php b/classes/db/queryparts/Subquery.class.php index 463aed658..3ec2e1a94 100644 --- a/classes/db/queryparts/Subquery.class.php +++ b/classes/db/queryparts/Subquery.class.php @@ -2,12 +2,13 @@ class Subquery extends Query { var $alias; - - function Subquery($alias, $columns, $tables, $conditions, $groups, $orderby, $limit){ + var $join_type; + + function Subquery($alias, $columns, $tables, $conditions, $groups, $orderby, $limit, $join_type = null){ $this->alias = $alias; $this->queryID = null; - $this->action = null; + $this->action = "select"; $this->columns = $columns; $this->tables = $tables; @@ -15,11 +16,23 @@ $this->groups = $groups; $this->orderby = $orderby; $this->limit = $limit; + $this->join_type = $join_type; } function getAlias(){ return $this->alias; } + + function isJoinTable(){ + if($this->join_type) return true; + return false; + } + + function toString($with_values = true){ + $oDB = &DB::getInstance(); + return '(' .$oDB->getSelectSql($this, $with_values) . ')'; + + } } ?> \ No newline at end of file diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index ac8130c89..fdeaeeaae 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -15,6 +15,8 @@ $this->pipe = $pipe; if($this->hasArgument()) $this->_value = $argument->getValue(); + else if(is_a($this->argument, 'Subquery')) + $this->_value = $argument->toString(); else $this->_value = $argument; } @@ -50,27 +52,27 @@ function show(){ switch($this->operation) { - case 'equal' : - case 'more' : - case 'excess' : - case 'less' : - case 'below' : - case 'like_tail' : - case 'like_prefix' : - case 'like' : - case 'in' : - case 'notin' : - case 'notequal' : - // if variable is not set or is not string or number, return - if(!isset($this->_value)) return false; - if($this->_value === '') return false; - if(!in_array(gettype($this->_value), array('string', 'integer'))) return false; - break; - case 'between' : - if(!is_array($this->_value)) return false; - if(count($this->_value)!=2) return false; + case 'equal' : + case 'more' : + case 'excess' : + case 'less' : + case 'below' : + case 'like_tail' : + case 'like_prefix' : + case 'like' : + case 'in' : + case 'notin' : + case 'notequal' : + // if variable is not set or is not string or number, return + if(!isset($this->_value)) return false; + if($this->_value === '') return false; + if(!in_array(gettype($this->_value), array('string', 'integer'))) return false; + break; + case 'between' : + if(!is_array($this->_value)) return false; + if(count($this->_value)!=2) return false; - } + } return true; } @@ -78,43 +80,43 @@ $name = $this->column_name; $operation = $this->operation; - switch($operation) { - case 'equal' : - return $name.' = '.$value; - break; - case 'more' : - return $name.' >= '.$value; - break; - case 'excess' : - return $name.' > '.$value; - break; - case 'less' : - return $name.' <= '.$value; - break; - case 'below' : - return $name.' < '.$value; - break; - case 'like_tail' : - case 'like_prefix' : - case 'like' : - return $name.' like '.$value; - break; - case 'in' : - return $name.' in ('.$value.')'; - break; - case 'notin' : - return $name.' not in ('.$value.')'; - break; - case 'notequal' : - return $name.' <> '.$value; - break; - case 'notnull' : - return $name.' is not null'; - break; - case 'null' : - return $name.' is null'; - break; - case 'between' : + switch($operation) { + case 'equal' : + return $name.' = '.$value; + break; + case 'more' : + return $name.' >= '.$value; + break; + case 'excess' : + return $name.' > '.$value; + break; + case 'less' : + return $name.' <= '.$value; + break; + case 'below' : + return $name.' < '.$value; + break; + case 'like_tail' : + case 'like_prefix' : + case 'like' : + return $name.' like '.$value; + break; + case 'in' : + return $name.' in ('.$value.')'; + break; + case 'notin' : + return $name.' not in ('.$value.')'; + break; + case 'notequal' : + return $name.' <> '.$value; + break; + case 'notnull' : + return $name.' is not null'; + break; + case 'null' : + return $name.' is null'; + break; + case 'between' : return $name.' between ' . $value[0] . ' and ' . $value[1]; break; } diff --git a/classes/db/queryparts/table/Table.class.php b/classes/db/queryparts/table/Table.class.php index 022be04f1..791a936d2 100644 --- a/classes/db/queryparts/table/Table.class.php +++ b/classes/db/queryparts/table/Table.class.php @@ -10,7 +10,8 @@ } function toString(){ - return sprintf("%s%s", $this->name, $this->alias ? ' as ' . $this->alias : ''); + return $this->name; + //return sprintf("%s%s", $this->name, $this->alias ? ' as ' . $this->alias : ''); } function getName(){ diff --git a/classes/xml/XmlQueryParser.class.php b/classes/xml/XmlQueryParser.class.php index 542640dab..72ac107f1 100644 --- a/classes/xml/XmlQueryParser.class.php +++ b/classes/xml/XmlQueryParser.class.php @@ -13,13 +13,21 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/QueryParser.class.php'); class XmlQueryParser extends XmlParser { - var $dbParser; + static $dbParser = null; var $db_type; function XmlQueryParser($db_type = NULL){ $this->db_type = $db_type; } + function &getInstance($db_type = NULL){ + static $theInstance = null; + if(!isset($theInstance)){ + $theInstance = new XmlQueryParser($db_type); + } + return $theInstance; + } + function parse($query_id, $xml_file, $cache_file) { // Read xml file @@ -36,15 +44,19 @@ // singleton function &getDBParser(){ - static $dbParser; - if(!$dbParser){ - if(isset($this->db_type)) - $oDB = &DB::getInstance($this->db_type); + if(!$self->dbParser){ + is_a($this,'XmlQueryParser')?$self=&$this:$self=&XmlQueryParser::getInstance(); + if(isset($self->db_type)) + $oDB = &DB::getInstance($self->db_type); else $oDB = &DB::getInstance(); - $dbParser = $oDB->getParser(); + $self->dbParser = $oDB->getParser(); } - return $dbParser; + return $self->dbParser; + } + + function setDBParser($value){ + $self->dbParser = $value; } function getXmlFileContent($xml_file){ diff --git a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php index ffe84809c..64c4048a2 100644 --- a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php @@ -20,8 +20,7 @@ if(!is_array($xml_columns)) $xml_columns = array($xml_columns); foreach($xml_columns as $column){ - if($column->node_name == 'query') $this->columns[] = new QueryTag($column, true); - else $this->columns[] = new SelectColumnTag($column); + $this->columns[] = new SelectColumnTag($column); } diff --git a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php index 57b250e73..4c7194160 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php @@ -11,8 +11,8 @@ if(count($conditions))require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); foreach($conditions as $condition){ - if($condition->name === 'query') $this->conditions[] = new QueryTag($condition, true); - else $this->conditions[] = new ConditionTag($condition); + //if($condition->node_name === 'query') $this->conditions[] = new QueryTag($condition, true); + $this->conditions[] = new ConditionTag($condition); } } @@ -22,8 +22,9 @@ function getConditionGroupString(){ $conditions_string = 'array('.PHP_EOL; - foreach($this->conditions as $condition) + foreach($this->conditions as $condition){ $conditions_string .= $condition->getConditionString() . PHP_EOL . ','; + } $conditions_string = substr($conditions_string, 0, -2);//remove ',' $conditions_string .= ')'; @@ -33,6 +34,9 @@ function getArguments(){ $arguments = array(); foreach($this->conditions as $condition){ + if(is_a($condition, 'QueryTag')) + $arguments = array_merge($arguments, $condition->getArguments()); + else $arguments[] = $condition->getArgument(); } return $arguments; diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index ed7e31a01..cf224c0fb 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -16,6 +16,7 @@ var $argument; var $default_column; + var $query; function ConditionTag($condition){ $this->operation = $condition->attrs->operation; $this->pipe = $condition->attrs->pipe; @@ -23,20 +24,20 @@ $this->column_name = $dbParser->parseColumnName($condition->attrs->column); $isColumnName = strpos($condition->attrs->default, '.'); - - if($condition->attrs->var || $isColumnName === false){ + + if($condition->node_name == 'query'){ + $this->query = new QueryTag($condition, true); + $this->default_column = $this->query->toString(); + } + else if($condition->attrs->var || $isColumnName === false){ require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - //$this->argument_name = $condition->attrs->var; $this->argument = new QueryArgument($condition); $this->argument_name = $this->argument->getArgumentName(); } - //else if($isColumnName === false){ - // $this->default_column = $condition->attrs->default; - //} else { - $this->default_column = $dbParser->parseColumnName($condition->attrs->default); - } + $this->default_column = "'" . $dbParser->parseColumnName($condition->attrs->default) . "'" ; + } } function setPipe($pipe){ @@ -49,11 +50,11 @@ function getConditionString(){ return sprintf("new Condition('%s',%s,%s%s)" - , $this->column_name - , $this->default_column ? "'" . $this->default_column . "'" : '$' . $this->argument_name . '_argument' - , '"'.$this->operation.'"' - , $this->pipe ? ", '" . $this->pipe . "'" : '' - ); + , $this->column_name + , $this->default_column ? $this->default_column: '$' . $this->argument_name . '_argument' + , '"'.$this->operation.'"' + , $this->pipe ? ", '" . $this->pipe . "'" : '' + ); } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php index 983f0e1fd..828220b50 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionsTag.class.php @@ -5,7 +5,15 @@ function ConditionsTag($xml_conditions){ $this->condition_groups = array(); - $xml_condition_list = $xml_conditions->condition; + $xml_condition_list = array(); + if($xml_conditions->condition) + $xml_condition_list = $xml_conditions->condition; + + if($xml_conditions->query){ + if(!is_array($xml_condition_list)) $xml_condition_list = array($xml_condition_list); + if(!is_array($xml_conditions->query)) $xml_conditions->query = array($xml_conditions->query); + $xml_condition_list = array_merge($xml_condition_list, $xml_conditions->query); + } if($xml_condition_list){ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php'); $this->condition_groups[] = new ConditionGroupTag($xml_condition_list); diff --git a/classes/xml/xmlquery/tags/query/QueryTag.class.php b/classes/xml/xmlquery/tags/query/QueryTag.class.php index 5a840800e..4f45aac21 100644 --- a/classes/xml/xmlquery/tags/query/QueryTag.class.php +++ b/classes/xml/xmlquery/tags/query/QueryTag.class.php @@ -17,6 +17,7 @@ class QueryTag { var $buff; var $isSubQuery; + var $join_type; var $alias; function QueryTag($query, $isSubQuery = false){ @@ -26,6 +27,7 @@ class QueryTag { $this->isSubQuery = $isSubQuery; if($this->isSubQuery) $this->action = 'select'; $this->alias = $query->attrs->alias; + $this->join_type = $query->attrs->join_type; $this->getColumns(); $tables = $this->getTables(); @@ -55,8 +57,10 @@ class QueryTag { $table_tags = $tables->getTables(); $column_type = array(); foreach($table_tags as $table_tag){ + if(is_a($table_tag, 'TableTag')){ $tag_column_type = QueryParser::getTableInfo($query_id, $table_tag->getTableName()); $column_type = array_merge($column_type, $tag_column_type); + } } $this->column_type[$query_id] = $column_type; } @@ -94,17 +98,17 @@ class QueryTag { function getBuff(){ $buff = ''; - //echo 'Luam un query care e '.$this->isSubQuery; if($this->isSubQuery){ $buff = 'new Subquery('; - $buff .= "'" . $this->alias . '\', '; + $buff .= "'\"" . $this->alias . '"\', '; $buff .= ($this->columns ? $this->columns->toString() : 'null' ). ', '.PHP_EOL; - $buff .= $this->tables->toString() .','.PHP_EOL; - $buff .= $this->conditions->toString() .',' .PHP_EOL; - $buff .= $this->groups->toString() . ',' .PHP_EOL; - $buff .= $this->navigation->getOrderByString() .','.PHP_EOL; - $limit = $this->navigation->getLimitString() ; + $buff .= $this->tables->toString() .','.PHP_EOL; + $buff .= $this->conditions->toString() .',' .PHP_EOL; + $buff .= $this->groups->toString() . ',' .PHP_EOL; + $buff .= $this->navigation->getOrderByString() .','.PHP_EOL; + $limit = $this->navigation->getLimitString() ; $buff .= $limit ? $limit : 'null' . PHP_EOL; + $buff .= $this->join_type ? "'" . $this->join_type . "'" : ''; $buff .= ')'; $this->buff = $buff; @@ -129,7 +133,7 @@ class QueryTag { } function getTables(){ - return $this->tables = new TablesTag($this->query->tables->table); + return $this->tables = new TablesTag($this->query->tables); } function getConditions(){ @@ -160,6 +164,7 @@ class QueryTag { return $this->buff; } + function getArguments(){ $arguments = array(); if($this->columns) @@ -170,4 +175,4 @@ class QueryTag { } } -?> \ No newline at end of file +?> diff --git a/classes/xml/xmlquery/tags/table/TableTag.class.php b/classes/xml/xmlquery/tags/table/TableTag.class.php index 3d5407f18..125176bbd 100644 --- a/classes/xml/xmlquery/tags/table/TableTag.class.php +++ b/classes/xml/xmlquery/tags/table/TableTag.class.php @@ -6,6 +6,17 @@ * @author Arnia Sowftare * @brief Models the tag inside an XML Query file * + * @abstract + * Example + *
+ *
+ * Attributes + * name - name of the table - table prefix will be automatically added + * alias - table alias. If no value is specified, the table name will be set as default alias + * join_type - in case the table is part of a join clause, this specifies the type of join: left, right etc. + * - permitted values: 'left join','left outer join','right join','right outer join' + * Children + * Can have children of type */ class TableTag { @@ -16,7 +27,6 @@ var $conditions; function TableTag($table){ - $this->unescaped_name = $table->attrs->name; $dbParser = XmlQueryParser::getDBParser(); diff --git a/classes/xml/xmlquery/tags/table/TablesTag.class.php b/classes/xml/xmlquery/tags/table/TablesTag.class.php index aaa58ae63..012a46b07 100644 --- a/classes/xml/xmlquery/tags/table/TablesTag.class.php +++ b/classes/xml/xmlquery/tags/table/TablesTag.class.php @@ -3,16 +3,29 @@ class TablesTag { var $tables; - function TablesTag($xml_tables){ - $this->tables = array(); - if(!is_array($xml_tables)) $xml_tables = array($xml_tables); - - if(count($xml_tables)) require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); - - foreach($xml_tables as $table){ - if($table->name === 'query') $this->tables[] = new QueryTag($table, true); - else $this->tables[] = new TableTag($table); - } + function TablesTag($xml_tables_tag){ + $xml_tables = $xml_tables_tag->table; + $xml_queries = $xml_tables_tag->query; + + $this->tables = array(); + + + if($xml_tables){ + if(!is_array($xml_tables)) $xml_tables = array($xml_tables); + + if(count($xml_tables)) require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); + + foreach($xml_tables as $table){ + if($table->name === 'query') $this->tables[] = new QueryTag($table, true); + else $this->tables[] = new TableTag($table); + } + } + if(!$xml_queries) return; + if(!is_array($xml_queries)) $xml_queries = array($xml_queries); + + foreach($xml_queries as $table){ + $this->tables[] = new QueryTag($table, true); + } } function getTables(){ @@ -21,8 +34,11 @@ function toString(){ $output_tables = 'array(' . PHP_EOL; - foreach($this->tables as $table){ - $output_tables .= $table->getTableString() . PHP_EOL . ','; + foreach($this->tables as $table){ + if(is_a($table, 'QueryTag')) + $output_tables .= $table->toString() . PHP_EOL . ','; + else + $output_tables .= $table->getTableString() . PHP_EOL . ','; } $output_tables = substr($output_tables, 0, -1); $output_tables .= ')'; diff --git a/config/config.inc.php b/config/config.inc.php index 858a8769a..b6b9e814a 100644 --- a/config/config.inc.php +++ b/config/config.inc.php @@ -5,7 +5,7 @@ * @brief set the include of the class file and other environment configurations **/ - @error_reporting(E_ALL ^ E_NOTICE); + @error_reporting((E_ALL ^ E_NOTICE) ^ E_DEPRECATED); if(!defined('__ZBXE__')) exit(); diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 000000000..7affa3183 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,14 @@ +include.path=\ + ${php.global.include.path} +php.version=PHP_5 +phpunit.bootstrap=test-phpUnit/config/config.inc.php +phpunit.bootstrap.create.tests=true +phpunit.configuration= +phpunit.run.test.files=false +phpunit.suite= +source.encoding=UTF-8 +src.dir=. +tags.asp=false +tags.short=true +test.src.dir=test-phpUnit +web.root=. diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 000000000..04e9f0376 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,9 @@ + + + org.netbeans.modules.php.project + + + mssql + + + diff --git a/test-phpUnit/Helper.class.php b/test-phpUnit/Helper.class.php index 24aa12b90..68a122883 100644 --- a/test-phpUnit/Helper.class.php +++ b/test-phpUnit/Helper.class.php @@ -1,7 +1,7 @@ getXmlFileContent($xml_file); + } + } ?> \ No newline at end of file diff --git a/test-phpUnit/QueryTester.class.php b/test-phpUnit/QueryTester.class.php index 65227083f..4ece64676 100644 --- a/test-phpUnit/QueryTester.class.php +++ b/test-phpUnit/QueryTester.class.php @@ -12,8 +12,8 @@ return _XE_PATH_ . $type ."/".$name."/queries/" . $query_name . ".xml"; } - function getNewParserOutput($xml_file, $escape_char = '"', $db_type = NULL){ - $newXmlQueryParser = new XmlQueryParser($db_type); + function getNewParserOutput($xml_file){ + $newXmlQueryParser = new XmlQueryParser(); $xml_obj = $newXmlQueryParser->getXmlFileContent($xml_file); $parser = new QueryParser($xml_obj->query); @@ -58,9 +58,9 @@ .''; } - function getNewParserOutputString($xml_file, $escape_char, $argsString, $db_type = NULL){ + function getNewParserOutputString($xml_file, $argsString){ $outputString = ''; - $outputString = $this->getNewParserOutput($xml_file, $escape_char, $db_type); + $outputString = $this->getNewParserOutput($xml_file); $outputString = $this->cleanOutputAndAddArgs($outputString, $argsString); return $outputString; } diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php b/test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php new file mode 100644 index 000000000..1312199fd --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php @@ -0,0 +1,134 @@ +xmlPath = str_replace('TableTagTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; + } + + /** + * Tests a simple
tag: + *
+ */ + function testTableTagWithName(){ + $xml_file = $this->xmlPath . "table_name.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new TableTag($xml_obj->table); + + $expected = "new Table('\"xe_modules\"', '\"modules\"')"; + $actual = $tag->getTableString(); + $this->assertEquals($expected, $actual); + } + + /** + * Tests a
tag with name and alias + *
+ */ + function testTableTagWithNameAndAlias(){ + $xml_file = $this->xmlPath . "table_name_alias.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + + $tag = new TableTag($xml_obj->table); + + $expected = "new Table('\"xe_modules\"', '\"mod\"')"; + $actual = $tag->getTableString(); + $this->assertEquals($expected, $actual); + } + + /** + * Tests a
tag used for joins + *
+ * + * + * + *
+ * + */ + function testTableTagWithJoinCondition(){ + $xml_file = $this->xmlPath . "table_name_alias_type.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + + $tag = new TableTag($xml_obj->table); + + $actual = $tag->getTableString(); + + $expected = 'new JoinTable(\'"xe_module_categories"\', \'"module_categories"\', "left join", array( + new ConditionGroup(array( + new Condition(\'"module_categories"."module_category_srl"\',\'"modules"."module_category_srl"\',"equal") + )) + ))'; + $actual = Helper::cleanQuery($actual); + $expected = Helper::cleanQuery($expected); + + $this->assertEquals($expected, $actual); + } + + /** + * If a table tag has the type attribute and condition children + * it means it is meant to be used inside a join + */ + function testTagWithTypeIsJoinTable(){ + $xml_file = $this->xmlPath . "table_name_alias_type.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + + $tag = new TableTag($xml_obj->table); + + $this->assertEquals(true, $tag->isJoinTable()); + } + + /** + * Tests that a simple table tag is not a join table + */ + function testTagWithoutTypeIsNotJoinTable(){ + $xml_file = $this->xmlPath . "table_name_alias.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + + $tag = new TableTag($xml_obj->table); + + $this->assertEquals(false, $tag->isJoinTable()); + } + + /** + * If no alias is specified, test that table name is used + */ + function testTableAliasWhenAliasNotSpecified(){ + $xml_file = $this->xmlPath . "table_name.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + + $tag = new TableTag($xml_obj->table); + + $this->assertEquals("modules", $tag->getTableAlias()); + } + + /** + * If alias is specified, test that it is used + */ + function testTableAliasWhenAliasSpecified(){ + $xml_file = $this->xmlPath . "table_name_alias.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + + $tag = new TableTag($xml_obj->table); + + $this->assertEquals("mod", $tag->getTableAlias()); + } + + /** + * Table name propery should returned unescaped and unprefixed table name + * (The one in the XML file) + */ + function testTableName(){ + $xml_file = $this->xmlPath . "table_name_alias.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + + $tag = new TableTag($xml_obj->table); + + $this->assertEquals("modules", $tag->getTableName()); + } + + } \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name.xml b/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name.xml new file mode 100644 index 000000000..6525964f0 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias.xml b/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias.xml new file mode 100644 index 000000000..8240d4652 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias.xml @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias_type.xml b/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias_type.xml new file mode 100644 index 000000000..6d8e7f1d5 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/data/table_name_alias_type.xml @@ -0,0 +1,5 @@ +
+ + + +
\ No newline at end of file diff --git a/test-phpUnit/config.inc.php b/test-phpUnit/config/config.inc.php similarity index 77% rename from test-phpUnit/config.inc.php rename to test-phpUnit/config/config.inc.php index d85b07d74..991db29f8 100644 --- a/test-phpUnit/config.inc.php +++ b/test-phpUnit/config/config.inc.php @@ -1,17 +1,20 @@ \ No newline at end of file diff --git a/test-phpUnit/db/CubridTest.php b/test-phpUnit/db/CubridTest.php new file mode 100644 index 000000000..b88c0a0da --- /dev/null +++ b/test-phpUnit/db/CubridTest.php @@ -0,0 +1,24 @@ +db_type = 'cubrid'; + $db_info->db_table_prefix = 'xe'; + + $oContext->setDbInfo($db_info); + } + + protected function tearDown() { + unset($GLOBALS['__DB__']); + XmlQueryParser::setDBParser(null); + } + } +?> diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php new file mode 100644 index 000000000..d883f27c9 --- /dev/null +++ b/test-phpUnit/db/DBTest.php @@ -0,0 +1,54 @@ +getNewParserOutputString($xml_file, $argsString); + $output = eval($outputString); + + if(!is_a($output, 'Query')){ + if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; + }else { + $db = &DB::getInstance(); + $querySql = $db->{$methodName}($output); + + // Remove whitespaces, tabs and all + $querySql = Helper::cleanQuery($querySql); + $expected = Helper::cleanQuery($expected); + } + $this->assertEquals($expected, $querySql); + } + + function _testPreparedQuery($xml_file, $argsString, $expected, $methodName, $expectedArgs = NULL){ + $tester = new QueryTester(); + $outputString = $tester->getNewParserOutputString($xml_file, $argsString); + $output = eval($outputString); + + if(!is_a($output, 'Query')){ + if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; + }else { + $db = &DB::getInstance(); + $querySql = $db->{$methodName}($output); + $queryArguments = $output->getArguments(); + + // Remove whitespaces, tabs and all + $querySql = Helper::cleanQuery($querySql); + $expected = Helper::cleanQuery($expected); + } + + // Test + $this->assertEquals($expected, $querySql); + + // Test query arguments + $argCount = count($expectedArgs); + for($i = 0; $i < $argCount; $i++){ + //echo "$i: $expectedArgs[$i] vs $queryArguments[$i]->getValue()"; + $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue()); + } + } + } +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +?> diff --git a/test-phpUnit/db/ExpressionParserTest.php b/test-phpUnit/db/ExpressionParserTest.php index 457301643..09bb8e73f 100644 --- a/test-phpUnit/db/ExpressionParserTest.php +++ b/test-phpUnit/db/ExpressionParserTest.php @@ -1,5 +1,5 @@ db_type = 'mssql'; + $db_info->db_table_prefix = 'xe'; + + $oContext->setDbInfo($db_info); + } + + protected function tearDown() { + unset($GLOBALS['__DB__']); + XmlQueryParser::setDBParser(null); + } + } +?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridDeleteTest.php b/test-phpUnit/db/xml_query/cubrid/CubridDeleteTest.php index 20d52e53d..76fddaa36 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridDeleteTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridDeleteTest.php @@ -1,28 +1,10 @@ getNewParserOutputString($xml_file, '"', $argsString); - $output = eval($outputString); - - if(!is_a($output, 'Query')){ - if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; - }else { - $db = &DB::getInstance(); - var_dump($db); - $querySql = $db->getDeleteSql($output); - - // Remove whitespaces, tabs and all - $querySql = Helper::cleanQuery($querySql); - $expected = Helper::cleanQuery($expected); - } - - // Test - $this->assertEquals($expected, $querySql); + $this->_testQuery($xml_file, $argsString, $expected, 'getDeleteSql'); } function test_module_deleteActionForward(){ diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php index 5b09617f8..aca4445f3 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php @@ -1,28 +1,12 @@ getNewParserOutputString($xml_file, '"', $argsString); - $output = eval($outputString); - - if(!is_a($output, 'Query')){ - if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; - }else { - $db = &DB::getInstance(); - $querySql = $db->getInsertSql($output); - - // Remove whitespaces, tabs and all - $querySql = Helper::cleanQuery($querySql); - $expected = Helper::cleanQuery($expected); - } - - // Test - $this->assertEquals($expected, $querySql); + $this->_testQuery($xml_file, $argsString, $expected, 'getInsertSql'); } + /** * Note: this test can fail when comaparing regdate from the $args with diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index bec501905..dddef4ffa 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -1,30 +1,10 @@ getNewParserOutputString($xml_file, '"', $argsString); - - //echo $outputString; - $output = eval($outputString); - - if(!is_a($output, 'Query')){ - if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; - }else { - //$db = new DBCubrid(); - $db = &DB::getInstance(); - $querySql = $db->getSelectSql($output); - - // Remove whitespaces, tabs and all - $querySql = Helper::cleanQuery($querySql); - $expected = Helper::cleanQuery($expected); - } - - // Test - $this->assertEquals($expected, $querySql); + function _test($xml_file, $argsString, $expected){ + $this->_testQuery($xml_file, $argsString, $expected, 'getSelectSql'); } function testSelectStar(){ diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php new file mode 100644 index 000000000..67657ea66 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php @@ -0,0 +1,77 @@ +xmlPath = str_replace('CubridSubqueryTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; + } + + function _test($xml_file, $argsString, $expected){ + $this->_testQuery($xml_file, $argsString, $expected, 'getSelectSql'); + } + + function testSelectUncorrelated1(){ + $xml_file = $this->xmlPath . "select_uncorrelated1.xml"; + echo $xml_file; + $argsString = '$args->user_id = 4; + '; + $expected = 'select "column_a" as "value_a" + , (select max("column_b") as "count" + from "xe_table_b" as "table_b" + ) as "value_b" + from "xe_table_a" as "table_a" + where "column_a" = 4'; + $this->_test($xml_file, $argsString, $expected); + } + + function testSelectUncorrelated2(){ + $xml_file = $this->xmlPath . "select_uncorrelated2.xml"; + echo $xml_file; + $argsString = '$args->user_id = 4; + $args->user_name = 7; + '; + $expected = 'SELECT "column_a" as "value_a" + , "column_b" as "value_b" + , "column_c" as "value_c" + , (SELECT max("column_b") as "count" + FROM "xe_table_b" as "table_b" + WHERE "column_ab" = 7) as "value_b" + FROM "xe_table_a" as "table_a" + WHERE "column_a" = 4'; + $this->_test($xml_file, $argsString, $expected); + } + + function testFromUncorrelated(){ + $xml_file = $this->xmlPath . "from_uncorrelated1.xml"; + echo $xml_file; + $argsString = '$args->user_id = 4; + $args->user_name = 7; + '; + $expected = 'select max("documentcountbymember"."count") as "maxcount" + from ( + select "member_srl" as "member_srl" + , count(*) as "count" + from "xe_documents" as "documents" + group by "member_srl" + ) as "documentcountbymember"'; + $this->_test($xml_file, $argsString, $expected); + } + + function testWhereUncorrelated(){ + $xml_file = $this->xmlPath . "where_uncorrelated1.xml"; + echo $xml_file; + $argsString = ''; + $expected = 'select * from + "xe_member" as "member" + where "regdate" = (select max("regdate") as "maxregdate" + from "xe_documents" as "documents")'; + $this->_test($xml_file, $argsString, $expected); + } + } +?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php index 2cee04153..c3b4accf6 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php @@ -1,26 +1,10 @@ getNewParserOutputString($xml_file, '"', $argsString); - $output = eval($outputString); - if(!is_a($output, 'Query')){ - if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; - }else { - $db = &DB::getInstance(); - $querySql = $db->getUpdateSql($output); - - // Remove whitespaces, tabs and all - $querySql = Helper::cleanQuery($querySql); - $expected = Helper::cleanQuery($expected); - } - - // Test - $this->assertEquals($expected, $querySql); + function _test($xml_file, $argsString, $expected){ + $this->_testQuery($xml_file, $argsString, $expected, 'getUpdateSql'); } function test_module_updateModule(){ diff --git a/test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php b/test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php deleted file mode 100644 index 410ae8dcd..000000000 --- a/test-phpUnit/db/xml_query/cubrid/config.cubrid.inc.php +++ /dev/null @@ -1,8 +0,0 @@ -db_type = 'cubrid'; - $db_info->db_table_prefix = 'xe'; - - $oContext->setDbInfo($db_info); -?> \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml b/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml new file mode 100644 index 000000000..64353bfb6 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated1.xml b/test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated1.xml new file mode 100644 index 000000000..00e556e35 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated1.xml @@ -0,0 +1,19 @@ + + +
+ + + + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated2.xml b/test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated2.xml new file mode 100644 index 000000000..a42294bcf --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/select_uncorrelated2.xml @@ -0,0 +1,24 @@ + + +
+ + + + + + +
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/where_uncorrelated1.xml b/test-phpUnit/db/xml_query/cubrid/data/where_uncorrelated1.xml new file mode 100644 index 000000000..248b63ae9 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/where_uncorrelated1.xml @@ -0,0 +1,18 @@ + + +
+ + + + + + + +
+ + + + + + + \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php index cba14e7a1..ce0c37777 100644 --- a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php +++ b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php @@ -1,36 +1,10 @@ getNewParserOutputString($xml_file, '[', $argsString); - //echo $outputString; - $output = eval($outputString); - - if(!is_a($output, 'Query')){ - if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; - }else { - $db = &DB::getInstance(); - $querySql = $db->getSelectSql($output); - $queryArguments = $output->getArguments(); - - // Remove whitespaces, tabs and all - $querySql = Helper::cleanQuery($querySql); - $expected = Helper::cleanQuery($expected); - } - - // Test - $this->assertEquals($expected, $querySql); - - // Test query arguments - $argCount = count($expectedArgs); - for($i = 0; $i < $argCount; $i++){ - //echo "$i: $expectedArgs[$i] vs $queryArguments[$i]->getValue()"; - $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue()); - } + $this->_testPreparedQuery($xml_file, $argsString, $expected, 'getSelectSql', $expectedArgs = NULL); } function testSelectStar(){ diff --git a/test-phpUnit/db/xml_query/mssql/config.mssql.inc.php b/test-phpUnit/db/xml_query/mssql/config.mssql.inc.php deleted file mode 100644 index 01040c220..000000000 --- a/test-phpUnit/db/xml_query/mssql/config.mssql.inc.php +++ /dev/null @@ -1,8 +0,0 @@ -db_type = 'mssql'; - $db_info->db_table_prefix = 'xe'; - - $oContext->setDbInfo($db_info); -?> \ No newline at end of file diff --git a/test-phpUnit/debug.php b/test-phpUnit/debug.php index 39208fd6e..1e788ca03 100644 --- a/test-phpUnit/debug.php +++ b/test-phpUnit/debug.php @@ -1,5 +1,6 @@ getParser(); From e313076cc8864143a1cde56e886b532365f00c7a Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 30 Jun 2011 18:14:24 +0000 Subject: [PATCH 53/82] Started unit tests for correlated subqueries - select, from, where. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8557 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../xmlquery/tags/table/TableTag.class.php | 22 +++++++--- .../xmlquery/tags/table/TablesTag.class.php | 19 ++++++++- test-phpUnit/db/DBTest.php | 7 +++- .../xml_query/cubrid/CubridSubqueryTest.php | 42 ++++++++++++++++--- .../cubrid/data/from_correlated1.xml | 27 ++++++++++++ .../cubrid/data/select_correlated1.xml | 22 ++++++++++ .../cubrid/data/where_correlated1.xml | 22 ++++++++++ 7 files changed, 147 insertions(+), 14 deletions(-) create mode 100644 test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/select_correlated1.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml diff --git a/classes/xml/xmlquery/tags/table/TableTag.class.php b/classes/xml/xmlquery/tags/table/TableTag.class.php index 125176bbd..6c047acdc 100644 --- a/classes/xml/xmlquery/tags/table/TableTag.class.php +++ b/classes/xml/xmlquery/tags/table/TableTag.class.php @@ -1,7 +1,6 @@ tag inside an XML Query file @@ -26,17 +25,22 @@ var $join_type; var $conditions; + /** + * @brief Initialises Table Tag properties + * @param XML
tag $table + */ function TableTag($table){ - $this->unescaped_name = $table->attrs->name; - $dbParser = XmlQueryParser::getDBParser(); + + $this->unescaped_name = $table->attrs->name; $this->name = $dbParser->parseTableName($table->attrs->name); - $this->alias = $table->attrs->alias; + + $this->alias = $table->attrs->alias; if(!$this->alias) $this->alias = $table->attrs->name; - //if(!$this->alias) $this->alias = $alias; $this->join_type = $table->attrs->type; - $this->conditions = $table->conditions; + + $this->conditions = $table->conditions; } function isJoinTable(){ @@ -53,6 +57,12 @@ return $this->unescaped_name; } + /** + * @brief Returns string for printing in PHP query cache file + * The string contains code for instantiation of either + * a Table or a JoinTable object + * @return string + */ function getTableString(){ $dbParser = XmlQueryParser::getDBParser(); if($this->isJoinTable()){ diff --git a/classes/xml/xmlquery/tags/table/TablesTag.class.php b/classes/xml/xmlquery/tags/table/TablesTag.class.php index 012a46b07..7ddadbc67 100644 --- a/classes/xml/xmlquery/tags/table/TablesTag.class.php +++ b/classes/xml/xmlquery/tags/table/TablesTag.class.php @@ -1,5 +1,21 @@ tag inside an XML Query file + * + * @abstract + * Example + * + *
+ * + * Attributes + * None. + * Children + * Can have children of type
or + */ + class TablesTag { var $tables; @@ -16,8 +32,7 @@ if(count($xml_tables)) require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); foreach($xml_tables as $table){ - if($table->name === 'query') $this->tables[] = new QueryTag($table, true); - else $this->tables[] = new TableTag($table); + $this->tables[] = new TableTag($table); } } if(!$xml_queries) return; diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php index d883f27c9..d03d645a2 100644 --- a/test-phpUnit/db/DBTest.php +++ b/test-phpUnit/db/DBTest.php @@ -2,10 +2,15 @@ class DBTest extends PHPUnit_Framework_TestCase { function _testQuery($xml_file, $argsString, $expected, $methodName){ + echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + echo $xml_file; + echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, $argsString); + echo $outputString; $output = eval($outputString); - + if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php index 67657ea66..57e98d46e 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php @@ -18,7 +18,6 @@ function testSelectUncorrelated1(){ $xml_file = $this->xmlPath . "select_uncorrelated1.xml"; - echo $xml_file; $argsString = '$args->user_id = 4; '; $expected = 'select "column_a" as "value_a" @@ -32,7 +31,6 @@ function testSelectUncorrelated2(){ $xml_file = $this->xmlPath . "select_uncorrelated2.xml"; - echo $xml_file; $argsString = '$args->user_id = 4; $args->user_name = 7; '; @@ -49,7 +47,6 @@ function testFromUncorrelated(){ $xml_file = $this->xmlPath . "from_uncorrelated1.xml"; - echo $xml_file; $argsString = '$args->user_id = 4; $args->user_name = 7; '; @@ -65,13 +62,48 @@ function testWhereUncorrelated(){ $xml_file = $this->xmlPath . "where_uncorrelated1.xml"; - echo $xml_file; $argsString = ''; $expected = 'select * from "xe_member" as "member" where "regdate" = (select max("regdate") as "maxregdate" from "xe_documents" as "documents")'; $this->_test($xml_file, $argsString, $expected); - } + } + + function testSelectCorrelated1(){ + $xml_file = $this->xmlPath . "select_correlated1.xml"; + $argsString = '$args->user_id = 7;'; + $expected = 'select *, + (select count(*) as "count" + from "xe_documents" as "documents" + where "documents"."user_id" = "member"."user_id" + ) as "totaldocumentcount" + from "xe_member" as "member" + where "user_id" = \'7\''; + $this->_test($xml_file, $argsString, $expected); + } + + function testWhereCorrelated1(){ + $xml_file = $this->xmlPath . "where_correlated1.xml"; + $argsString = ''; + $expected = ' SELECT * + FROM xe_member as member + WHERE regdate = (SELECT MAX(regdate) as regdate + FROM xe_documents as documents + WHERE documents.user_id = member.user_id)'; + $this->_test($xml_file, $argsString, $expected); + } + + function testFromCorrelated1(){ + $xml_file = $this->xmlPath . "from_correlated1.xml"; + $argsString = ''; + $expected = 'SELECT m.member_srl, m.nickname, m.regdate, a.count + FROM ( + SELECT documents.member_srl as member_srl, count(*) as count + FROM xe_documents as documents + GROUP BY documents.member_srl) a + INNER JOIN xe_members m on m.member_srl = a.member_srl'; + $this->_test($xml_file, $argsString, $expected); + } } ?> diff --git a/test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml b/test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml new file mode 100644 index 000000000..531d759a3 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml @@ -0,0 +1,27 @@ + + + + +
+ + + + + + + + + +
+ + + +
+
+ + + + + + +
\ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/select_correlated1.xml b/test-phpUnit/db/xml_query/cubrid/data/select_correlated1.xml new file mode 100644 index 000000000..797d878e3 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/select_correlated1.xml @@ -0,0 +1,22 @@ + + + + + + + + +
+ + + + + + + + + + + + + \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml b/test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml new file mode 100644 index 000000000..b39a8582d --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml @@ -0,0 +1,22 @@ + + +
+ + + + + + + +
+ + + + + + + + + + + \ No newline at end of file From 909276e16bdec28aaa1816918ba4026a023fca96 Mon Sep 17 00:00:00 2001 From: ucorina Date: Fri, 1 Jul 2011 08:15:43 +0000 Subject: [PATCH 54/82] Updates to unit tests for correlated subqueries. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8560 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/QueryParser.class.php | 2 +- .../xmlquery/tags/table/TablesTag.class.php | 34 ++++++++----------- test-phpUnit/QueryTester.class.php | 3 +- test-phpUnit/db/DBTest.php | 8 ++--- .../xml_query/cubrid/CubridSubqueryTest.php | 29 ++++++++++------ .../cubrid/data/from_correlated1.xml | 6 ++-- .../cubrid/data/from_uncorrelated1.xml | 4 +-- .../cubrid/data/where_correlated1.xml | 23 ++++++------- 8 files changed, 54 insertions(+), 55 deletions(-) diff --git a/classes/xml/xmlquery/QueryParser.class.php b/classes/xml/xmlquery/QueryParser.class.php index 5272c7857..08fda0f27 100644 --- a/classes/xml/xmlquery/QueryParser.class.php +++ b/classes/xml/xmlquery/QueryParser.class.php @@ -18,7 +18,7 @@ class QueryParser { function QueryParser($query, $isSubQuery = false){ $this->queryTag = new QueryTag($query, $isSubQuery); } - + function getTableInfo($query_id, $table_name){ $column_type = array(); diff --git a/classes/xml/xmlquery/tags/table/TablesTag.class.php b/classes/xml/xmlquery/tags/table/TablesTag.class.php index 7ddadbc67..32a95606e 100644 --- a/classes/xml/xmlquery/tags/table/TablesTag.class.php +++ b/classes/xml/xmlquery/tags/table/TablesTag.class.php @@ -16,31 +16,25 @@ * Can have children of type
or */ + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); + class TablesTag { var $tables; - function TablesTag($xml_tables_tag){ - $xml_tables = $xml_tables_tag->table; - $xml_queries = $xml_tables_tag->query; - + function TablesTag($xml_tables_tag){ $this->tables = array(); - - if($xml_tables){ - if(!is_array($xml_tables)) $xml_tables = array($xml_tables); - - if(count($xml_tables)) require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); - - foreach($xml_tables as $table){ - $this->tables[] = new TableTag($table); - } - } - if(!$xml_queries) return; - if(!is_array($xml_queries)) $xml_queries = array($xml_queries); - - foreach($xml_queries as $table){ - $this->tables[] = new QueryTag($table, true); - } + $xml_tables = $xml_tables_tag->table; + if(!is_array($xml_tables)) $xml_tables = array($xml_tables); + + foreach($xml_tables as $tag){ + if($tag->attrs->query == 'true'){ + $this->tables[] = new QueryTag($tag, true); + } + else { + $this->tables[] = new TableTag($tag); + } + } } function getTables(){ diff --git a/test-phpUnit/QueryTester.class.php b/test-phpUnit/QueryTester.class.php index 4ece64676..3fc911044 100644 --- a/test-phpUnit/QueryTester.class.php +++ b/test-phpUnit/QueryTester.class.php @@ -14,8 +14,7 @@ function getNewParserOutput($xml_file){ $newXmlQueryParser = new XmlQueryParser(); - $xml_obj = $newXmlQueryParser->getXmlFileContent($xml_file); - + $xml_obj = $newXmlQueryParser->getXmlFileContent($xml_file); $parser = new QueryParser($xml_obj->query); return $parser->toString(); } diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php index d03d645a2..073cefe05 100644 --- a/test-phpUnit/db/DBTest.php +++ b/test-phpUnit/db/DBTest.php @@ -2,13 +2,13 @@ class DBTest extends PHPUnit_Framework_TestCase { function _testQuery($xml_file, $argsString, $expected, $methodName){ - echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; - echo $xml_file; - echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + //echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + //echo $xml_file; + //echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, $argsString); - echo $outputString; + //echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php index 57e98d46e..63ce3f923 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php @@ -86,23 +86,30 @@ function testWhereCorrelated1(){ $xml_file = $this->xmlPath . "where_correlated1.xml"; $argsString = ''; - $expected = ' SELECT * - FROM xe_member as member - WHERE regdate = (SELECT MAX(regdate) as regdate - FROM xe_documents as documents - WHERE documents.user_id = member.user_id)'; + $expected = 'select * + from "xe_member" as "member" + where "regdate" = ( + select max("regdate") as "maxregdate" + from "xe_documents" as "documents" + where "documents"."user_id" = "member"."user_id" + )'; $this->_test($xml_file, $argsString, $expected); } function testFromCorrelated1(){ $xml_file = $this->xmlPath . "from_correlated1.xml"; $argsString = ''; - $expected = 'SELECT m.member_srl, m.nickname, m.regdate, a.count - FROM ( - SELECT documents.member_srl as member_srl, count(*) as count - FROM xe_documents as documents - GROUP BY documents.member_srl) a - INNER JOIN xe_members m on m.member_srl = a.member_srl'; + $expected = 'select "m"."member_srl" + , "m"."nickname" + , "m"."regdate" + , "a"."count" + from ( + select "member_srl" as "member_srl" + , count(*) as "count" + from "xe_documents" as "documents" + group by "member_srl" + ) as "a" + left join "xe_member" as "m" on "m"."member" = "a"."member_srl"'; $this->_test($xml_file, $argsString, $expected); } } diff --git a/test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml b/test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml index 531d759a3..7c2c27143 100644 --- a/test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml +++ b/test-phpUnit/db/xml_query/cubrid/data/from_correlated1.xml @@ -1,6 +1,6 @@ - +
@@ -11,8 +11,8 @@ - -
+
+ diff --git a/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml b/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml index 64353bfb6..ec83f3f36 100644 --- a/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml +++ b/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated1.xml @@ -1,6 +1,6 @@ - +
@@ -11,7 +11,7 @@ - +
diff --git a/test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml b/test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml index b39a8582d..f6115c71f 100644 --- a/test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml +++ b/test-phpUnit/db/xml_query/cubrid/data/where_correlated1.xml @@ -6,17 +6,16 @@ - - - - - - - - - - - - + + +
+ + + + + + + + \ No newline at end of file From 013ada255d8f1a76ff50d1cfe20959080517afca Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 5 Jul 2011 08:15:27 +0000 Subject: [PATCH 55/82] fix Argument and Condition argument type git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8562 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../xml/xmlquery/argument/Argument.class.php | 40 ++++--------------- .../argument/ConditionArgument.class.php | 39 +++++++++++++++++- .../queryargument/QueryArgument.class.php | 9 ++++- .../tags/navigation/IndexTag.class.php | 7 +++- .../xmlquery/tags/query/QueryTag.class.php | 7 ++-- 5 files changed, 61 insertions(+), 41 deletions(-) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index cf85710a6..a7c275ef9 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -3,21 +3,13 @@ class Argument { var $value; var $name; - var $type; var $isValid; var $errorMessage; function Argument($name, $value){ - $this->name = $name; - - if($this->type !== 'date'){ - $dbParser = XmlQueryParser::getDBParser(); - $this->value = $dbParser->escapeStringValue($value); - } - else - $this->value = $value; - + $this->value = $value; + $this->name = $name; $this->isValid = true; } @@ -40,22 +32,14 @@ } function escapeValue($value){ - if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ - if(!is_array($value)) - $value = '\''.$value.'\''; - else { - $total = count($value); - for($i = 0; $i < $total; $i++) - $value[$i] = '\''.$value[$i].'\''; - } - } - return $value; - } - - function getType(){ - return $this->type; + if(is_string($value)){ + $dbParser = XmlQueryParser::getDBParser(); + return $dbParser->parseExpression($value); + } + return $value; } + function isValid(){ return $this->isValid; } @@ -69,15 +53,7 @@ $this->value = $default_value; } - function setColumnType($column_type){ - if(!isset($this->value)) return; - if($column_type === '') return; - - $this->type = $column_type; - - //if($column_type === '') $column_type = 'varchar'; - } function checkFilter($filter_type){ if(isset($this->value) && $this->value != ''){ diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index cad112b90..2d0c526a1 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -2,10 +2,16 @@ class ConditionArgument extends Argument { var $operation; - + var $type; + function ConditionArgument($name, $value, $operation){ parent::Argument($name, $value); $this->operation = $operation; + + if($this->type !== 'date'){ + $dbParser = XmlQueryParser::getDBParser(); + $this->value = $dbParser->escapeStringValue($this->value); + } } function createConditionValue(){ @@ -119,6 +125,35 @@ */ } - } + + function getType(){ + return $this->type; + } + + function setColumnType($column_type){ + if(!isset($this->value)) return; + if($column_type === '') return; + + $this->type = $column_type; + + //if($column_type === '') $column_type = 'varchar'; + + } + + function escapeValue($value){ + if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ + if(!is_array($value)) + $value = '\''.$value.'\''; + else { + $total = count($value); + for($i = 0; $i < $total; $i++) + $value[$i] = '\''.$value[$i].'\''; + } + } + return $value; + } + + + } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index de5e8cfc9..5f7e0c73c 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -49,8 +49,13 @@ return $this->argument_validator->toString(); } + function isConditionArgument(){ + if($this->operation) return true; + return false; + } + function toString(){ - if($this->operation) + if($this->isConditionArgument()) $arg = sprintf("\n$%s_argument = new ConditionArgument('%s', %s, '%s');\n" , $this->argument_name , $this->argument_name @@ -67,7 +72,7 @@ $arg .= $this->argument_validator->toString(); - if($this->operation){ + if($this->isConditionArgument()){ $arg .= sprintf("$%s_argument->createConditionValue();\n" , $this->argument_name ); diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index 0d8f9829f..04e545696 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -10,11 +10,14 @@ function IndexTag($index){ $this->argument_name = $index->attrs->var; - $dbParser = XmlQueryParser::getDBParser(); - $index->attrs->default = $dbParser->parseExpression($index->attrs->default); + // Sort index - column by which to sort + //$dbParser = XmlQueryParser::getDBParser(); + //$index->attrs->default = $dbParser->parseExpression($index->attrs->default); $this->default = $index->attrs->default; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($index); + + // Sort order - asc / desc $this->sort_order = $index->attrs->order; if(!in_array($this->sort_order, array("asc", "desc"))){ $arg->var = $this->sort_order; diff --git a/classes/xml/xmlquery/tags/query/QueryTag.class.php b/classes/xml/xmlquery/tags/query/QueryTag.class.php index 4f45aac21..ee8379d13 100644 --- a/classes/xml/xmlquery/tags/query/QueryTag.class.php +++ b/classes/xml/xmlquery/tags/query/QueryTag.class.php @@ -86,9 +86,10 @@ class QueryTag { foreach($arguments as $argument){ if(isset($argument) && $argument->getArgumentName()){ $prebuff .= $argument->toString(); - $prebuff .= sprintf("$%s_argument->setColumnType('%s');\n" - , $argument->getArgumentName() - , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); + if($argument->isConditionArgument()) + $prebuff .= sprintf("$%s_argument->setColumnType('%s');\n" + , $argument->getArgumentName() + , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); } } $prebuff .= "\n"; From e9dca900318df6c8da10d7df99e3680c92bc2417 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Tue, 5 Jul 2011 15:53:52 +0000 Subject: [PATCH 56/82] fix Argument and ConditionArgument type git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8563 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../xml/xmlquery/argument/Argument.class.php | 27 ++++++++++++++++--- .../argument/ConditionArgument.class.php | 16 ++--------- .../xmlquery/tags/query/QueryTag.class.php | 5 ++-- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index a7c275ef9..2ebaa68ae 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -3,6 +3,7 @@ class Argument { var $value; var $name; + var $type; var $isValid; var $errorMessage; @@ -13,6 +14,16 @@ $this->isValid = true; } + function getType(){ + if(isset($this->type)) return $this->type; + if(is_string($this->value)) return 'column_name'; + return 'number'; + } + + function setColumnType($value){ + $this->type = $value; + } + function getName(){ return $this->name; } @@ -32,14 +43,22 @@ } function escapeValue($value){ - if(is_string($value)){ + if($this->getType() == 'column_name'){ $dbParser = XmlQueryParser::getDBParser(); return $dbParser->parseExpression($value); } - return $value; - } + if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ + if(!is_array($value)) + $value = '\''.$value.'\''; + else { + $total = count($value); + for($i = 0; $i < $total; $i++) + $value[$i] = '\''.$value[$i].'\''; + } + } + return $value; + } - function isValid(){ return $this->isValid; } diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index 2d0c526a1..4a3ffec2b 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -2,7 +2,7 @@ class ConditionArgument extends Argument { var $operation; - var $type; + function ConditionArgument($name, $value, $operation){ parent::Argument($name, $value); @@ -139,19 +139,7 @@ //if($column_type === '') $column_type = 'varchar'; } - - function escapeValue($value){ - if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ - if(!is_array($value)) - $value = '\''.$value.'\''; - else { - $total = count($value); - for($i = 0; $i < $total; $i++) - $value[$i] = '\''.$value[$i].'\''; - } - } - return $value; - } + } diff --git a/classes/xml/xmlquery/tags/query/QueryTag.class.php b/classes/xml/xmlquery/tags/query/QueryTag.class.php index ee8379d13..6631159fa 100644 --- a/classes/xml/xmlquery/tags/query/QueryTag.class.php +++ b/classes/xml/xmlquery/tags/query/QueryTag.class.php @@ -86,10 +86,11 @@ class QueryTag { foreach($arguments as $argument){ if(isset($argument) && $argument->getArgumentName()){ $prebuff .= $argument->toString(); - if($argument->isConditionArgument()) + $column_type = $this->column_type[$this->getQueryId()][$argument->getColumnName()]; + if(isset($column_type)) $prebuff .= sprintf("$%s_argument->setColumnType('%s');\n" , $argument->getArgumentName() - , $this->column_type[$this->getQueryId()][$argument->getColumnName()] ); + , $column_type ); } } $prebuff .= "\n"; From 4b85afd9b3b7a653b75051e9ba9ff0be149e1354 Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 5 Jul 2011 16:10:36 +0000 Subject: [PATCH 57/82] Update to subquery alias. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8564 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/Query.class.php | 3 ++- classes/db/queryparts/table/Table.class.php | 7 +++---- classes/xml/xmlquery/argument/Argument.class.php | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 93f36f739..0e21f8e81 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -178,7 +178,8 @@ foreach($this->tables as $table){ if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString($with_values) . ' '; else $from .= ', '.$table->toString($with_values) . ' '; - if(!$table->isJoinTable()) $from .= $table->getAlias() ? ' as ' . $table->getAlias() . ' ' : ' '; + + if(is_a($table, 'Subquery')) $from .= $table->getAlias() ? ' as ' . $table->getAlias() . ' ' : ' '; $simple_table_count++; } diff --git a/classes/db/queryparts/table/Table.class.php b/classes/db/queryparts/table/Table.class.php index 791a936d2..3a19d3a97 100644 --- a/classes/db/queryparts/table/Table.class.php +++ b/classes/db/queryparts/table/Table.class.php @@ -10,8 +10,8 @@ } function toString(){ - return $this->name; - //return sprintf("%s%s", $this->name, $this->alias ? ' as ' . $this->alias : ''); + //return $this->name; + return sprintf("%s%s", $this->name, $this->alias ? ' as ' . $this->alias : ''); } function getName(){ @@ -23,8 +23,7 @@ } function isJoinTable(){ - if(in_array($tableName,array('left join','left outer join','right join','right outer join'))) return true; - return false; + return false; } } diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 2ebaa68ae..a3ed14a56 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -32,7 +32,7 @@ $value = $this->escapeValue($this->value); return $this->toString($value); } - + function getUnescapedValue(){ return $this->toString($this->value); } From d248d70773b90dcb372c7d91b13eeff71cda57b0 Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 5 Jul 2011 19:49:20 +0000 Subject: [PATCH 58/82] Added subquery argument support to more types of queries. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8565 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../condition/ConditionGroupTag.class.php | 3 - .../tags/condition/ConditionTag.class.php | 8 +- .../xmlquery/tags/query/QueryTag.class.php | 1 + .../xmlquery/tags/table/TableTag.class.php | 13 ++- .../xmlquery/tags/table/TablesTag.class.php | 7 ++ test-phpUnit/db/DBTest.php | 29 +++--- .../xml_query/cubrid/CubridSubqueryTest.php | 99 ++++++++++++++++--- .../cubrid/data/from_correlated2.xml | 33 +++++++ .../cubrid/data/from_uncorrelated2.xml | 25 +++++ .../cubrid/data/select_correlated2.xml | 23 +++++ .../cubrid/data/where_correlated2.xml | 23 +++++ 11 files changed, 232 insertions(+), 32 deletions(-) create mode 100644 test-phpUnit/db/xml_query/cubrid/data/from_correlated2.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated2.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/select_correlated2.xml create mode 100644 test-phpUnit/db/xml_query/cubrid/data/where_correlated2.xml diff --git a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php index 4c7194160..1ddba44e6 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionGroupTag.class.php @@ -34,10 +34,7 @@ function getArguments(){ $arguments = array(); foreach($this->conditions as $condition){ - if(is_a($condition, 'QueryTag')) $arguments = array_merge($arguments, $condition->getArguments()); - else - $arguments[] = $condition->getArgument(); } return $arguments; } diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index cf224c0fb..19232141c 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -44,8 +44,12 @@ $this->pipe = $pipe; } - function getArgument(){ - return $this->argument; + function getArguments(){ + $arguments = array(); + if($this->query) + $arguments = array_merge($arguments, $this->query->getArguments()); + $arguments[] = $this->argument; + return $arguments; } function getConditionString(){ diff --git a/classes/xml/xmlquery/tags/query/QueryTag.class.php b/classes/xml/xmlquery/tags/query/QueryTag.class.php index 6631159fa..41c7db291 100644 --- a/classes/xml/xmlquery/tags/query/QueryTag.class.php +++ b/classes/xml/xmlquery/tags/query/QueryTag.class.php @@ -171,6 +171,7 @@ class QueryTag { $arguments = array(); if($this->columns) $arguments = array_merge($arguments, $this->columns->getArguments()); + $arguments = array_merge($arguments, $this->tables->getArguments()); $arguments = array_merge($arguments, $this->conditions->getArguments()); $arguments = array_merge($arguments, $this->navigation->getArguments()); return $arguments; diff --git a/classes/xml/xmlquery/tags/table/TableTag.class.php b/classes/xml/xmlquery/tags/table/TableTag.class.php index 6c047acdc..8fe35ff6f 100644 --- a/classes/xml/xmlquery/tags/table/TableTag.class.php +++ b/classes/xml/xmlquery/tags/table/TableTag.class.php @@ -24,7 +24,7 @@ var $alias; var $join_type; var $conditions; - + var $conditionsTag; /** * @brief Initialises Table Tag properties * @param XML
tag $table @@ -41,6 +41,9 @@ $this->join_type = $table->attrs->type; $this->conditions = $table->conditions; + + if($this->isJoinTable()) + $this->conditionsTag = new JoinConditionsTag($this->conditions); } function isJoinTable(){ @@ -66,16 +69,20 @@ function getTableString(){ $dbParser = XmlQueryParser::getDBParser(); if($this->isJoinTable()){ - $conditionsTag = new JoinConditionsTag($this->conditions); return sprintf('new JoinTable(\'%s\', \'%s\', "%s", %s)' , $dbParser->escape($this->name) , $dbParser->escape($this->alias) - , $this->join_type, $conditionsTag->toString()); + , $this->join_type, $this->conditionsTag->toString()); } return sprintf('new Table(\'%s\'%s)' , $dbParser->escape($this->name) , $this->alias ? ', \'' . $dbParser->escape($this->alias) .'\'' : ''); } + + function getArguments(){ + if(!isset($this->conditionsTag)) return array(); + return $this->conditionsTag->getArguments(); + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/table/TablesTag.class.php b/classes/xml/xmlquery/tags/table/TablesTag.class.php index 32a95606e..3c1d6fcdb 100644 --- a/classes/xml/xmlquery/tags/table/TablesTag.class.php +++ b/classes/xml/xmlquery/tags/table/TablesTag.class.php @@ -53,5 +53,12 @@ $output_tables .= ')'; return $output_tables; } + + function getArguments(){ + $arguments = array(); + foreach($this->tables as $table) + $arguments = array_merge($arguments, $table->getArguments()); + return $arguments; + } } ?> \ No newline at end of file diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php index 073cefe05..c4d43a02f 100644 --- a/test-phpUnit/db/DBTest.php +++ b/test-phpUnit/db/DBTest.php @@ -2,13 +2,13 @@ class DBTest extends PHPUnit_Framework_TestCase { function _testQuery($xml_file, $argsString, $expected, $methodName){ - //echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; - //echo $xml_file; - //echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + echo $xml_file; + echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, $argsString); - //echo $outputString; + echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ @@ -18,8 +18,8 @@ $querySql = $db->{$methodName}($output); // Remove whitespaces, tabs and all - $querySql = Helper::cleanQuery($querySql); - $expected = Helper::cleanQuery($expected); + $querySql = Helper::cleanString($querySql); + $expected = Helper::cleanString($expected); } $this->assertEquals($expected, $querySql); } @@ -37,8 +37,8 @@ $queryArguments = $output->getArguments(); // Remove whitespaces, tabs and all - $querySql = Helper::cleanQuery($querySql); - $expected = Helper::cleanQuery($expected); + $querySql = Helper::cleanString($querySql); + $expected = Helper::cleanString($expected); } // Test @@ -51,9 +51,14 @@ $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue()); } } + + function _testCachedOutput($expected, $actual){ + $expected = Helper::cleanString($expected); + $actual = Helper::cleanString($actual); + + $this->assertEquals($expected, $actual); + + } } -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ + ?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php index 63ce3f923..81fbcf5b1 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSubqueryTest.php @@ -19,7 +19,7 @@ function testSelectUncorrelated1(){ $xml_file = $this->xmlPath . "select_uncorrelated1.xml"; $argsString = '$args->user_id = 4; - '; + '; $expected = 'select "column_a" as "value_a" , (select max("column_b") as "count" from "xe_table_b" as "table_b" @@ -45,7 +45,7 @@ $this->_test($xml_file, $argsString, $expected); } - function testFromUncorrelated(){ + function testFromUncorrelated1(){ $xml_file = $this->xmlPath . "from_uncorrelated1.xml"; $argsString = '$args->user_id = 4; $args->user_name = 7; @@ -58,17 +58,40 @@ group by "member_srl" ) as "documentcountbymember"'; $this->_test($xml_file, $argsString, $expected); - } + } - function testWhereUncorrelated(){ - $xml_file = $this->xmlPath . "where_uncorrelated1.xml"; - $argsString = ''; - $expected = 'select * from - "xe_member" as "member" - where "regdate" = (select max("regdate") as "maxregdate" - from "xe_documents" as "documents")'; +// function testFromUncorrelated2(){ +// $xml_file = $this->xmlPath . "from_uncorrelated1.xml"; +// $argsString = '$args->user_id = 4; +// $args->user_name = 7; +// '; +// $expected = 'select max("documentcountbymember"."count") as "maxcount" +// from ( +// select "member_srl" as "member_srl" +// , count(*) as "count" +// from "xe_documents" as "documents" +// group by "member_srl" +// ) as "documentcountbymember"'; +// $this->_test($xml_file, $argsString, $expected); +// } + + function testFromUncorrelated2(){ + $xml_file = $this->xmlPath . "from_uncorrelated2.xml"; + $argsString = '$args->member_srl = 4; + $args->module_srl = 7; + '; + $expected = 'select max("documentcountbymember"."count") as "maxcount" + from ( + select "member_srl" as "member_srl" + , count(*) as "count" + from "xe_documents" as "documents" + where "module_srl" = 7 + group by "member_srl" + ) as "documentcountbymember" + where "member_srl" = 4 + '; $this->_test($xml_file, $argsString, $expected); - } + } function testSelectCorrelated1(){ $xml_file = $this->xmlPath . "select_correlated1.xml"; @@ -83,6 +106,22 @@ $this->_test($xml_file, $argsString, $expected); } + function testSelectCorrelated2(){ + $xml_file = $this->xmlPath . "select_correlated2.xml"; + $argsString = '$args->user_id = 7; + $args->module_srl = 17; + '; + $expected = 'select *, + (select count(*) as "count" + from "xe_documents" as "documents" + where "documents"."user_id" = "member"."user_id" + and "module_srl" = 17 + ) as "totaldocumentcount" + from "xe_member" as "member" + where "user_id" = \'7\''; + $this->_test($xml_file, $argsString, $expected); + } + function testWhereCorrelated1(){ $xml_file = $this->xmlPath . "where_correlated1.xml"; $argsString = ''; @@ -96,6 +135,22 @@ $this->_test($xml_file, $argsString, $expected); } + function testWhereCorrelated2(){ + $xml_file = $this->xmlPath . "where_correlated2.xml"; + $argsString = '$args->module_srl = 12; $args->member_srl = 19;'; + $expected = 'select * + from "xe_member" as "member" + where "member_srl" = 19 + and "regdate" = ( + select max("regdate") as "maxregdate" + from "xe_documents" as "documents" + where "documents"."user_id" = "member"."user_id" + and "module_srl" = 12 + ) + '; + $this->_test($xml_file, $argsString, $expected); + } + function testFromCorrelated1(){ $xml_file = $this->xmlPath . "from_correlated1.xml"; $argsString = ''; @@ -111,6 +166,26 @@ ) as "a" left join "xe_member" as "m" on "m"."member" = "a"."member_srl"'; $this->_test($xml_file, $argsString, $expected); - } + } + + function testFromCorrelated2(){ + $xml_file = $this->xmlPath . "from_correlated2.xml"; + $argsString = '$args->module_srl = 12; $args->count = 20;'; + $expected = 'select "m"."member_srl" + , "m"."nickname" + , "m"."regdate" + , "a"."count" + from ( + select "member_srl" as "member_srl" + , count(*) as "count" + from "xe_documents" as "documents" + where "module_srl" = 12 + group by "member_srl" + ) as "a" + left join "xe_member" as "m" on "m"."member" = "a"."member_srl" + where "a"."count" >= 20 +'; + $this->_test($xml_file, $argsString, $expected); + } } ?> diff --git a/test-phpUnit/db/xml_query/cubrid/data/from_correlated2.xml b/test-phpUnit/db/xml_query/cubrid/data/from_correlated2.xml new file mode 100644 index 000000000..8dc162154 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/from_correlated2.xml @@ -0,0 +1,33 @@ + + +
+ +
+ + + + + + + + + + + +
+ + + + +
+
+ + + + + + + + + +
\ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated2.xml b/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated2.xml new file mode 100644 index 000000000..6431b3b90 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/from_uncorrelated2.xml @@ -0,0 +1,25 @@ + + + + +
+ + + + + + + + + + + +
+
+ + + + + + +
\ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/select_correlated2.xml b/test-phpUnit/db/xml_query/cubrid/data/select_correlated2.xml new file mode 100644 index 000000000..85ab25308 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/select_correlated2.xml @@ -0,0 +1,23 @@ + + + + + + + + +
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/data/where_correlated2.xml b/test-phpUnit/db/xml_query/cubrid/data/where_correlated2.xml new file mode 100644 index 000000000..2ab45461c --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/data/where_correlated2.xml @@ -0,0 +1,23 @@ + + +
+ + + + + + + + +
+ + + + + + + + + + + \ No newline at end of file From 7112d518c8eae0815435ae9902cc1275716a5f8a Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 5 Jul 2011 19:52:27 +0000 Subject: [PATCH 59/82] Added unit tests for Table, TableTag and TablesTag classes. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8566 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- test-phpUnit/Helper.class.php | 7 +- .../classes/db/queryparts/table/TableTest.php | 42 +++++++ .../xml/xmlquery/tags/table/TableTagTest.php | 4 +- .../xml/xmlquery/tags/table/TablesTagTest.php | 114 ++++++++++++++++++ .../tags/table/data/tables_one_table.xml | 3 + .../table/data/tables_two_tables_no_join.xml | 4 + .../data/tables_two_tables_with_join.xml | 8 ++ 7 files changed, 178 insertions(+), 4 deletions(-) create mode 100644 test-phpUnit/classes/db/queryparts/table/TableTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/TablesTagTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_one_table.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_no_join.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_with_join.xml diff --git a/test-phpUnit/Helper.class.php b/test-phpUnit/Helper.class.php index 68a122883..597d52ac3 100644 --- a/test-phpUnit/Helper.class.php +++ b/test-phpUnit/Helper.class.php @@ -1,14 +1,17 @@ object = new Table('"xe_member"', '"m"'); + } + + protected function tearDown() + { + } + + public function testToString() + { + $this->assertEquals('"xe_member" as "m"', $this->object->toString()); + } + + public function testGetName() + { + $this->assertEquals('"xe_member"', $this->object->getName()); + } + + public function testGetAlias() + { + $this->assertEquals('"m"', $this->object->getAlias()); + } + + public function testIsJoinTable() + { + $this->assertEquals(false, $this->object->isJoinTable()); + } +} +?> diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php b/test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php index 1312199fd..1e7c86d74 100644 --- a/test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/TableTagTest.php @@ -63,8 +63,8 @@ new Condition(\'"module_categories"."module_category_srl"\',\'"modules"."module_category_srl"\',"equal") )) ))'; - $actual = Helper::cleanQuery($actual); - $expected = Helper::cleanQuery($expected); + $actual = Helper::cleanString($actual); + $expected = Helper::cleanString($expected); $this->assertEquals($expected, $actual); } diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/TablesTagTest.php b/test-phpUnit/classes/xml/xmlquery/tags/table/TablesTagTest.php new file mode 100644 index 000000000..5181cafbd --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/TablesTagTest.php @@ -0,0 +1,114 @@ +xmlPath = str_replace('TablesTagTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; + } + + /** + * Tests a simple tag: + * + *
+ * + */ + function testTablesTagWithOneTable(){ + $xml_file = $this->xmlPath . "tables_one_table.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new TablesTag($xml_obj->tables); + + $expected = "array(new Table('\"xe_member\"', '\"member\"'))"; + $actual = $tag->toString(); + + $this->_testCachedOutput($expected, $actual); + } + + /** + * Tests a simple tag: + * + *
+ *
+ * + */ + function testTablesTagWithTwoTablesNoJoin(){ + $xml_file = $this->xmlPath . "tables_two_tables_no_join.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new TablesTag($xml_obj->tables); + + $expected = "array( + new Table('\"xe_member_group\"', '\"a\"') + ,new Table('\"xe_member_group_member\"', '\"b\"') + )"; + $actual = $tag->toString(); + + $this->_testCachedOutput($expected, $actual); + } + + /** + * Tests a simple tag: + * + *
+ *
+ * + * + * + *
+ *
+ */ + function testTablesTagWithTwoTablesWithJoin(){ + $xml_file = $this->xmlPath . "tables_two_tables_with_join.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new TablesTag($xml_obj->tables); + + $expected = "array( + new Table('\"xe_files\"', '\"files\"') + ,new JoinTable('\"xe_member\"' + , '\"member\"' + , \"left join\" + , array( + new ConditionGroup( + array( + new Condition( + '\"files\".\"member_srl\"' + ,'\"member\".\"member_srl\"' + ,\"equal\" + ) + ) + ) + ) + ) + )"; + $actual = $tag->toString(); + + $this->_testCachedOutput($expected, $actual); + } + + /** + * Tests a simple tag: + * + * + *
+ * + * + * + *
+ *
+ */ + function testGetTables(){ + $xml_file = $this->xmlPath . "tables_two_tables_with_join.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new TablesTag($xml_obj->tables); + + $tables = $tag->getTables(); + + $this->assertEquals(2, count($tables)); + $this->assertTrue(is_a($tables[0], 'TableTag')); + $this->assertTrue(is_a($tables[1], 'TableTag')); + } + } \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_one_table.xml b/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_one_table.xml new file mode 100644 index 000000000..525df54be --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_one_table.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_no_join.xml b/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_no_join.xml new file mode 100644 index 000000000..cdedcb831 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_no_join.xml @@ -0,0 +1,4 @@ + +
+
+ \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_with_join.xml b/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_with_join.xml new file mode 100644 index 000000000..fd8d8775e --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/table/data/tables_two_tables_with_join.xml @@ -0,0 +1,8 @@ + +
+
+ + + +
+
\ No newline at end of file From 76019a4b2b6315e78afcefd21ee5208ff37c7b35 Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 7 Jul 2011 14:34:56 +0000 Subject: [PATCH 60/82] Started unit tests for condition and argument classes. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8577 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../queryparts/condition/Condition.class.php | 2 + .../argument/ConditionArgument.class.php | 211 ++++++++-------- .../queryargument/QueryArgument.class.php | 4 +- .../tags/condition/ConditionTag.class.php | 3 +- .../db/queryparts/condition/ConditionTest.php | 43 ++++ .../xml/xmlquery/argument/ArgumentTest.php | 232 ++++++++++++++++++ .../argument/ConditionArgumentTest.php | 40 +++ .../queryargument/QueryArgumentTest.php | 35 +++ .../queryargument/data/condition1.xml | 1 + .../xmlquery/queryargument/data/index1.xml | 1 + .../tags/condition/ConditionTagTest.php | 68 +++++ .../tags/condition/data/condition1.xml | 1 + .../tags/condition/data/condition2.xml | 1 + .../tags/condition/data/condition3.xml | 1 + test-phpUnit/config/config.inc.php | 2 + 15 files changed, 537 insertions(+), 108 deletions(-) create mode 100644 test-phpUnit/classes/db/queryparts/condition/ConditionTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/queryargument/data/condition1.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/queryargument/data/index1.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition1.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition2.xml create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition3.xml diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index fdeaeeaae..addab276c 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -31,6 +31,7 @@ } function toString($withValue = true){ + if(!$this->show()) return ''; if($withValue) return $this->toStringWithValue(); return $this->toStringWithoutValue(); @@ -51,6 +52,7 @@ } function show(){ + if($this->hasArgument() && !$this->argument->isValid()) return false; switch($this->operation) { case 'equal' : case 'more' : diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index 4a3ffec2b..421bf85a2 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -17,113 +17,114 @@ function createConditionValue(){ if(!isset($this->value)) return; - $name = $this->column_name; - $operation = $this->operation; - $value = $this->value; - - switch($operation) { - case 'like_prefix' : - $this->value = $value.'%'; - break; - case 'like_tail' : - $this-> value = '%'.$value; - break; - case 'like' : - $this->value = '%'.$value.'%'; - break; - case 'in' : - if(is_array($value)) - { - //$value = $this->addQuotesArray($value); - //if($type=='number') return join(',',$value); - //else - //$this->value = "['". join("','",$value)."']"; - } - else - { - $this->value = $value; - } - break; - } - /* - //if(!in_array($operation,array('in','notin','between')) && is_array($value)){ - // $value = join(',', $value); - //} - // Daca operatia nu este in, notin, between si coloana e de tip numeric - // daca valoarea e array -> concatenare - // daca valoarea nu e array si nici nu contine paranteze (nu e functie) -> return (int) - // altfel return valoare - -// if(!in_array($operation,array('in','notin','between')) && $type == 'number') { -// if(is_array($value)){ -// $value = join(',',$value); -// } -// if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; -// return $value; -// } -// -// if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { -// list($table_name, $column_name) = explode('.', $value); -// if($column_type[$column_name]) return $value; -// } + $name = $this->column_name; + $operation = $this->operation; + $value = $this->value; - switch($operation) { - case 'like_prefix' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = $value.'%'; - break; - case 'like_tail' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value; - break; - case 'like' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value.'%'; - break; -// case 'notin' : -// if(is_array($value)) -// { -// $value = $this->addQuotesArray($value); -// if($type=='number') return join(',',$value); -// else return "'". join("','",$value)."'"; -// } -// else -// { -// return $value; -// } -// break; -// case 'in' : -// if(is_array($value)) -// { -// $value = $this->addQuotesArray($value); -// if($type=='number') return join(',',$value); -// else return "'". join("','",$value)."'"; -// } -// else -// { -// return $value; -// } -// break; -// case 'between' : -// if(!is_array($value)) $value = array($value); -// $value = $this->addQuotesArray($value); -// if($type!='number') -// { -// foreach($value as $k=>$v) -// { -// $value[$k] = "'".$v."'"; -// } -// } + switch($operation) { + case 'like_prefix' : + $this->value = $value.'%'; + break; + case 'like_tail' : + $this->value = '%'.$value; + break; + case 'like' : + $this->value = '%'.$value.'%'; + break; + case 'in' : + if(is_array($value)) + { + //$value = $this->addQuotesArray($value); + if($this->getType() == 'number') + $this->value = "(" . join(',',$value) . ")"; + else + $this->value = "('". join("','",$value)."')"; + } + else + { + $this->value = $value; + } + break; + } + /* + //if(!in_array($operation,array('in','notin','between')) && is_array($value)){ + // $value = join(',', $value); + //} + // Daca operatia nu este in, notin, between si coloana e de tip numeric + // daca valoarea e array -> concatenare + // daca valoarea nu e array si nici nu contine paranteze (nu e functie) -> return (int) + // altfel return valoare + + // if(!in_array($operation,array('in','notin','between')) && $type == 'number') { + // if(is_array($value)){ + // $value = join(',',$value); + // } + // if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; + // return $value; + // } + // + // if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { + // list($table_name, $column_name) = explode('.', $value); + // if($column_type[$column_name]) return $value; + // } + + switch($operation) { + case 'like_prefix' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = $value.'%'; + break; + case 'like_tail' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = '%'.$value; + break; + case 'like' : + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + $value = '%'.$value.'%'; + break; + // case 'notin' : + // if(is_array($value)) + // { + // $value = $this->addQuotesArray($value); + // if($type=='number') return join(',',$value); + // else return "'". join("','",$value)."'"; + // } + // else + // { + // return $value; + // } + // break; + // case 'in' : + // if(is_array($value)) + // { + // $value = $this->addQuotesArray($value); + // if($type=='number') return join(',',$value); + // else return "'". join("','",$value)."'"; + // } + // else + // { + // return $value; + // } + // break; + // case 'between' : + // if(!is_array($value)) $value = array($value); + // $value = $this->addQuotesArray($value); + // if($type!='number') + // { + // foreach($value as $k=>$v) + // { + // $value[$k] = "'".$v."'"; + // } + // } + + //return $value; + break; + default: + if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); + } + $this->value = $value; + //return "'".$this->addQuotes($value)."'"; + */ - //return $value; - break; - default: - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - } - $this->value = $value; - //return "'".$this->addQuotes($value)."'"; - */ - } function getType(){ diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index 5f7e0c73c..3257ce17f 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -23,8 +23,8 @@ if(!$name) $name = $tag->attrs->column; if(strpos($name, '.') === false) $this->column_name = $name; else { - list($prefix, $name) = explode('.', $name); - $this->column_name = $name; + list($prefix, $name) = explode('.', $name); + $this->column_name = $name; } if($tag->attrs->operation) $this->operation = $tag->attrs->operation; diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index 19232141c..817603656 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -48,7 +48,8 @@ $arguments = array(); if($this->query) $arguments = array_merge($arguments, $this->query->getArguments()); - $arguments[] = $this->argument; + if($this->argument) + $arguments[] = $this->argument; return $arguments; } diff --git a/test-phpUnit/classes/db/queryparts/condition/ConditionTest.php b/test-phpUnit/classes/db/queryparts/condition/ConditionTest.php new file mode 100644 index 000000000..20452df0b --- /dev/null +++ b/test-phpUnit/classes/db/queryparts/condition/ConditionTest.php @@ -0,0 +1,43 @@ +assertEquals(' "member_srl" = 20', $tag->toString()); + } + + /** + * Checks equal operation + */ + public function testConditionString_Equal_WithPipe_NumericValue() { + $member_srl_argument = new ConditionArgument('"member_srl"', 20, 'equal'); + + $tag = new Condition('"member_srl"', $member_srl_argument, 'equal', 'and'); + + $this->assertEquals('and "member_srl" = 20', $tag->toString()); + } + + /** + * Checks condition returns nothing when argument is not valid + */ + public function testConditionString_InvalidArgument() { + $member_srl_argument = new ConditionArgument('"member_srl"', null, 'equal'); + $member_srl_argument->checkNotNull(); + + $tag = new Condition('"member_srl"', $member_srl_argument, 'equal', 'and'); + + $this->assertEquals('', $tag->toString()); + } +} + +?> diff --git a/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php new file mode 100644 index 000000000..45e893743 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php @@ -0,0 +1,232 @@ +markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testSetColumnType(). + */ + public function testSetColumnType() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testGetName(). + */ + public function testGetName() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testGetValue(). + */ + public function testGetValue() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testGetUnescapedValue(). + */ + public function testGetUnescapedValue() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testToString(). + */ + public function testToString() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testEscapeValue(). + */ + public function testEscapeValue() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testIsValid(). + */ + public function testIsValid() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testGetErrorMessage(). + */ + public function testGetErrorMessage() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testEnsureDefaultValue(). + */ + public function testEnsureDefaultValue() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testCheckFilter(). + */ + public function testCheckFilter() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testCheckMaxLength(). + */ + public function testCheckMaxLength() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testCheckMinLength(). + */ + public function testCheckMinLength() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * Checks that argument is valid after a notnull check when value is not null + */ + public function testCheckNotNullWhenNotNull() { + $member_srl_argument = new ConditionArgument('member_srl', 20, 'equal'); + $member_srl_argument->checkNotNull(); + + $this->assertEquals(true, $member_srl_argument->isValid()); + } + + /** + * Checks that argument becomes invalid after a notnull check when value is null + */ + public function testCheckNotNullWhenNull() { + $member_srl_argument = new ConditionArgument('member_srl', null, 'equal'); + $member_srl_argument->checkNotNull(); + + $this->assertEquals(false, $member_srl_argument->isValid()); + } + + /** + * Checks that argument value stays the same when both user value and default value are given + */ + public function testCheckDefaultValueWhenNotNull() { + $member_srl_argument = new ConditionArgument('member_srl', 20, 'equal'); + $member_srl_argument->ensureDefaultValue(25); + + $this->assertEquals(20, $member_srl_argument->getValue()); + } + + /** + * Checks that argument value gets set when user value is null and default value is specified + */ + public function testCheckDefaultValueWhenNull() { + $member_srl_argument = new ConditionArgument('member_srl', null, 'equal'); + $member_srl_argument->ensureDefaultValue(25); + + $this->assertEquals(25, $member_srl_argument->getValue()); + } + + /** + * Checks like prefix operation + */ + public function testCreateConditionValue_LikePrefix() { + $member_srl_argument = new ConditionArgument('"mid"', 'forum', 'like_prefix'); + $member_srl_argument->createConditionValue(); + + $this->assertEquals('forum%', $member_srl_argument->getValue()); + } + + /** + * Checks like tail operation + */ + public function testCreateConditionValue_LikeTail() { + $member_srl_argument = new ConditionArgument('"mid"', 'forum', 'like_tail'); + $member_srl_argument->createConditionValue(); + + $this->assertEquals('%forum', $member_srl_argument->getValue()); + } + + /** + * Checks like operation + */ + public function testCreateConditionValue_Like() { + $member_srl_argument = new ConditionArgument('"mid"', 'forum', 'like'); + $member_srl_argument->createConditionValue(); + + $this->assertEquals('%forum%', $member_srl_argument->getValue()); + } + + + /** + * Checks in operation + */ + public function testCreateConditionValue_In_StringValues() { + $member_srl_argument = new ConditionArgument('"mid"', array('forum', 'board'), 'in'); + $member_srl_argument->createConditionValue(); + + $this->assertEquals('(\'forum\',\'board\')', $member_srl_argument->getValue()); + } + + /** + * Checks in operation + */ + public function testCreateConditionValue_In_NumericValues() { + $member_srl_argument = new ConditionArgument('"module_srl"', array(3, 21), 'in'); + $member_srl_argument->setColumnType('number'); + $member_srl_argument->createConditionValue(); + + $this->assertEquals('(3,21)', $member_srl_argument->getValue()); + } +} + +?> diff --git a/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php new file mode 100644 index 000000000..d2f386b0b --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php @@ -0,0 +1,40 @@ +markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testGetType(). + */ + public function testGetType() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @todo Implement testSetColumnType(). + */ + public function testSetColumnType() { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + +} + +?> diff --git a/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php new file mode 100644 index 000000000..ec40ce9d9 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php @@ -0,0 +1,35 @@ +xmlPath = str_replace('QueryArgumentTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; + } + + function testNotNullConditionArgument(){ + $xml_file = $this->xmlPath . "condition1.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new QueryArgument($xml_obj->condition); + + $this->assertEquals("member_srl", $tag->getArgumentName()); + $this->assertEquals("member_srl", $tag->getColumnName()); + $this->assertEquals(true, $tag->isConditionArgument()); + + $actual = $tag->toString(); + $expected = ' $member_srl_argument = new ConditionArgument(\'member_srl\', $args->member_srl, \'equal\'); + $member_srl_argument->checkNotNull(); + $member_srl_argument->createConditionValue(); + if(!$member_srl_argument->isValid()) return $member_srl_argument->getErrorMessage();'; + $this->assertEquals($expected, $actual); + } + + + +} + +?> diff --git a/test-phpUnit/classes/xml/xmlquery/queryargument/data/condition1.xml b/test-phpUnit/classes/xml/xmlquery/queryargument/data/condition1.xml new file mode 100644 index 000000000..53decc580 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/queryargument/data/condition1.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/queryargument/data/index1.xml b/test-phpUnit/classes/xml/xmlquery/queryargument/data/index1.xml new file mode 100644 index 000000000..6cbf9193a --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/queryargument/data/index1.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php b/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php new file mode 100644 index 000000000..6ac7e6036 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php @@ -0,0 +1,68 @@ +xmlPath = str_replace('ConditionTagTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; + } + + /** + * Tests a simple tag: + * + */ + function testConditionStringWithArgument(){ + $xml_file = $this->xmlPath . "condition1.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new ConditionTag($xml_obj->condition); + + $expected = "new Condition('\"user_id\"',\$user_id_argument,\"equal\")"; + $actual = $tag->getConditionString(); + $this->assertEquals($expected, $actual); + + $arguments = $tag->getArguments(); + $this->assertEquals(1, count($arguments)); + } + + /** + * Tests a condition tag for joins - that uses no argument + * + */ + function testConditionStringWithoutArgument(){ + $xml_file = $this->xmlPath . "condition3.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new ConditionTag($xml_obj->condition); + + $expected = "new Condition('\"comments\".\"user_id\"','\"member\".\"user_id\"',\"equal\")"; + $actual = $tag->getConditionString(); + $this->assertEquals($expected, $actual); + + $arguments = $tag->getArguments(); + $this->assertEquals(0, count($arguments)); + } + + + /** + * Tests a tag with pipe: + * + */ + function testConditionStringWithPipe(){ + $xml_file = $this->xmlPath . "condition2.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new ConditionTag($xml_obj->condition); + + $expected = "new Condition('\"type\"',\$type_argument,\"equal\", 'and')"; + $actual = $tag->getConditionString(); + $this->assertEquals($expected, $actual); + + $arguments = $tag->getArguments(); + $this->assertEquals(1, count($arguments)); + } + +} + +?> diff --git a/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition1.xml b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition1.xml new file mode 100644 index 000000000..274121640 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition1.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition2.xml b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition2.xml new file mode 100644 index 000000000..7ace26b8d --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition2.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition3.xml b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition3.xml new file mode 100644 index 000000000..538d81f3d --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition3.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/test-phpUnit/config/config.inc.php b/test-phpUnit/config/config.inc.php index 991db29f8..3fe95835d 100644 --- a/test-phpUnit/config/config.inc.php +++ b/test-phpUnit/config/config.inc.php @@ -41,5 +41,7 @@ require_once(_XE_PATH_.'classes/db/queryparts/Subquery.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); ?> \ No newline at end of file From 652cc1549a159c2e7cf734ccd9896c684b38afe5 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Fri, 8 Jul 2011 14:04:50 +0000 Subject: [PATCH 61/82] fix a bug where empty argument were escaped git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8584 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/argument/Argument.class.php | 1 + 1 file changed, 1 insertion(+) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index a3ed14a56..2d48a3a48 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -47,6 +47,7 @@ $dbParser = XmlQueryParser::getDBParser(); return $dbParser->parseExpression($value); } + if(!isset($value) || $value === '') return null; if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ if(!is_array($value)) $value = '\''.$value.'\''; From 54ef159878c83cf052ff0aa600da701c6bd7e102 Mon Sep 17 00:00:00 2001 From: ucorina Date: Fri, 8 Jul 2011 15:10:42 +0000 Subject: [PATCH 62/82] Added support for addQuotes - escpaes special charcters in query arguments. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8585 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 1 - classes/xml/xmlquery/argument/Argument.class.php | 12 ++++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index b91eace42..92ab43252 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -121,7 +121,6 @@ /** * @brief handles quatation of the string variables from the query **/ - // TODO Make sure this is handled in DBParser class function addQuotes($string) { if (!$this->fd) return $string; diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 2d48a3a48..063244400 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -50,16 +50,24 @@ if(!isset($value) || $value === '') return null; if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ if(!is_array($value)) - $value = '\''.$value.'\''; + $value = $this->_escapeStringValue ($value); else { $total = count($value); for($i = 0; $i < $total; $i++) - $value[$i] = '\''.$value[$i].'\''; + $value[$i] = $this->_escapeStringValue($value[$i]); + //$value[$i] = '\''.$value[$i].'\''; } } return $value; } + function _escapeStringValue($value){ + $db = &DB::getInstance(); + $value = $db->addQuotes($value); + return '\''.$value.'\''; + + } + function isValid(){ return $this->isValid; } From 9606e263e8ccde9295bc68acdbb5d5d866b53501 Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 14 Jul 2011 17:00:16 +0000 Subject: [PATCH 63/82] Added classes for testing db queries directly on a test database. Fixed a few insert bugs. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8600 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBCubrid.class.php | 2 +- .../xml/xmlquery/argument/Argument.class.php | 2 +- .../xml/xmlquery/argument/ArgumentTest.php | 16 +++++ test-phpUnit/config/config.inc.php | 20 +++--- test-phpUnit/db/CubridOnlineTest.php | 38 ++++++++++ test-phpUnit/db/CubridTest.php | 13 ++-- .../cubrid/CubridInsertOnlineTest.php | 69 +++++++++++++++++++ .../db/xml_query/cubrid/CubridInsertTest.php | 12 ++-- .../cubrid/CubridSelectOnlineTest.php | 22 ++++++ 9 files changed, 173 insertions(+), 21 deletions(-) create mode 100644 test-phpUnit/db/CubridOnlineTest.php create mode 100644 test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php create mode 100644 test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 92ab43252..e4f28ebae 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -207,7 +207,7 @@ $this->actFinish (); // Return the result - return $result; + return $result; } /** diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 063244400..4111508b3 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -47,7 +47,7 @@ $dbParser = XmlQueryParser::getDBParser(); return $dbParser->parseExpression($value); } - if(!isset($value) || $value === '') return null; + if(!isset($value)) return null; if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ if(!is_array($value)) $value = $this->_escapeStringValue ($value); diff --git a/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php index 45e893743..0a8180777 100644 --- a/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php +++ b/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php @@ -227,6 +227,22 @@ class ArgumentTest extends CubridTest { $this->assertEquals('(3,21)', $member_srl_argument->getValue()); } + + public function testEnsureDefaultValueWithEmptyString(){ + $homepage_argument = new Argument('homepage', ''); + $homepage_argument->ensureDefaultValue(''); + $homepage_argument->checkFilter('homepage'); + if(!$homepage_argument->isValid()) return $homepage_argument->getErrorMessage(); + $homepage_argument->setColumnType('varchar'); + + + $this->assertEquals('\'\'', $homepage_argument->getValue()); + } + + public function testDefaultValue() { + $default = new DefaultValue("var", ''); + $this->assertEquals('\'\'', $default->toString()); + } } ?> diff --git a/test-phpUnit/config/config.inc.php b/test-phpUnit/config/config.inc.php index 3fe95835d..9bf62db40 100644 --- a/test-phpUnit/config/config.inc.php +++ b/test-phpUnit/config/config.inc.php @@ -4,20 +4,22 @@ define('_TEST_PATH_', _XE_PATH_ . 'test-phpUnit/'); if(!defined('__DEBUG__')) define('__DEBUG__', 4); - + define('__ZBXE__', true); + require_once(_XE_PATH_.'test-phpUnit/Helper.class.php'); require_once(_XE_PATH_.'test-phpUnit/QueryTester.class.php'); require_once(_XE_PATH_.'test-phpUnit/db/DBTest.php'); require_once(_XE_PATH_.'test-phpUnit/db/CubridTest.php'); + require_once(_XE_PATH_.'test-phpUnit/db/CubridOnlineTest.php'); - - require_once(_XE_PATH_.'classes/object/Object.class.php'); - require_once(_XE_PATH_.'classes/handler/Handler.class.php'); - require_once(_XE_PATH_.'classes/context/Context.class.php'); - require_once(_XE_PATH_.'classes/file/FileHandler.class.php'); - require_once(_XE_PATH_.'classes/xml/XmlParser.class.php'); + require_once(_XE_PATH_.'config/config.inc.php'); +// require_once(_XE_PATH_.'classes/object/Object.class.php'); +// require_once(_XE_PATH_.'classes/handler/Handler.class.php'); +// require_once(_XE_PATH_.'classes/context/Context.class.php'); +// require_once(_XE_PATH_.'classes/file/FileHandler.class.php'); +// require_once(_XE_PATH_.'classes/xml/XmlParser.class.php'); require_once(_XE_PATH_.'classes/xml/XmlQueryParser.class.php'); - +// require_once(_XE_PATH_.'classes/db/DB.class.php'); require_once(_XE_PATH_.'classes/db/DBCubrid.class.php'); @@ -26,6 +28,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/ConditionArgument.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/DefaultValue.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/SelectExpression.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/InsertExpression.class.php'); @@ -43,5 +46,4 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - ?> \ No newline at end of file diff --git a/test-phpUnit/db/CubridOnlineTest.php b/test-phpUnit/db/CubridOnlineTest.php new file mode 100644 index 000000000..adb3e5d0c --- /dev/null +++ b/test-phpUnit/db/CubridOnlineTest.php @@ -0,0 +1,38 @@ +db_type = 'cubrid'; + $db_info->db_port = '33000'; + $db_info->db_hostname = '10.0.0.206'; + $db_info->db_userid = 'dba'; + $db_info->db_password = 'arniarules'; + $db_info->db_database = 'xe15QA'; + $db_info->db_table_prefix = 'xe'; + + $oContext->setDbInfo($db_info); + } + + /** + * Free resources - reset static DB and QueryParser + */ + protected function tearDown() { + unset($GLOBALS['__DB__']); + XmlQueryParser::setDBParser(null); + } + } +?> diff --git a/test-phpUnit/db/CubridTest.php b/test-phpUnit/db/CubridTest.php index b88c0a0da..8739f62bd 100644 --- a/test-phpUnit/db/CubridTest.php +++ b/test-phpUnit/db/CubridTest.php @@ -1,12 +1,14 @@ setDbInfo($db_info); } + /** + * Free resources - reset static DB and QueryParser + */ protected function tearDown() { unset($GLOBALS['__DB__']); XmlQueryParser::setDBParser(null); diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php new file mode 100644 index 000000000..bb680b922 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php @@ -0,0 +1,69 @@ +module_category_srl = 0; + $args->browser_title = "test"; + $args->layout_srl = 0; + $args->mlayout_srl = 0; + $args->module = "page"; + $args->mid = "test"; + $args->site_srl = 0; + $args->module_srl = 47374; + $args->content = "hello \' moto"; + + $output = executeQuery('module.insertModule', $args); + + $this->assertTrue(!$output->error); + } + + function test_document_insertDocument_defaultVarcharValue(){ + $args->module_srl = 102; + $args->content = '

yuhuuuuu

'; + $args->document_srl = 9200; + $args->is_secret = 'N'; + $args->allow_comment = 'N'; + $args->lock_comment = 'N'; + $args->allow_trackback = 'N'; + $args->notify_message = 'N'; + $args->ipaddress = '127.0.0.1'; + $args->extra_vars = 'N;'; + $args->readed_count = 0; + $args->list_order = -9201; + $args->update_order = -9201; + $args->member_srl = 4; + $args->user_id = 'admin'; + $args->user_name = 'admin'; + $args->nick_name = 'admin'; + $args->email_address = 'admin@admin.admin'; + $args->homepage = ''; + $args->title = 'yuhuu'; + $args->lang_code; + $output = executeQuery('document.insertDocument', $args); + + $this->assertNotEquals(-225, $args->error); + $this->assertNotEquals('Missing value for attribute "homepage" with the NOT NULL constraint.', $output->message); + + + } + + protected function tearDown() { + + + $db = &DB::getInstance(); + $db->_query("DELETE FROM xe_modules WHERE module_srl = 47374"); + $db->_query("DELETE FROM xe_documents WHERE document_srl = 9200"); + $db->close(); + + parent::tearDown(); + // TODO Delete inserted value + } + + } \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php index aca4445f3..531260aa3 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php @@ -50,14 +50,15 @@ , \'n\')'; $this->_test($xml_file, $argsString, $expected); } - function test_module_insertSiteTodayStatus(){ + + function test_module_insertSiteTodayStatus(){ //\''.date("YmdHis").'\' $xml_file = _XE_PATH_ . "modules/counter/queries/insertTodayStatus.xml"; $argsString = ' $args->regdate = 0; $args->unique_visitor = 0; $args->pageview = 0;'; $expected = 'insert into "xe_counter_status" - ("regdate" + ("regdate" , "unique_visitor" , "pageview") values @@ -94,7 +95,6 @@ $args->allow_mailing = "Y"; $args->allow_message = "Y"; $args->denied = "N"; - $args->limit_date = ""; $args->regdate = "20110607121952"; $args->change_password_date = "20110607121952"; $args->last_login = "20110607121952"; @@ -104,10 +104,10 @@ '; $expected = 'INSERT INTO "xe_member" ("member_srl", "user_id", "email_address", "password", "email_id", "email_host", "user_name", "nick_name", - "homepage", "allow_mailing", "allow_message", "denied", "limit_date", "regdate", "change_password_date", + "homepage", "allow_mailing", "allow_message", "denied", "regdate", "change_password_date", "last_login", "is_admin", "extra_vars", "list_order") VALUES (203, \'cacao\', \'teta@ar.ro\', \'23e5484cb88f3c07bcce2920a5e6a2a7\', \'teta\', \'ar.ro\', \'trident\', - \'aloha\', \'http://jkgjfk./ww\', \'Y\', \'Y\', \'N\', \'\', \'20110607121952\', \'20110607121952\', + \'aloha\', \'http://jkgjfk./ww\', \'Y\', \'Y\', \'N\', \'20110607121952\', \'20110607121952\', \'20110607121952\', \'N\', \'O:8:"stdClass":2:{s:4:"body";s:0:"";s:7:"_filter";s:6:"insert";}\', -203)'; $this->_test($xml_file, $argsString, $expected); } @@ -123,6 +123,6 @@ VALUES (202, \'_filter\', \'insert_page\') '; $this->_test($xml_file, $argsString, $expected); - } + } } \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php new file mode 100644 index 000000000..2d5643ff7 --- /dev/null +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php @@ -0,0 +1,22 @@ +mid = 'test_4l8ci4vv0n'; + $args->site_srl = 0; + $output = executeQuery('module.getMidInfo', $args); + $this->assertNotNull($output); + $this->assertNotNull($output->data); + $this->assertEquals($output->data->module_srl, 111); + } + + function test_module_getInfo(){ + $args->site_srl = 0; + $output = executeQuery('module.getSiteInfo', $args); + $this->assertTrue(is_a($output, 'Object')); + $this->assertEquals(0, $output->error); + var_dump($output); + } + } +?> From bf1d72e478f21aaa4a15bb344b321fb7cb764842 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 18 Jul 2011 12:25:27 +0000 Subject: [PATCH 64/82] Update to array condition arguments. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8602 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../argument/ConditionArgument.class.php | 34 ++++++------------- .../db/queryparts/condition/ConditionTest.php | 13 +++++++ .../db/xml_query/cubrid/CubridSelectTest.php | 2 +- 3 files changed, 24 insertions(+), 25 deletions(-) diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index 421bf85a2..b5d3a280b 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -22,34 +22,20 @@ $value = $this->value; switch($operation) { - case 'like_prefix' : - $this->value = $value.'%'; - break; - case 'like_tail' : - $this->value = '%'.$value; - break; - case 'like' : - $this->value = '%'.$value.'%'; - break; - case 'in' : - if(is_array($value)) - { - //$value = $this->addQuotesArray($value); - if($this->getType() == 'number') - $this->value = "(" . join(',',$value) . ")"; - else - $this->value = "('". join("','",$value)."')"; - } - else - { - $this->value = $value; - } - break; + case 'like_prefix' : + $this->value = $value.'%'; + break; + case 'like_tail' : + $this->value = '%'.$value; + break; + case 'like' : + $this->value = '%'.$value.'%'; + break; } /* //if(!in_array($operation,array('in','notin','between')) && is_array($value)){ // $value = join(',', $value); - //} + //} // Daca operatia nu este in, notin, between si coloana e de tip numeric // daca valoarea e array -> concatenare // daca valoarea nu e array si nici nu contine paranteze (nu e functie) -> return (int) diff --git a/test-phpUnit/classes/db/queryparts/condition/ConditionTest.php b/test-phpUnit/classes/db/queryparts/condition/ConditionTest.php index 20452df0b..5b0d54d1a 100644 --- a/test-phpUnit/classes/db/queryparts/condition/ConditionTest.php +++ b/test-phpUnit/classes/db/queryparts/condition/ConditionTest.php @@ -38,6 +38,19 @@ class ConditionTest extends CubridTest { $this->assertEquals('', $tag->toString()); } + + /** + * Checks "in" operation + */ + public function testConditionString_In_VarcharArray() { + $member_srl_argument = new ConditionArgument('"member_srl"', array('a', 'b', 'c'), 'in'); + $member_srl_argument->createConditionValue(); + $member_srl_argument->setColumnType('varchar'); + + $tag = new Condition('"member_srl"', $member_srl_argument, 'in'); + + $this->assertEquals(' "member_srl" in (\'a\',\'b\',\'c\')', $tag->toString()); + } } ?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index dddef4ffa..992316a00 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -142,7 +142,7 @@ function test_syndication_getGrantedModules(){ $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml"; $argsString = '$args->module_srl = 12; - $args->name = array(\'access\',\'view\',\'list\');'; + $args->name = array(\'access\',\'view\',\'list\');'; $expected = 'select "module_srl" from "xe_module_grants" as "module_grants" where "name" in (\'access\',\'view\',\'list\') From 19c0ba4964b1f053d1b8b82802b1d44be5dc04d6 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 18 Jul 2011 12:36:39 +0000 Subject: [PATCH 65/82] Fixed failing test for ConditionArgument class. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8603 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/condition/Condition.class.php | 4 ++-- classes/xml/xmlquery/argument/Argument.class.php | 2 +- test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php | 1 + .../xml/xmlquery/queryargument/QueryArgumentTest.php | 6 +++--- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index addab276c..b81802f67 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -104,10 +104,10 @@ return $name.' like '.$value; break; case 'in' : - return $name.' in ('.$value.')'; + return $name.' in '.$value; break; case 'notin' : - return $name.' not in ('.$value.')'; + return $name.' not in '.$value; break; case 'notequal' : return $name.' <> '.$value; diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 4111508b3..db37822ee 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -38,7 +38,7 @@ } function toString($value){ - if(is_array($value)) return implode(',', $value); + if(is_array($value)) return '('.implode(',', $value).')'; return $value; } diff --git a/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php index 0a8180777..84293883e 100644 --- a/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php +++ b/test-phpUnit/classes/xml/xmlquery/argument/ArgumentTest.php @@ -213,6 +213,7 @@ class ArgumentTest extends CubridTest { public function testCreateConditionValue_In_StringValues() { $member_srl_argument = new ConditionArgument('"mid"', array('forum', 'board'), 'in'); $member_srl_argument->createConditionValue(); + $member_srl_argument->setColumnType('varchar'); $this->assertEquals('(\'forum\',\'board\')', $member_srl_argument->getValue()); } diff --git a/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php index ec40ce9d9..d8911682f 100644 --- a/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php +++ b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php @@ -20,11 +20,11 @@ class QueryArgumentTest extends CubridTest { $this->assertEquals("member_srl", $tag->getColumnName()); $this->assertEquals(true, $tag->isConditionArgument()); - $actual = $tag->toString(); - $expected = ' $member_srl_argument = new ConditionArgument(\'member_srl\', $args->member_srl, \'equal\'); + $actual = Helper::cleanString($tag->toString()); + $expected = Helper::cleanString('$member_srl_argument = new ConditionArgument(\'member_srl\', $args->member_srl, \'equal\'); $member_srl_argument->checkNotNull(); $member_srl_argument->createConditionValue(); - if(!$member_srl_argument->isValid()) return $member_srl_argument->getErrorMessage();'; + if(!$member_srl_argument->isValid()) return $member_srl_argument->getErrorMessage();'); $this->assertEquals($expected, $actual); } From 5dc0b9c36ca49a9f6031f6f313377225c08fd8b6 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 18 Jul 2011 14:31:10 +0000 Subject: [PATCH 66/82] Fixed output bug - XML requests were not rendered properly because a newline was added at the beginning of the reponse. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8604 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php index 64c4048a2..e23c48aed 100644 --- a/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php +++ b/classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php @@ -57,4 +57,4 @@ return $arguments; } } -?> +?> \ No newline at end of file From ff679cc517be09515358985dae18ea64c86c5eec Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 18 Jul 2011 15:17:49 +0000 Subject: [PATCH 67/82] Fixed query argument bug - for in operation, if there was only one element, the brackets weren't added. Added unit test for this. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8605 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../xml/xmlquery/argument/ConditionArgument.class.php | 3 +++ .../xml/xmlquery/argument/ConditionArgumentTest.php | 11 +++++++++++ .../xml/xmlquery/queryargument/QueryArgumentTest.php | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index b5d3a280b..2e2267793 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -31,6 +31,9 @@ case 'like' : $this->value = '%'.$value.'%'; break; + case 'in': + if(!is_array($value)) $this->value = array($value); + break; } /* //if(!in_array($operation,array('in','notin','between')) && is_array($value)){ diff --git a/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php index d2f386b0b..116cf232a 100644 --- a/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php +++ b/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php @@ -5,6 +5,17 @@ */ class ConditionArgumentTest extends CubridTest { + function testIn(){ + $args->document_srl = 1234; + $document_srl_argument = new ConditionArgument('document_srl', $args->document_srl, 'in'); + $document_srl_argument->checkNotNull(); + $document_srl_argument->createConditionValue(); + if(!$document_srl_argument->isValid()) return $document_srl_argument->getErrorMessage(); + $document_srl_argument->setColumnType('number'); + + $condition = new Condition('"extra_vars"."document_srl"',$document_srl_argument,"in", 'and'); + $this->assertEquals('and "extra_vars"."document_srl" in (1234)', $condition->toString()); + } /** * @todo Implement testCreateConditionValue(). */ diff --git a/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php index d8911682f..b13e953db 100644 --- a/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php +++ b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php @@ -7,7 +7,7 @@ class QueryArgumentTest extends CubridTest { var $xmlPath = "data/"; - function QueryArgumentClass(){ + function QueryArgumentTest(){ $this->xmlPath = str_replace('QueryArgumentTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; } From 0c63c32b1050ecf13fb6c91c59c7e9fc5fa3e186 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 18 Jul 2011 15:58:46 +0000 Subject: [PATCH 68/82] Fixed condition group bug - if there are more condition groups and the first doesn't get displayed, the pipe of the next is printed even though it shouldn't have been. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8607 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/Query.class.php | 9 ++++++++- .../condition/ConditionGroup.class.php | 4 ++++ .../cubrid/CubridSelectOnlineTest.php | 13 ++++++++++++- .../db/xml_query/cubrid/CubridSelectTest.php | 18 ++++++++++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 0e21f8e81..842b27716 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -190,8 +190,15 @@ function getWhereString($with_values = true){ $where = ''; if(count($this->conditions) > 0){ + $condition_count = 0; foreach($this->conditions as $conditionGroup){ - $where .= $conditionGroup->toString($with_values); + $condition_string = $conditionGroup->toString($with_values); + if($condition_string !== '') $condition_count++; + if($condition_count === 1){ + $conditionGroup->setPipe(""); + $condition_string = $conditionGroup->toString($with_values); + } + $where .= $condition_string; } if(trim($where) == '') return ''; diff --git a/classes/db/queryparts/condition/ConditionGroup.class.php b/classes/db/queryparts/condition/ConditionGroup.class.php index e044254f1..f801ac63c 100644 --- a/classes/db/queryparts/condition/ConditionGroup.class.php +++ b/classes/db/queryparts/condition/ConditionGroup.class.php @@ -9,6 +9,10 @@ $this->pipe = $pipe; } + function setPipe($pipe){ + $this->pipe = $pipe; + } + function toString($with_value = true){ if($this->pipe !== "") $group = $this->pipe .' ('; diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php index 2d5643ff7..a9df8ed26 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php @@ -16,7 +16,18 @@ $output = executeQuery('module.getSiteInfo', $args); $this->assertTrue(is_a($output, 'Object')); $this->assertEquals(0, $output->error); - var_dump($output); + } + + function test_document_getDocumentList_pagination(){ + $args->sort_index = 'list_order'; + $args->order_type = 'asc'; + $args->page = 1; + $args->list_count = 30; + $args->page_count = 10; + $args->s_member_srl = 4; + + $output = executeQuery('document.getDocumentList', $args); + $this->assertEquals(0, $output->error, $output->message); } } ?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index 992316a00..939e7e6c9 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -176,5 +176,23 @@ $this->assertTrue(is_int($output->page)); // $this->assertTrue($output->page == 5); } + + function test_document_getDocumentList(){ + $xml_file = _XE_PATH_ . "modules/document/queries/getDocumentList.xml"; + $argsString = '$args->sort_index = \'list_order\'; + $args->order_type = \'asc\'; + $args->page = 1; + $args->list_count = 30; + $args->page_count = 10; + $args->s_member_srl = 4;'; + $expected = 'select * + from "xe_documents" as "documents" + where "member_srl" = 4 + order by "list_order" asc + limit 0, 30'; + $this->_test($xml_file, $argsString, $expected); + + + } } \ No newline at end of file From 98a85cdaa9bb156f4cea2c092867051c05309b84 Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 19 Jul 2011 11:54:58 +0000 Subject: [PATCH 69/82] Fixed insert bug - nextSequnce was not properly retrieved. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8608 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../queryargument/DefaultValue.class.php | 37 ++++++++++++------- .../QueryArgumentValidator.class.php | 2 + test-phpUnit/db/CubridOnlineTest.php | 10 ++++- .../cubrid/CubridInsertOnlineTest.php | 17 +++++++-- .../db/xml_query/cubrid/CubridInsertTest.php | 2 +- 5 files changed, 49 insertions(+), 19 deletions(-) diff --git a/classes/xml/xmlquery/queryargument/DefaultValue.class.php b/classes/xml/xmlquery/queryargument/DefaultValue.class.php index 8ebed633a..73846b218 100644 --- a/classes/xml/xmlquery/queryargument/DefaultValue.class.php +++ b/classes/xml/xmlquery/queryargument/DefaultValue.class.php @@ -3,19 +3,25 @@ class DefaultValue { var $column_name; var $value; - + var $is_sequence = false; + function DefaultValue($column_name, $value){ $this->column_name = $column_name; $this->value = $value; + $this->value = $this->_setValue(); } function isString(){ $str_pos = strpos($this->value, '('); - if($str_pos===false) return true; - return false; + if($str_pos===false) return true; + return false; } - function toString(){ + function isSequence(){ + return $this->is_sequence; + } + + function _setValue(){ if(!isset($this->value)) return; // If value contains comma separated values and does not contain paranthesis @@ -24,13 +30,13 @@ return sprintf('array(%s)', $this->value); } - $str_pos = strpos($this->value, '('); - // // TODO Replace this with parseExpression - if($str_pos===false) return '\''.$this->value.'\''; - //if($str_pos===false) return $this->value; - - $func_name = substr($this->value, 0, $str_pos); - $args = substr($this->value, $str_pos+1, strlen($value)-1); + $str_pos = strpos($this->value, '('); + // // TODO Replace this with parseExpression + if($str_pos===false) return '\''.$this->value.'\''; + //if($str_pos===false) return $this->value; + + $func_name = substr($this->value, 0, $str_pos); + $args = substr($this->value, $str_pos+1, strlen($value)-1); switch($func_name) { case 'ipaddress' : @@ -43,7 +49,8 @@ $val = 'date("YmdHis")'; break; case 'sequence' : - $val = '$this->getNextSequence()'; + $this->is_sequence = true; + $val = '$sequence'; break; case 'plus' : $args = abs($args); @@ -63,7 +70,11 @@ //$val = $this->value; } - return $val; + return $val; + } + + function toString(){ + return $this->value; } } diff --git a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php index 7d930a6e4..e89820081 100644 --- a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php +++ b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php @@ -28,6 +28,8 @@ $validator = ''; if(isset($this->default_value)){ $this->default_value = new DefaultValue($this->argument_name, $this->default_value); + if($this->default_value->isSequence()) + $validator .= '$db = &DB::getInstance(); $sequence = $db->getNextSequence(); '; $validator .= sprintf("$%s_argument->ensureDefaultValue(%s);\n" , $this->argument_name , $this->default_value->toString() diff --git a/test-phpUnit/db/CubridOnlineTest.php b/test-phpUnit/db/CubridOnlineTest.php index adb3e5d0c..d104c0d76 100644 --- a/test-phpUnit/db/CubridOnlineTest.php +++ b/test-phpUnit/db/CubridOnlineTest.php @@ -24,7 +24,15 @@ $db_info->db_database = 'xe15QA'; $db_info->db_table_prefix = 'xe'; - $oContext->setDbInfo($db_info); + $oContext->setDbInfo($db_info); + + // remove cache dir + $tmp_cache_list = FileHandler::readDir('./files','/(^cache_[0-9]+)/'); + if($tmp_cache_list){ + foreach($tmp_cache_list as $tmp_dir){ + if($tmp_dir) FileHandler::removeDir('./files/'.$tmp_dir); + } + } } /** diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php index bb680b922..1515984fb 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php @@ -48,22 +48,31 @@ $args->lang_code; $output = executeQuery('document.insertDocument', $args); - $this->assertNotEquals(-225, $args->error); + $this->assertNotEquals(-225, $output->error); $this->assertNotEquals('Missing value for attribute "homepage" with the NOT NULL constraint.', $output->message); } - protected function tearDown() { - - + function test_communication_addFriendGroup(){ + $args->member_srl = 202; + $args->title = "Grup"; + + $output = executeQuery("communication.addFriendGroup", $args); + $this->assertEquals(0, $output->error, $output->message); + + } + + protected function tearDown() { $db = &DB::getInstance(); $db->_query("DELETE FROM xe_modules WHERE module_srl = 47374"); $db->_query("DELETE FROM xe_documents WHERE document_srl = 9200"); + $db->_query("DELETE FROM xe_member_friend_group WHERE member_srl = 202"); $db->close(); parent::tearDown(); // TODO Delete inserted value } + } \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php index 531260aa3..b52a6f4d4 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php @@ -123,6 +123,6 @@ VALUES (202, \'_filter\', \'insert_page\') '; $this->_test($xml_file, $argsString, $expected); - } + } } \ No newline at end of file From 8b9468a165333e765f00155fabd189fbae4c8e56 Mon Sep 17 00:00:00 2001 From: ucorina Date: Wed, 20 Jul 2011 09:54:07 +0000 Subject: [PATCH 70/82] Update to default value - set it both when value is null or empty string. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8613 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/xml/xmlquery/argument/Argument.class.php | 2 +- .../db/xml_query/cubrid/CubridInsertOnlineTest.php | 10 ++++++++++ test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php | 2 +- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index db37822ee..7a528f50c 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -77,7 +77,7 @@ } function ensureDefaultValue($default_value){ - if(!isset($this->value)) + if(!isset($this->value) || $this->value == '') $this->value = $default_value; } diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php index 1515984fb..d96446205 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php @@ -63,6 +63,16 @@ } + function test_communication_addFriendGroup_NullId(){ + $args->member_srl = 202; + $args->title = "Grup"; + $args->friend_group_srl = trim(null); + + $output = executeQuery("communication.addFriendGroup", $args); + $this->assertEquals(0, $output->error, $output->message); + + } + protected function tearDown() { $db = &DB::getInstance(); $db->_query("DELETE FROM xe_modules WHERE module_srl = 47374"); diff --git a/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php index c3b4accf6..e731f0a45 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php @@ -27,7 +27,7 @@ , "open_rss" = \'Y\' , "header_text" = \'\' , "footer_text" = \'\' - , "use_mobile" = \'\' + , "use_mobile" = \'n\' WHERE "site_srl" = 0 AND "module_srl" = 47374'; $this->_test($xml_file, $argsString, $expected); From e7fe19db1f67eeb08423139bfe4eb2b42a0d3548 Mon Sep 17 00:00:00 2001 From: ucorina Date: Wed, 20 Jul 2011 12:34:31 +0000 Subject: [PATCH 71/82] Added support for selecting a subset of the columns specified in the XML query file. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8614 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/queryparts/Query.class.php | 35 ++++++++++---- test-phpUnit/db/DBTest.php | 3 +- .../cubrid/CubridInsertOnlineTest.php | 2 +- .../cubrid/CubridSelectOnlineTest.php | 23 +++++++-- .../db/xml_query/cubrid/CubridSelectTest.php | 47 +++++++++---------- 5 files changed, 71 insertions(+), 39 deletions(-) diff --git a/classes/db/queryparts/Query.class.php b/classes/db/queryparts/Query.class.php index 842b27716..4943a39a0 100644 --- a/classes/db/queryparts/Query.class.php +++ b/classes/db/queryparts/Query.class.php @@ -13,6 +13,8 @@ var $arguments = null; + var $columnList = null; + function Query($queryID = null , $action = null , $columns = null @@ -24,12 +26,13 @@ $this->queryID = $queryID; $this->action = $action; - $this->columns = $columns; - $this->tables = $tables; - $this->conditions = $conditions; - $this->groups = $groups; - $this->orderby = $orderby; - $this->limit = $limit; + if(!isset($tables)) return; + $this->columns = $this->setColumns($columns); + $this->tables = $this->setTables($tables); + $this->conditions = $this->setConditions($conditions); + $this->groups = $this->setGroups($groups); + $this->orderby = $this->setOrder($orderby); + $this->limit = $this->setLimit($limit); } function show(){ @@ -44,6 +47,10 @@ $this->action = $action; } + function setColumnList($columnList){ + $this->columnList = $columnList; + } + function setColumns($columns){ if(!isset($columns) || count($columns) === 0){ $this->columns = array(new StarExpression()); @@ -130,9 +137,21 @@ return $this->action; } - function getSelectString($with_values = true){ + function getSelectString($with_values = true){ + if(isset($this->columnList)){ + $selectColumns = array(); + $dbParser = XmlQueryParser::getDBParser(); + + foreach($this->columnList as $columnName){ + $columnName = $dbParser->escapeColumn($columnName); + $selectColumns[] = new SelectExpression($columnName); + } + } + else + $selectColumns = $this->columns; + $select = ''; - foreach($this->columns as $column){ + foreach($selectColumns as $column){ if($column->show()) if(is_a($column, 'Subquery')){ $select .= $column->toString($with_values) . ' as '. $column->getAlias() .', '; diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php index c4d43a02f..c3e5d2d5a 100644 --- a/test-phpUnit/db/DBTest.php +++ b/test-phpUnit/db/DBTest.php @@ -1,7 +1,7 @@ toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { $db = &DB::getInstance(); + if($columnList) $output->setColumnList($columnList); $querySql = $db->{$methodName}($output); // Remove whitespaces, tabs and all diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php index d96446205..e1568307a 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php @@ -21,7 +21,7 @@ $output = executeQuery('module.insertModule', $args); - $this->assertTrue(!$output->error); + $this->assertTrue(!$output->error, $output->message); } function test_document_insertDocument_defaultVarcharValue(){ diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php index a9df8ed26..3965b2488 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php @@ -7,7 +7,7 @@ $args->site_srl = 0; $output = executeQuery('module.getMidInfo', $args); $this->assertNotNull($output); - $this->assertNotNull($output->data); + $this->assertNotNull($output->data, $output->message); $this->assertEquals($output->data->module_srl, 111); } @@ -15,7 +15,7 @@ $args->site_srl = 0; $output = executeQuery('module.getSiteInfo', $args); $this->assertTrue(is_a($output, 'Object')); - $this->assertEquals(0, $output->error); + $this->assertEquals(0, $output->error, $output->message); } function test_document_getDocumentList_pagination(){ @@ -29,5 +29,22 @@ $output = executeQuery('document.getDocumentList', $args); $this->assertEquals(0, $output->error, $output->message); } - } + + function test_syndication_getDocumentList(){ + $args->module_srl = NULL; + $args->exclude_module_srl = NULL; + $args->category_srl = NULL; + $args->sort_index = 'list_order'; + $args->order_type = 'asc'; + $args->page = 5; + $args->list_count = 30; + $args->page_count = 10; + $args->start_date = NULL; + $args->end_date = NULL; + $args->member_srl = NULL; + $output = executeQuery('document.getDocumentList', $args); + + $this->assertTrue(is_int($output->page), $output->message); + } + } ?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index 939e7e6c9..1ffeff5a9 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -3,8 +3,8 @@ class CubridSelectTest extends CubridTest { - function _test($xml_file, $argsString, $expected){ - $this->_testQuery($xml_file, $argsString, $expected, 'getSelectSql'); + function _test($xml_file, $argsString, $expected, $columnList = null){ + $this->_testQuery($xml_file, $argsString, $expected, 'getSelectSql', $columnList); } function testSelectStar(){ @@ -151,30 +151,6 @@ or "group_srl" = -2) group by "module_srl"'; $this->_test($xml_file, $argsString, $expected); - } - - function test_syndication_getDocumentList(){ - define('__ZBXE__', 1); - - require_once(_XE_PATH_.'classes/page/PageHandler.class.php'); - - $db = &DB::getInstance('cubrid'); - $args = new StdClass(); - $args->module_srl = NULL; - $args->exclude_module_srl = NULL; - $args->category_srl = NULL; - $args->sort_index = 'list_order'; - $args->order_type = 'asc'; - $args->page = 5; - $args->list_count = 30; - $args->page_count = 10; - $args->start_date = NULL; - $args->end_date = NULL; - $args->member_srl = NULL; - $output = $db->executeQuery('document.getDocumentList', $args); - - $this->assertTrue(is_int($output->page)); - // $this->assertTrue($output->page == 5); } function test_document_getDocumentList(){ @@ -194,5 +170,24 @@ } + + /** + * Test column list + */ + function test_session_getSession(){ + $xml_file = _XE_PATH_ . "modules/session/queries/getSession.xml"; + $argsString = '$args->session_key = \'session_key\';'; + $columnList = array('session_key', 'cur_mid', 'val'); + + $expected = 'select "session_key", "cur_mid", "val" + from "xe_session" as "session" + where "session_key" = \'session_key\''; + + $this->_test($xml_file, $argsString, $expected, $columnList); + + //$columnList = array('session_key', 'cur_mid', 'val'); + //$output = executeQuery('session.getSession', $args, $columnList); + + } } \ No newline at end of file From 8f04aa5d63491cbc41e85713ebadc87d9cc443c5 Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 21 Jul 2011 13:25:30 +0000 Subject: [PATCH 72/82] Update to condition tag - column name should also be accepted in the "var" attribute and not just "default" attribute. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8617 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../tags/condition/ConditionTag.class.php | 8 ++++++-- .../tags/condition/ConditionTagTest.php | 19 ++++++++++++++++++- .../tags/condition/data/condition4.xml | 1 + .../db/xml_query/cubrid/CubridSelectTest.php | 17 +++++++++++++---- 4 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition4.xml diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index 817603656..00c83d300 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -24,19 +24,23 @@ $this->column_name = $dbParser->parseColumnName($condition->attrs->column); $isColumnName = strpos($condition->attrs->default, '.'); - + $isColumnName = $isColumnName || strpos($condition->attrs->var, '.'); + if($condition->node_name == 'query'){ $this->query = new QueryTag($condition, true); $this->default_column = $this->query->toString(); } - else if($condition->attrs->var || $isColumnName === false){ + else if(($condition->attrs->var && !$isColumnName) || $isColumnName === false){ require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); $this->argument = new QueryArgument($condition); $this->argument_name = $this->argument->getArgumentName(); } else { + if($condition->attrs->default) $this->default_column = "'" . $dbParser->parseColumnName($condition->attrs->default) . "'" ; + else + $this->default_column = "'" . $dbParser->parseColumnName($condition->attrs->var) . "'" ; } } diff --git a/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php b/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php index 6ac7e6036..245dbc37f 100644 --- a/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php +++ b/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php @@ -61,7 +61,24 @@ class ConditionTagTest extends CubridTest { $arguments = $tag->getArguments(); $this->assertEquals(1, count($arguments)); - } + } + + /** + * Tests that even if the column name is given in the var attribute, it knows it's just a name and not an argument + * + */ + function testConditionStringWithoutArgumentAndDefaultValueInsideVar(){ + $xml_file = $this->xmlPath . "condition4.xml"; + $xml_obj = Helper::getXmlObject($xml_file); + $tag = new ConditionTag($xml_obj->condition); + + $expected = "new Condition('\"modules\".\"module_srl\"','\"documents\".\"module_srl\"',\"equal\", 'and')"; + $actual = $tag->getConditionString(); + $this->assertEquals($expected, $actual); + + $arguments = $tag->getArguments(); + $this->assertEquals(0, count($arguments)); + } } diff --git a/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition4.xml b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition4.xml new file mode 100644 index 000000000..ac432b118 --- /dev/null +++ b/test-phpUnit/classes/xml/xmlquery/tags/condition/data/condition4.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index 1ffeff5a9..daf89436d 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -184,10 +184,19 @@ where "session_key" = \'session_key\''; $this->_test($xml_file, $argsString, $expected, $columnList); - - //$columnList = array('session_key', 'cur_mid', 'val'); - //$output = executeQuery('session.getSession', $args, $columnList); - } + + function test_module_getModuleInfoByDocument(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getModuleInfoByDocument.xml"; + $argsString = '$args->document_srl = 10;'; + $expected = 'SELECT "modules".* + FROM "xe_modules" as "modules" + , "xe_documents" as "documents" + WHERE "documents"."document_srl" = 10 + and "modules"."module_srl" = "documents"."module_srl"'; + $this->_test($xml_file, $argsString, $expected); + + + } } \ No newline at end of file From 7de48344cc1240a05258306be9cf22f90269fb6e Mon Sep 17 00:00:00 2001 From: ucorina Date: Fri, 22 Jul 2011 11:50:08 +0000 Subject: [PATCH 73/82] Fixed select bug - unless default value is explicitly set as empty string, ignore arguments whose value is empty string. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8624 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../queryparts/condition/Condition.class.php | 1 + .../xml/xmlquery/argument/Argument.class.php | 2 +- .../queryargument/QueryArgument.class.php | 18 ++++-------------- .../argument/ConditionArgumentTest.php | 13 +++++++++++++ .../cubrid/CubridInsertOnlineTest.php | 2 -- .../cubrid/CubridSelectOnlineTest.php | 14 +++++++++++++- .../db/xml_query/cubrid/CubridSelectTest.php | 18 +++++++++++++++--- 7 files changed, 47 insertions(+), 21 deletions(-) diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index b81802f67..35ccfc453 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -53,6 +53,7 @@ function show(){ if($this->hasArgument() && !$this->argument->isValid()) return false; + if($this->hasArgument() && ($this->_value === '\'\'')) return false; switch($this->operation) { case 'equal' : case 'more' : diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 7a528f50c..b9c869946 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -7,7 +7,7 @@ var $isValid; var $errorMessage; - + function Argument($name, $value){ $this->value = $value; $this->name = $name; diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index 3257ce17f..92f9bdfd5 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -5,17 +5,9 @@ var $argument_validator; var $column_name; var $operation; - var $ignoreValue; function QueryArgument($tag){ - // HACK (this is for backwords compatibility - there are many xml files that have variable names (var) given with .) - // eg. var = point.memeber_srl (getMemberList query from point module) - $this->argument_name = str_replace('.', '_',$tag->attrs->var); - if(!$this->argument_name) $this->ignoreValue = true; - else $this->ignoreValue = false; - - - + $this->argument_name = $tag->attrs->var; if(!$this->argument_name) $this->argument_name = $tag->attrs->name; if(!$this->argument_name) $this->argument_name = str_replace('.', '_',$tag->attrs->column); @@ -28,10 +20,7 @@ } if($tag->attrs->operation) $this->operation = $tag->attrs->operation; - - // If we work with ConditionArgument, check if default value exists, and if yes, create argument - if($this->operation && $tag->attrs->default) $this->ignoreValue = false; - + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); $this->argument_validator = new QueryArgumentValidator($tag, $this); @@ -59,7 +48,7 @@ $arg = sprintf("\n$%s_argument = new ConditionArgument('%s', %s, '%s');\n" , $this->argument_name , $this->argument_name - , $this->ignoreValue ? 'null' : '$args->'.$this->argument_name + , '$args->'.$this->argument_name , $this->operation ); @@ -67,6 +56,7 @@ $arg = sprintf("\n$%s_argument = new Argument('%s', %s);\n" , $this->argument_name , $this->argument_name + , '$args->'.$this->argument_name , $this->ignoreValue ? 'null' : '$args->'.$this->argument_name); diff --git a/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php index 116cf232a..633e00cfb 100644 --- a/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php +++ b/test-phpUnit/classes/xml/xmlquery/argument/ConditionArgumentTest.php @@ -16,6 +16,19 @@ class ConditionArgumentTest extends CubridTest { $condition = new Condition('"extra_vars"."document_srl"',$document_srl_argument,"in", 'and'); $this->assertEquals('and "extra_vars"."document_srl" in (1234)', $condition->toString()); } + + function testZeroValue(){ + $args->site_srl = 0; + $site_srl_argument = new ConditionArgument('site_srl', $args->site_srl, 'equal'); + $site_srl_argument->checkNotNull(); + $site_srl_argument->createConditionValue(); + if(!$site_srl_argument->isValid()) return $site_srl_argument->getErrorMessage(); + $site_srl_argument->setColumnType('number'); + + $condition = new Condition('"sites"."site_srl"',$site_srl_argument,"equal"); + $this->assertEquals(' "sites"."site_srl" = 0', $condition->toString()); + } + /** * @todo Implement testCreateConditionValue(). */ diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php index e1568307a..f55bd3720 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertOnlineTest.php @@ -50,8 +50,6 @@ $this->assertNotEquals(-225, $output->error); $this->assertNotEquals('Missing value for attribute "homepage" with the NOT NULL constraint.', $output->message); - - } function test_communication_addFriendGroup(){ diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php index 3965b2488..fcc7eecb6 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php @@ -11,7 +11,7 @@ $this->assertEquals($output->data->module_srl, 111); } - function test_module_getInfo(){ + function test_module_getInfo(){ $args->site_srl = 0; $output = executeQuery('module.getSiteInfo', $args); $this->assertTrue(is_a($output, 'Object')); @@ -46,5 +46,17 @@ $this->assertTrue(is_int($output->page), $output->message); } + + function test_member_getMemberList(){ + $args->is_admin = ''; + $args->is_denied = ''; + $args->sort_index = "list_order"; + $args->sort_order = 'asc'; + $args->list_count = 40; + $args->page_count = 10; + + $output = executeQuery('member.getMemberList', $args); + $this->assertEquals(0, $output->error, $output->message); + } } ?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index daf89436d..edaa484a2 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -194,9 +194,21 @@ , "xe_documents" as "documents" WHERE "documents"."document_srl" = 10 and "modules"."module_srl" = "documents"."module_srl"'; - $this->_test($xml_file, $argsString, $expected); - - + $this->_test($xml_file, $argsString, $expected); } + + function test_member_getMemberList(){ + $xml_file = _XE_PATH_ . "modules/member/queries/getMemberList.xml"; + $argsString = '$args->is_admin = \'\'; + $args->is_denied = \'\'; + $args->sort_index = "list_order"; + $args->sort_order = \'asc\'; + $args->list_count = 40; + $args->page_count = 10;'; + $expected = 'select * from "xe_member" as "member" + order by "list_order" asc + limit 0, 40'; + $this->_test($xml_file, $argsString, $expected); + } } \ No newline at end of file From 6edd5f03a7eb1ceb6eb39406344376c44830bcf3 Mon Sep 17 00:00:00 2001 From: lickawtl Date: Fri, 22 Jul 2011 11:52:02 +0000 Subject: [PATCH 74/82] fix pagination git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8625 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBFirebird.class.php | 145 +++++++++++------ classes/db/DBMysql.class.php | 4 +- classes/db/DBPostgresql.class.php | 4 +- classes/db/DBSqlite3_pdo.class.php | 251 +++++++++++++++-------------- 4 files changed, 231 insertions(+), 173 deletions(-) diff --git a/classes/db/DBFirebird.class.php b/classes/db/DBFirebird.class.php index a73d183fc..62e2effd8 100644 --- a/classes/db/DBFirebird.class.php +++ b/classes/db/DBFirebird.class.php @@ -622,7 +622,7 @@ * @brief Handle the insertAct **/ function _executeInsertAct($queryObject) { - $query = $this->getInsertSql($queryObject); + $query = $this->getInsertSql($queryObject); if(is_a($query, 'Object')) return; return $this->_query($query); } @@ -662,55 +662,102 @@ else return $this->queryPageLimit($queryObject, $result); } - function queryError($queryObject){ - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ - $buff = new Object (); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array (); - $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values - return $buff; - }else - return; - } - - function queryPageLimit($queryObject, $result){ - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { - // Total count - $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); - if ($queryObject->getGroupByString() != '') { - $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); - } - - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result_count = $this->_query($count_query); - $count_output = $this->_fetch($result_count); - $total_count = (int)$count_output->count; - - // Total pages - if ($total_count) { - $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; - } else $total_page = 1; - - $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; - $data = $this->_fetch($result, $virtual_no); - - $buff = new Object (); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $queryObject->getLimit()->page; - $buff->data = $data; - $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); - }else{ - $data = $this->_fetch($result); - $buff = new Object (); - $buff->data = $data; - } - return $buff; - } - + function queryError($queryObject) { + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array(); + $buff->page_navigation = new PageHandler(/* $total_count */0, /* $total_page */1, /* $page */1, /* $page_count */10); //default page handler values + }else + return; } + function queryPageLimit($queryObject, $result) { + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE ' . $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } + + $count_query .= ( __DEBUG_QUERY__ & 1 && $output->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; + $result_count = $this->_query($count_query); + $count_output = $this->_fetch($result_count); + $total_count = (int) $count_output->count; + + // Total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; + } else + $total_page = 1; + + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; + while ($tmp = ibase_fetch_object($result)) + $data[$virtual_no--] = $tmp; + + if (!$this->transaction_started) + @ibase_commit($this->fd); + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $queryObject->getLimit()->page->getValue(); + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page->getValue(), $queryObject->getLimit()->page_count); + }else { + $data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } + return $buff; + } + + function getParser() { + return new DBParser('"'); + } + + function getSelectSql($query, $with_values = true) { + + if ($query->getLimit()) { + $list_count = $query->getLimit()->list_count->getValue(); + if(!$query->getLimit()->page) $page = 1; + else $page = $query->getLimit()->page->getValue(); + + $start_count = ($page - 1) * $list_count; + $limit = sprintf('SELECT FIRST %d SKIP %d ', $list_count, $start_count); + } + + $select = $query->getSelectString($with_values); + if ($select == '') + return new Object(-1, "Invalid query"); + + if ($query->getLimit()) + $select = $limit . ' ' . $select; + else + $select = 'SELECT ' . $select; + $from = $query->getFromString($with_values); + if ($from == '') + return new Object(-1, "Invalid query"); + $from = ' FROM ' . $from; + + $where = $query->getWhereString($with_values); + if ($where != '') + $where = ' WHERE ' . $where; + + $groupBy = $query->getGroupByString(); + if ($groupBy != '') + $groupBy = ' GROUP BY ' . $groupBy; + + $orderBy = $query->getOrderByString(); + if ($orderBy != '') + $orderBy = ' ORDER BY ' . $orderBy; + + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; + } + +} + return new DBFireBird; ?> diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index 507a343de..8a36032d3 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -493,9 +493,9 @@ $buff = new Object (); $buff->total_count = $total_count; $buff->total_page = $total_page; - $buff->page = $queryObject->getLimit()->page; + $buff->page = $queryObject->getLimit()->page->getValue(); $buff->data = $data; - $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page->getValue(), $queryObject->getLimit()->page_count); }else{ $data = $this->_fetch($result); $buff = new Object (); diff --git a/classes/db/DBPostgresql.class.php b/classes/db/DBPostgresql.class.php index 38d54e228..01eefe729 100644 --- a/classes/db/DBPostgresql.class.php +++ b/classes/db/DBPostgresql.class.php @@ -614,9 +614,9 @@ class DBPostgresql extends DB $buff = new Object (); $buff->total_count = $total_count; $buff->total_page = $total_page; - $buff->page = $queryObject->getLimit()->page; + $buff->page = $queryObject->getLimit()->page->getValue(); $buff->data = $data; - $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page->getValue(), $queryObject->getLimit()->page_count); }else{ $data = $this->_fetch($result); $buff = new Object (); diff --git a/classes/db/DBSqlite3_pdo.class.php b/classes/db/DBSqlite3_pdo.class.php index 0e3d31ef6..ac624f377 100644 --- a/classes/db/DBSqlite3_pdo.class.php +++ b/classes/db/DBSqlite3_pdo.class.php @@ -399,130 +399,141 @@ } } - /** - * @brief insertAct - **/ - function _executeInsertAct($queryObject) { - $query = $this->getInsertSql($queryObject); - if(is_a($query, 'Object')) return; - - $this->_prepare($query); + /** + * @brief insertAct + * */ + function _executeInsertAct($queryObject) { + $query = $this->getInsertSql($queryObject); + if (is_a($query, 'Object')) + return; - $val_count = count($val_list); - for($i=0;$i<$val_count;$i++) $this->_bind($val_list[$i]); + $this->_prepare($query); - return $this->_execute(); - } + $val_count = count($val_list); + for ($i = 0; $i < $val_count; $i++) + $this->_bind($val_list[$i]); - /** - * @brief updateAct - **/ - function _executeUpdateAct($queryObject) { - $query = $this->getUpdateSql($queryObject); - if(is_a($query, 'Object')) return; - - $this->_prepare($query); - return $this->_execute(); - } - - /** - * @brief deleteAct - **/ - function _executeDeleteAct($queryObject) { - $query = $this->getDeleteSql($queryObject); - if(is_a($query, 'Object')) return; - - $this->_prepare($query); - return $this->_execute(); - } - - /** - * @brief selectAct - * - * To fetch a list of the page conveniently when selecting, \n - * navigation method supported - **/ - function _executeSelectAct($queryObject) { - $query = $this->getSelectSql($queryObject); - if(is_a($query, 'Object')) return; - - $this->_prepare($query); - $data = $this->_execute(); - if($this->isError()) return; - - if ($this->isError ()) return $this->queryError($queryObject); - else return $this->queryPageLimit($queryObject, $data); - } - - function queryError($queryObject){ - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ - $buff = new Object (); - $buff->total_count = 0; - $buff->total_page = 0; - $buff->page = 1; - $buff->data = array (); - $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values - return $buff; - }else - return; - } - - function queryPageLimit($queryObject, $data){ - if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { - // Total count - $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); - if ($queryObject->getGroupByString() != '') { - $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); - } - - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $this->_prepare($count_query); - $count_output = $this->_execute(); - $total_count = (int)$count_output->count; - - // Total pages - if ($total_count) { - $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; - } else $total_page = 1; - - $this->_prepare($this->getSelectSql($queryObject)); - $this->stmt->execute(); - if($this->stmt->errorCode() != '00000') { - $this->setError($this->stmt->errorCode(), print_r($this->stmt->errorInfo(),true)); - $this->actFinish(); - return $buff; - } - - $output = null; - $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; - //$data = $this->_fetch($result, $virtual_no); - while($tmp = $this->stmt->fetch(PDO::FETCH_ASSOC)) { - unset($obj); - foreach($tmp as $key => $val) { - $pos = strpos($key, '.'); - if($pos) $key = substr($key, $pos+1); - $obj->{$key} = $val; - } - $data[$virtual_no--] = $obj; - } - - $this->stmt = null; - $this->actFinish(); - - $buff = new Object (); - $buff->total_count = $total_count; - $buff->total_page = $total_page; - $buff->page = $queryObject->getLimit()->page; - $buff->data = $data; - $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); - }else{ - //$data = $this->_fetch($result); - $buff = new Object (); - $buff->data = $data; - } - return $buff; - } + return $this->_execute(); } + /** + * @brief updateAct + * */ + function _executeUpdateAct($queryObject) { + $query = $this->getUpdateSql($queryObject); + if (is_a($query, 'Object')) + return; + + $this->_prepare($query); + return $this->_execute(); + } + + /** + * @brief deleteAct + * */ + function _executeDeleteAct($queryObject) { + $query = $this->getDeleteSql($queryObject); + if (is_a($query, 'Object')) + return; + + $this->_prepare($query); + return $this->_execute(); + } + + /** + * @brief selectAct + * + * To fetch a list of the page conveniently when selecting, \n + * navigation method supported + * */ + function _executeSelectAct($queryObject) { + $query = $this->getSelectSql($queryObject); + if (is_a($query, 'Object')) + return; + + $this->_prepare($query); + $data = $this->_execute(); + if ($this->isError()) + return; + + if ($this->isError()) + return $this->queryError($queryObject); + else + return $this->queryPageLimit($queryObject, $data); + } + + function queryError($queryObject) { + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + $buff = new Object (); + $buff->total_count = 0; + $buff->total_page = 0; + $buff->page = 1; + $buff->data = array(); + $buff->page_navigation = new PageHandler(/* $total_count */0, /* $total_page */1, /* $page */1, /* $page_count */10); //default page handler values + return $buff; + }else + return; + } + + function queryPageLimit($queryObject, $data) { + if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { + // Total count + $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE ' . $queryObject->getWhereString())); + if ($queryObject->getGroupByString() != '') { + $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); + } + + $count_query .= ( __DEBUG_QUERY__ & 1 && $output->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; + $this->_prepare($count_query); + $count_output = $this->_execute(); + $total_count = (int) $count_output->count; + + // Total pages + if ($total_count) { + $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; + } else + $total_page = 1; + + $this->_prepare($this->getSelectSql($queryObject)); + $this->stmt->execute(); + if ($this->stmt->errorCode() != '00000') { + $this->setError($this->stmt->errorCode(), print_r($this->stmt->errorInfo(), true)); + $this->actFinish(); + return $buff; + } + + $output = null; + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; + //$data = $this->_fetch($result, $virtual_no); + while ($tmp = $this->stmt->fetch(PDO::FETCH_ASSOC)) { + unset($obj); + foreach ($tmp as $key => $val) { + $pos = strpos($key, '.'); + if ($pos) + $key = substr($key, $pos + 1); + $obj->{$key} = $val; + } + $data[$virtual_no--] = $obj; + } + + $this->stmt = null; + $this->actFinish(); + + $buff = new Object (); + $buff->total_count = $total_count; + $buff->total_page = $total_page; + $buff->page = $queryObject->getLimit()->page->getValue(); + $buff->data = $data; + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page->getValue(), $queryObject->getLimit()->page_count); + }else { + //$data = $this->_fetch($result); + $buff = new Object (); + $buff->data = $data; + } + return $buff; + } + +} + return new DBSqlite3_pdo; ?> From b3c75ac4db5cfb4a7e164488625e0e601429ae45 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 25 Jul 2011 15:35:43 +0000 Subject: [PATCH 75/82] Fixed a few MSSQL bugs - related to array query arguments and increment columns. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8632 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 62 ++++----- classes/db/DBMssql.class.php | 120 ++++++++++-------- .../queryparts/condition/Condition.class.php | 46 ++++--- .../expression/UpdateExpression.class.php | 24 ++-- .../xml/xmlquery/argument/Argument.class.php | 76 ++++++----- .../queryargument/DefaultValue.class.php | 52 +++++--- .../QueryArgumentValidator.class.php | 29 +++-- test-phpUnit/config/config.inc.php | 26 ++-- test-phpUnit/db/CubridOnlineTest.php | 19 +-- test-phpUnit/db/DBTest.php | 20 +-- test-phpUnit/db/MssqlOnlineTest.php | 41 ++++++ .../db/xml_query/cubrid/CubridUpdateTest.php | 52 ++++---- .../db/xml_query/mssql/MssqlSelectTest.php | 91 +++++++------ .../xml_query/mssql/MssqlUpdateOnlineTest.php | 12 ++ .../db/xml_query/mssql/MssqlUpdateTest.php | 17 +++ 15 files changed, 411 insertions(+), 276 deletions(-) create mode 100644 test-phpUnit/db/MssqlOnlineTest.php create mode 100644 test-phpUnit/db/xml_query/mssql/MssqlUpdateOnlineTest.php create mode 100644 test-phpUnit/db/xml_query/mssql/MssqlUpdateTest.php diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index ca9333f85..042cc8986 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -320,12 +320,12 @@ require_once(_XE_PATH_.'classes/db/queryparts/limit/Limit.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/Query.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/Subquery.class.php'); - - + + $output = include($cache_file); if( (is_a($output, 'Object') || is_subclass_of($output, 'Object')) && !$output->toBool()) return $output; - + // execute appropriate query switch($output->getAction()) { case 'insert' : @@ -346,7 +346,7 @@ $output = $this->_executeSelectAct($output); break; } - + if($this->isError()) $output = $this->getError(); else if(!is_a($output, 'Object') && !is_subclass_of($output, 'Object')) $output = new Object(); $output->add('_query', $this->query); @@ -458,76 +458,76 @@ $query = sprintf("drop table %s%s", $this->prefix, $table_name); $this->_query($query); } - - function getSelectSql($query, $with_values = true){ + + function getSelectSql($query, $with_values = true){ $select = $query->getSelectString($with_values); if($select == '') return new Object(-1, "Invalid query"); $select = 'SELECT ' .$select; - + $from = $query->getFromString($with_values); if($from == '') return new Object(-1, "Invalid query"); $from = ' FROM '.$from; - + $where = $query->getWhereString($with_values); if($where != '') $where = ' WHERE ' . $where; - + $groupBy = $query->getGroupByString(); if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; - + $orderBy = $query->getOrderByString(); if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; - + $limit = $query->getLimitString(); if($limit != '') $limit = ' LIMIT ' . $limit; return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; - } + } function getDeleteSql($query, $with_values = true){ $sql = 'DELETE '; // TODO Add support for deleting based on alias, for both simple FROM and multi table join FROM clause $tables = $query->getTables(); - + $sql .= $tables[0]->getAlias(); - + $from = $query->getFromString($with_values); if($from == '') return new Object(-1, "Invalid query"); - $sql .= ' FROM '.$from; - + $sql .= ' FROM '.$from; + $where = $query->getWhereString($with_values); - if($where != '') $sql .= ' WHERE ' . $where; - + if($where != '') $sql .= ' WHERE ' . $where; + return $sql; - } + } function getUpdateSql($query, $with_values = true){ - $columnsList = $query->getSelectString(); + $columnsList = $query->getSelectString($with_values); if($columnsList == '') return new Object(-1, "Invalid query"); - + $tableName = $query->getFirstTableName(); if($tableName == '') return new Object(-1, "Invalid query"); - + $where = $query->getWhereString($with_values); if($where != '') $where = ' WHERE ' . $where; - + return "UPDATE $tableName SET $columnsList ".$where; - } - + } + function getInsertSql($query, $with_values = true){ $tableName = $query->getFirstTableName(); $values = $query->getInsertString($with_values); - + return "INSERT INTO $tableName \n $values"; - } - + } + // HACK This is needed because on installation, the XmlQueryParer is used without any configured database // TODO Change this or make sure the query cache files created before db.config exists are deleted function getParser(){ return new DBParser('"'); } - + // TO BE REMOVED - Used for query compare /** * @brief returns type of column @@ -560,7 +560,7 @@ if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; return $value; } - + if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { list($table_name, $column_name) = explode('.', $value); if($column_type[$column_name]) return $value; @@ -713,6 +713,6 @@ } return $conditions; - } + } } ?> diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index 7cac092b1..cdf1cf995 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -17,7 +17,7 @@ var $prefix = 'xe'; // / _setDBInfo(); $this->_connect(); } - + /** * @brief create an instance of this class */ @@ -70,7 +70,7 @@ $this->password = $db_info->db_password; $this->database = $db_info->db_database; $this->prefix = $db_info->db_table_prefix; - + if(!substr($this->prefix,-1)!='_') $this->prefix .= '_'; } @@ -85,10 +85,10 @@ //sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); //sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL ); - $this->conn = sqlsrv_connect( $this->hostname, + $this->conn = sqlsrv_connect( $this->hostname, array( 'Database' => $this->database,'UID'=>$this->userid,'PWD'=>$this->password )); - + // Check connections if($this->conn){ $this->is_connected = true; @@ -103,7 +103,7 @@ **/ function close() { if($this->is_connected == false) return; - + $this->commit(); sqlsrv_close($this->conn); $this->conn = null; @@ -116,7 +116,7 @@ function addQuotes($string) { if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); //if(!is_numeric($string)) $string = str_replace("'","''",$string); - + return $string; } @@ -126,7 +126,7 @@ function begin() { if($this->is_connected == false || $this->transaction_started) return; if(sqlsrv_begin_transaction( $this->conn ) === false) return; - + $this->transaction_started = true; } @@ -135,7 +135,7 @@ **/ function rollback() { if($this->is_connected == false || !$this->transaction_started) return; - + $this->transaction_started = false; sqlsrv_rollback( $this->conn ); } @@ -145,8 +145,8 @@ **/ function commit($force = false) { if(!$force && ($this->is_connected == false || !$this->transaction_started)) return; - - $this->transaction_started = false; + + $this->transaction_started = false; sqlsrv_commit( $this->conn ); } @@ -159,25 +159,37 @@ * object if a row returned \n * return\n **/ + + // TODO Support array arguments in sql server + /* + * $query_emp="select name from employee where id in (?,?,?)"; + $params_emp= Array(1,2,3); + $res_emp = sqlsrv_query($conn, $query_emp, $params_emp); + * + */ + function _query($query) { if($this->is_connected == false || !$query) return; $_param = array(); - + if(count($this->param)){ foreach($this->param as $k => $o){ if($o->getType() == 'number'){ - $_param[] = $o->getUnescapedValue(); + $value = $o->getUnescapedValue(); + if(is_array($value)) $_param = array_merge($_param, $value); + else $_param[] = $o->getUnescapedValue(); }else{ + // TODO treat arrays here too $value = $o->getUnescapedValue(); $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); } - } + } } - + // Notify to start a query execution $this->actStart($query); - + // Run the query statement $result = false; if(count($_param)){ @@ -186,9 +198,9 @@ $result = @sqlsrv_query($this->conn, $query); } // Error Check - + if(!$result) $this->setError(print_r(sqlsrv_errors(),true)); - + // Notify to complete a query execution $this->actFinish(); $this->param = array(); @@ -201,16 +213,16 @@ **/ function _fetch($result, $arrayIndexEndValue = NULL) { if(!$this->isConnected() || $this->isError() || !$result) return; - + $c = sqlsrv_num_fields($result); $m = null; $output = array(); - + while(sqlsrv_fetch($result)){ if(!$m) $m = sqlsrv_field_metadata($result); unset($row); for($i=0;$i<$c;$i++){ - $row->{$m[$i]['Name']} = sqlsrv_get_field( $result, $i, SQLSRV_PHPTYPE_STRING( 'utf-8' )); + $row->{$m[$i]['Name']} = sqlsrv_get_field( $result, $i, SQLSRV_PHPTYPE_STRING( 'utf-8' )); } if($arrayIndexEndValue) $output[$arrayIndexEndValue--] = $row; else $output[] = $row; @@ -230,12 +242,12 @@ function getNextSequence() { $query = sprintf("insert into %ssequence (seq) values (ident_incr('%ssequence'))", $this->prefix, $this->prefix); $this->_query($query); - + $query = sprintf("select ident_current('%ssequence')+1 as sequence", $this->prefix); $result = $this->_query($query); $tmp = $this->_fetch($result); - + return $tmp->sequence; } @@ -244,9 +256,9 @@ **/ function isTableExists($target_name) { $query = sprintf("select name from sysobjects where name = '%s%s' and xtype='U'", $this->prefix, $this->addQuotes($target_name)); - $result = $this->_query($query); + $result = $this->_query($query); $tmp = $this->_fetch($result); - + if(!$tmp) return false; return true; } @@ -391,11 +403,11 @@ if($unique) $unique_list[$unique][] = $name; else if($index) $index_list[$index][] = $name; } - + $schema = sprintf('create table [%s] (xe_seq int identity(1,1),%s%s)', $this->addQuotes($table_name), "\n", implode($column_schema,",\n")); $output = $this->_query($schema); if(!$output) return false; - + if(count($unique_list)) { foreach($unique_list as $key => $val) { $query = sprintf("create unique index %s on %s (%s);", $key, $table_name, '['.implode('],[',$val).']'); @@ -413,13 +425,13 @@ } } - + /** * @brief Handle the insertAct **/ // TODO Lookup _filterNumber against sql injection - see if it is still needed and how to integrate function _executeInsertAct($queryObject) { - $query = $this->getInsertSql($queryObject); + $query = $this->getInsertSql($queryObject, false); $this->param = $queryObject->getArguments(); return $this->_query($query); } @@ -428,7 +440,7 @@ * @brief Handle updateAct **/ function _executeUpdateAct($queryObject) { - $query = $this->getUpdateSql($queryObject); + $query = $this->getUpdateSql($queryObject, false); $this->param = $queryObject->getArguments(); return $this->_query($query); } @@ -437,47 +449,47 @@ * @brief Handle deleteAct **/ function _executeDeleteAct($queryObject) { - $query = $this->getDeleteSql($queryObject); + $query = $this->getDeleteSql($queryObject, false); $this->param = $queryObject->getArguments(); return $this->_query($query); } function getSelectSql($query){ $with_value = false; - + //$limitOffset = $query->getLimit()->getOffset(); //if($limitOffset) // TODO Implement Limit with offset with subquery $limit = '';$limitCount = ''; if($query->getLimit()) $limitCount = $query->getLimit()->getLimit(); - if($limitCount != '') $limit = 'SELECT TOP ' . $limitCount; - + if($limitCount != '') $limit = 'SELECT TOP ' . $limitCount; + $select = $query->getSelectString($with_values); if($select == '') return new Object(-1, "Invalid query"); if($limit != '') $select = $limit.' '.$select; else $select = 'SELECT ' .$select; - + $from = $query->getFromString($with_values); if($from == '') return new Object(-1, "Invalid query"); $from = ' FROM '.$from; - + $where = $query->getWhereString($with_values); if($where != '') $where = ' WHERE ' . $where; - + $groupBy = $query->getGroupByString(); if($groupBy != '') $groupBy = ' GROUP BY ' . $groupBy; - + $orderBy = $query->getOrderByString(); if($orderBy != '') $orderBy = ' ORDER BY ' . $orderBy; - + return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; } - + /** * @brief Handle selectAct * @@ -486,21 +498,21 @@ **/ function _executeSelectAct($queryObject) { $query = $this->getSelectSql($queryObject); - + // TODO Decide if we continue to pass parameters like this $this->param = $queryObject->getArguments(); - - $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_query($query); - if ($this->isError ()) return $this->queryError($queryObject); - else return $this->queryPageLimit($queryObject, $result); + $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; + $result = $this->_query($query); + + if ($this->isError ()) return $this->queryError($queryObject); + else return $this->queryPageLimit($queryObject, $result); } function getParser(){ return new DBParser("[", "]"); } - + function queryError($queryObject){ if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()){ $buff = new Object (); @@ -510,10 +522,10 @@ $buff->data = array (); $buff->page_navigation = new PageHandler (/*$total_count*/0, /*$total_page*/1, /*$page*/1, /*$page_count*/10);//default page handler values return $buff; - }else + }else return; } - + function queryPageLimit($queryObject, $result){ if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count @@ -526,12 +538,12 @@ $result_count = $this->_query($count_query); $count_output = $this->_fetch($result_count); $total_count = (int)$count_output->count; - + // Total pages if ($total_count) { $total_page = (int) (($total_count - 1) / $queryObject->getLimit()->list_count) + 1; } else $total_page = 1; - + $virtual_no = $total_count - ($queryObject->getLimit()->page - 1) * $queryObject->getLimit()->list_count; $data = $this->_fetch($result, $virtual_no); @@ -540,15 +552,15 @@ $buff->total_page = $total_page; $buff->page = $queryObject->getLimit()->page; $buff->data = $data; - $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); + $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); }else{ $data = $this->_fetch($result); $buff = new Object (); - $buff->data = $data; + $buff->data = $data; } return $buff; } - + } return new DBMssql; diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index 35ccfc453..287d4fb61 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -1,13 +1,13 @@ -column_name = $column_name; $this->argument = $argument; @@ -17,40 +17,50 @@ $this->_value = $argument->getValue(); else if(is_a($this->argument, 'Subquery')) $this->_value = $argument->toString(); - else + else $this->_value = $argument; } - + function hasArgument(){ return is_a($this->argument, 'Argument'); } - + function getArgument(){ if($this->hasArgument()) return $this->argument; return null; } - + function toString($withValue = true){ if(!$this->show()) return ''; if($withValue) return $this->toStringWithValue(); return $this->toStringWithoutValue(); } - + function toStringWithoutValue(){ - if($this->hasArgument()) - return $this->pipe . ' ' . $this->getConditionPart("?"); + if($this->hasArgument()){ + $value = $this->argument->getUnescapedValue(); + + if(is_array($value)){ + $q = ''; + foreach ($value as $v) $q .= '?,'; + if($q !== '') $q = substr($q, 0, -1); + $q = '(' . $q . ')'; + } + else $q = '?'; + return $this->pipe . ' ' . $this->getConditionPart($q); + } else return $this->toString(); } - + function toStringWithValue(){ return $this->pipe . ' ' . $this->getConditionPart($this->_value); } - + function setPipe($pipe){ $this->pipe = $pipe; } - + function show(){ if($this->hasArgument() && !$this->argument->isValid()) return false; if($this->hasArgument() && ($this->_value === '\'\'')) return false; @@ -75,14 +85,14 @@ if(!is_array($this->_value)) return false; if(count($this->_value)!=2) return false; - } + } return true; } - + function getConditionPart($value) { $name = $this->column_name; - $operation = $this->operation; - + $operation = $this->operation; + switch($operation) { case 'equal' : return $name.' = '.$value; @@ -123,7 +133,7 @@ return $name.' between ' . $value[0] . ' and ' . $value[1]; break; } - } + } } ?> \ No newline at end of file diff --git a/classes/db/queryparts/expression/UpdateExpression.class.php b/classes/db/queryparts/expression/UpdateExpression.class.php index 8ec05d250..eb938dc8b 100644 --- a/classes/db/queryparts/expression/UpdateExpression.class.php +++ b/classes/db/queryparts/expression/UpdateExpression.class.php @@ -1,46 +1,52 @@ -argument = $argument; } - + function getExpression($with_value = true){ if($with_value) return $this->getExpressionWithValue(); return $this->getExpressionWithoutValue(); } - + function getExpressionWithValue(){ $value = $this->argument->getValue(); + $operation = $this->argument->getColumnOperation(); + if(isset($operation)) + return "$this->column_name = $this->column_name $operation $value"; return "$this->column_name = $value"; } - + function getExpressionWithoutValue(){ + $operation = $this->argument->getColumnOperation(); + if(isset($operation)) + return "$this->column_name = $this->column_name $operation ?"; return "$this->column_name = ?"; } - + function getValue(){ // TODO Escape value according to column type instead of variable type $value = $this->argument->getValue(); if(!is_numeric($value)) return "'".$value."'"; return $value; } - + function show(){ if(!$this->argument->getValue()) return false; return true; } - + function getArgument(){ return $this->argument; } diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index b9c869946..3effc5f91 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -1,52 +1,62 @@ -value = $value; - $this->name = $name; + $this->name = $name; $this->isValid = true; } - + function getType(){ if(isset($this->type)) return $this->type; if(is_string($this->value)) return 'column_name'; return 'number'; } - + function setColumnType($value){ $this->type = $value; } - + + function setColumnOperation($operation){ + $this->column_operation = $operation; + } + function getName(){ return $this->name; } - + function getValue(){ $value = $this->escapeValue($this->value); return $this->toString($value); } + function getColumnOperation(){ + return $this->column_operation; + } + function getUnescapedValue(){ - return $this->toString($this->value); + return $this->value; } - + function toString($value){ if(is_array($value)) return '('.implode(',', $value).')'; - return $value; + return $value; } - + function escapeValue($value){ if($this->getType() == 'column_name'){ $dbParser = XmlQueryParser::getDBParser(); - return $dbParser->parseExpression($value); - } + return $dbParser->parseExpression($value); + } if(!isset($value)) return null; if(in_array($this->type, array('date', 'varchar', 'char','text', 'bigtext'))){ if(!is_array($value)) @@ -57,32 +67,32 @@ $value[$i] = $this->_escapeStringValue($value[$i]); //$value[$i] = '\''.$value[$i].'\''; } - } - return $value; - } - + } + return $value; + } + function _escapeStringValue($value){ $db = &DB::getInstance(); - $value = $db->addQuotes($value); + $value = $db->addQuotes($value); return '\''.$value.'\''; - + } - + function isValid(){ return $this->isValid; } - + function getErrorMessage(){ return $this->errorMessage; } - + function ensureDefaultValue($default_value){ - if(!isset($this->value) || $this->value == '') + if(!isset($this->value) || $this->value == '') $this->value = $default_value; } - - + + function checkFilter($filter_type){ if(isset($this->value) && $this->value != ''){ $val = $this->value; @@ -90,7 +100,7 @@ switch($filter_type) { case 'email' : case 'email_address' : - if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) { + if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) { $this->isValid = false; $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key)); } @@ -111,7 +121,7 @@ case 'number' : case 'numbers' : if(is_array($val)) $val = join(',', $val); - if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)){ + if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)){ $this->isValid = false; $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_number, $lang->{$key} ? $lang->{$key} : $key)); } @@ -128,10 +138,10 @@ $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key)); } break; - } + } } } - + function checkMaxLength($length){ if($this->value && (strlen($this->value) > $length)){ $this->isValid = false; @@ -139,15 +149,15 @@ $this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key); } } - + function checkMinLength($length){ if($this->value && (strlen($this->value) > $length)){ $this->isValid = false; $key = $this->name; $this->errorMessage = new Object(-1, $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key); } - } - + } + function checkNotNull(){ if(!isset($this->value)){ $this->isValid = false; diff --git a/classes/xml/xmlquery/queryargument/DefaultValue.class.php b/classes/xml/xmlquery/queryargument/DefaultValue.class.php index 73846b218..3ee5d4358 100644 --- a/classes/xml/xmlquery/queryargument/DefaultValue.class.php +++ b/classes/xml/xmlquery/queryargument/DefaultValue.class.php @@ -1,35 +1,46 @@ -column_name = $column_name; + $dbParser = &XmlQueryParser::getDBParser(); + $this->column_name = $dbParser->parseColumnName($column_name); $this->value = $value; $this->value = $this->_setValue(); } - + function isString(){ $str_pos = strpos($this->value, '('); if($str_pos===false) return true; - return false; + return false; } - + function isSequence(){ return $this->is_sequence; } - + + function isOperation(){ + return $this->is_operation; + } + + function getOperation(){ + return $this->operation; + } + function _setValue(){ if(!isset($this->value)) return; - + // If value contains comma separated values and does not contain paranthesis // -> default value is an array if(strpos($this->value, ',') !== false && strpos($this->value, '(') === false) { return sprintf('array(%s)', $this->value); } - + $str_pos = strpos($this->value, '('); // // TODO Replace this with parseExpression if($str_pos===false) return '\''.$this->value.'\''; @@ -37,7 +48,7 @@ $func_name = substr($this->value, 0, $str_pos); $args = substr($this->value, $str_pos+1, strlen($value)-1); - + switch($func_name) { case 'ipaddress' : $val = '$_SERVER[\'REMOTE_ADDR\']'; @@ -54,25 +65,30 @@ break; case 'plus' : $args = abs($args); - // TODO Make sure column name is escaped - $val = sprintf('"%s+%d"', $this->column_name, $args); + $this->is_operation = true; + $this->operation = '+'; + $val = sprintf('%d', $args); break; case 'minus' : $args = abs($args); - $val = sprintf('"%s-%d"', $this->column_name, $args); - break; + $this->is_operation = true; + $this->operation = '-'; + $val = sprintf('%d', $args); + break; case 'multiply' : $args = intval($args); - $val = sprintf('"%s*%d"', $this->column_name, $args); + $this->is_operation = true; + $this->operation = '*'; + $val = sprintf('%d', $args); break; default : $val = '\'' . $this->value . '\''; //$val = $this->value; } - - return $val; + + return $val; } - + function toString(){ return $this->value; } diff --git a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php index e89820081..03816e447 100644 --- a/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php +++ b/classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php @@ -1,4 +1,4 @@ -argument = $argument; $this->argument_name = $this->argument->getArgumentName(); - + $this->default_value = $tag->attrs->default; $this->notnull = $tag->attrs->notnull; $this->filter = $tag->attrs->filter; $this->min_length = $tag->attrs->min_length; - $this->max_length = $tag->attrs->max_length; + $this->max_length = $tag->attrs->max_length; } - + function toString(){ $validator = ''; if(isset($this->default_value)){ $this->default_value = new DefaultValue($this->argument_name, $this->default_value); if($this->default_value->isSequence()) $validator .= '$db = &DB::getInstance(); $sequence = $db->getNextSequence(); '; + if($this->default_value->isOperation()) + $validator .= sprintf("$%s_argument->setColumnOperation('%s');\n" + , $this->argument_name + , $this->default_value->getOperation() + ); $validator .= sprintf("$%s_argument->ensureDefaultValue(%s);\n" , $this->argument_name , $this->default_value->toString() ); - } + } if($this->notnull){ $validator .= sprintf("$%s_argument->checkNotNull();\n" , $this->argument_name - ); + ); } if($this->filter){ $validator .= sprintf("$%s_argument->checkFilter('%s');\n" , $this->argument_name , $this->filter - ); + ); } if($this->min_length){ $validator .= sprintf("$%s_argument->checkMinLength(%s);\n" , $this->argument_name , $this->min_length - ); + ); } if($this->max_length){ $validator .= sprintf("$%s_argument->checkMaxLength(%s);\n" , $this->argument_name , $this->max_length - ); - } + ); + } return $validator; } } diff --git a/test-phpUnit/config/config.inc.php b/test-phpUnit/config/config.inc.php index 9bf62db40..b1386b2f6 100644 --- a/test-phpUnit/config/config.inc.php +++ b/test-phpUnit/config/config.inc.php @@ -1,30 +1,32 @@ db_type = 'cubrid'; @@ -22,17 +22,12 @@ $db_info->db_userid = 'dba'; $db_info->db_password = 'arniarules'; $db_info->db_database = 'xe15QA'; - $db_info->db_table_prefix = 'xe'; + $db_info->db_table_prefix = 'xe'; + + $oContext->setDbInfo($db_info); - $oContext->setDbInfo($db_info); - // remove cache dir - $tmp_cache_list = FileHandler::readDir('./files','/(^cache_[0-9]+)/'); - if($tmp_cache_list){ - foreach($tmp_cache_list as $tmp_dir){ - if($tmp_dir) FileHandler::removeDir('./files/'.$tmp_dir); - } - } + FileHandler::removeDir( _XE_PATH_ . 'files/cache'); } /** @@ -41,6 +36,6 @@ protected function tearDown() { unset($GLOBALS['__DB__']); XmlQueryParser::setDBParser(null); - } + } } ?> diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php index c3e5d2d5a..17b80ab90 100644 --- a/test-phpUnit/db/DBTest.php +++ b/test-phpUnit/db/DBTest.php @@ -1,16 +1,16 @@ getNewParserOutputString($xml_file, $argsString); echo $outputString; $output = eval($outputString); - + if(!is_a($output, 'Query')){ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { @@ -23,8 +23,8 @@ $expected = Helper::cleanString($expected); } $this->assertEquals($expected, $querySql); - } - + } + function _testPreparedQuery($xml_file, $argsString, $expected, $methodName, $expectedArgs = NULL){ $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, $argsString); @@ -34,7 +34,7 @@ if(!$output->toBool()) $querySql = "Date incorecte! Query-ul nu a putut fi executat."; }else { $db = &DB::getInstance(); - $querySql = $db->{$methodName}($output); + $querySql = $db->{$methodName}($output, false); $queryArguments = $output->getArguments(); // Remove whitespaces, tabs and all @@ -51,14 +51,14 @@ //echo "$i: $expectedArgs[$i] vs $queryArguments[$i]->getValue()"; $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue()); } - } - + } + function _testCachedOutput($expected, $actual){ $expected = Helper::cleanString($expected); $actual = Helper::cleanString($actual); - + $this->assertEquals($expected, $actual); - + } } diff --git a/test-phpUnit/db/MssqlOnlineTest.php b/test-phpUnit/db/MssqlOnlineTest.php new file mode 100644 index 000000000..10cfe0423 --- /dev/null +++ b/test-phpUnit/db/MssqlOnlineTest.php @@ -0,0 +1,41 @@ +db_type = 'mssql'; + $db_info->db_port = '3306'; + $db_info->db_hostname = 'PHENOMII\SQL2008EXPRESS'; + $db_info->db_userid = 'dba'; + $db_info->db_password = 'arniarules'; + $db_info->db_database = 'xe-15-db'; + $db_info->db_table_prefix = 'xe'; + + $oContext->setDbInfo($db_info); + + // remove cache dir + FileHandler::removeDir( _XE_PATH_ . 'files/cache'); + } + + /** + * Free resources - reset static DB and QueryParser + */ + protected function tearDown() { + unset($GLOBALS['__DB__']); + XmlQueryParser::setDBParser(null); + } + } +?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php index e731f0a45..23f19d5c8 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridUpdateTest.php @@ -6,10 +6,10 @@ function _test($xml_file, $argsString, $expected){ $this->_testQuery($xml_file, $argsString, $expected, 'getUpdateSql'); } - - function test_module_updateModule(){ + + function test_module_updateModule(){ $xml_file = _XE_PATH_ . "modules/module/queries/updateModule.xml"; - $argsString = ' $args->module_category_srl = 0; + $argsString = ' $args->module_category_srl = 0; $args->browser_title = "test"; $args->layout_srl = 0; $args->mlayout_srl = 0; @@ -18,7 +18,7 @@ $args->use_mobile = ""; $args->site_srl = 0; $args->module_srl = 47374;'; - $expected = 'UPDATE "xe_modules" + $expected = 'UPDATE "xe_modules" SET "module" = \'page\' , "mid" = \'test\' , "browser_title" = \'test\' @@ -27,47 +27,47 @@ , "open_rss" = \'Y\' , "header_text" = \'\' , "footer_text" = \'\' - , "use_mobile" = \'n\' - WHERE "site_srl" = 0 + , "use_mobile" = \'n\' + WHERE "site_srl" = 0 AND "module_srl" = 47374'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - function test_module_updateMember(){ + function test_member_updateLastLogin(){ $xml_file = _XE_PATH_ . "modules/member/queries/updateLastLogin.xml"; - $argsString = ' $args->member_srl = 4; + $argsString = ' $args->member_srl = 4; $args->last_login = "20110607120549";'; $expected = 'UPDATE "xe_member" SET "member_srl" = 4, "last_login" = \'20110607120549\' WHERE "member_srl" = 4'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - - function test_module_updatePoint(){ + + function test_module_updatePoint(){ $xml_file = _XE_PATH_ . "modules/point/queries/updatePoint.xml"; - $argsString = ' $args->member_srl = 4; + $argsString = ' $args->member_srl = 4; $args->point = 105;'; $expected = 'UPDATE "xe_point" SET "point" = 105 WHERE "member_srl" = 4'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - - function test_module_updateCounterUnique(){ + + function test_module_updateCounterUnique(){ $xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml"; $argsString = '$args->regdate = 20110607; '; - $expected = 'UPDATE "xe_counter_status" SET "unique_visitor" = unique_visitor+1, - "pageview" = pageview+1 WHERE "regdate" = 20110607 '; - $this->_test($xml_file, $argsString, $expected); + $expected = 'UPDATE "xe_counter_status" SET "unique_visitor" = "unique_visitor" + 1, + "pageview" = "pageview" + 1 WHERE "regdate" = 20110607 '; + $this->_test($xml_file, $argsString, $expected); } - - function test_module_updateMenu(){ + + function test_module_updateMenu(){ $xml_file = _XE_PATH_ . "modules/menu/queries/updateMenu.xml"; $argsString = '$args->menu_srl = 204; $args->title = "test_menu"; '; $expected = 'UPDATE "xe_menu" SET "title" = \'test_menu\' WHERE "menu_srl" = 204'; - $this->_test($xml_file, $argsString, $expected); - } - + $this->_test($xml_file, $argsString, $expected); + } + // $queryTester->test_admin_deleteActionForward(); // $queryTester->test_module_insertModule(); - - + + } \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php index ce0c37777..f5c0c5d25 100644 --- a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php +++ b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php @@ -6,28 +6,28 @@ function _test($xml_file, $argsString, $expected, $expectedArgs = NULL){ $this->_testPreparedQuery($xml_file, $argsString, $expected, 'getSelectSql', $expectedArgs = NULL); } - + function testSelectStar(){ $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; $argsString = '$args->module_srl = 10;'; $expected = 'SELECT * FROM [xe_module_admins] as [module_admins] , [xe_member] as [member] WHERE [module_srl] = ? and [member].[member_srl] = [module_admins].[member_srl]'; $this->_test($xml_file, $argsString, $expected, array(10)); } - + function testRquiredParameter(){ $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; $argsString = ''; $expected = 'Date incorecte! Query-ul nu a putut fi executat.'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - + function testWithoutCategoriesTag(){ $xml_file = _XE_PATH_ . "modules/module/queries/getModuleCategories.xml"; $argsString = ''; $expected = 'SELECT * FROM [xe_module_categories] as [module_categories] ORDER BY [title] asc'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - + function test_module_getDefaultModules(){ $xml_file = _XE_PATH_ . "modules/module/queries/getDefaultModules.xml"; $argsString = ''; @@ -36,14 +36,14 @@ , [modules].[mid] , [modules].[browser_title] , [module_categories].[title] as [category] - , [modules].[module_srl] - FROM [xe_modules] as [modules] - left join [xe_module_categories] as [module_categories] - on [module_categories].[module_category_srl] = [modules].[module_category_srl] - WHERE [modules].[site_srl] = ? + , [modules].[module_srl] + FROM [xe_modules] as [modules] + left join [xe_module_categories] as [module_categories] + on [module_categories].[module_category_srl] = [modules].[module_category_srl] + WHERE [modules].[site_srl] = ? ORDER BY [modules].[module] asc, [module_categories].[title] asc, [modules].[mid] asc'; - $this->_test($xml_file, $argsString, $expected, array(0)); - } + $this->_test($xml_file, $argsString, $expected, array(0)); + } function test_module_getSiteInfo(){ $xml_file = _XE_PATH_ . "modules/module/queries/getSiteInfo.xml"; @@ -72,8 +72,8 @@ , [sites].[domain] as [domain] , [sites].[index_module_srl] as [index_module_srl] , [sites].[default_language] as [default_language] - FROM [xe_sites] as [sites] - left join [xe_modules] as [modules] on [modules].[module_srl] = [sites].[index_module_srl] + FROM [xe_sites] as [sites] + left join [xe_modules] as [modules] on [modules].[module_srl] = [sites].[index_module_srl] WHERE [sites].[site_srl] = ? '; $this->_test($xml_file, $argsString, $expected, array(0)); } @@ -81,77 +81,86 @@ function test_addon_getAddonInfo(){ $xml_file = _XE_PATH_ . "modules/addon/queries/getAddonInfo.xml"; $argsString = '$args->addon = "captcha";'; - $expected = 'SELECT * + $expected = 'SELECT * FROM [xe_addons] as [addons] WHERE [addon] = ? '; $this->_test($xml_file, $argsString, $expected, array("'captcha'")); } - + function test_addon_getAddons(){ $xml_file = _XE_PATH_ . "modules/addon/queries/getAddons.xml"; $argsString = ''; - $expected = 'SELECT * + $expected = 'SELECT * FROM [xe_addons] as [addons] ORDER BY [addon] asc'; $this->_test($xml_file, $argsString, $expected); - } - + } + function test_admin_getCommentCount(){ $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentCount.xml"; $argsString = ''; - $expected = 'SELECT count(*) as [count] + $expected = 'SELECT count(*) as [count] FROM [xe_comments] as [comments]'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } function test_admin_getCommentDeclaredStatus(){ $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentDeclaredStatus.xml"; $argsString = '$args->date = "20110411";'; - $expected = 'SELECT TOP 2 substr([regdate],1,8) as [date], count(*) as [count] + $expected = 'SELECT TOP 2 substr([regdate],1,8) as [date], count(*) as [count] FROM [xe_comment_declared_log] as [comment_declared_log] - WHERE [regdate] >= ? - GROUP BY substr([regdate],1,8) + WHERE [regdate] >= ? + GROUP BY substr([regdate],1,8) ORDER BY substr([regdate],1,8) asc'; - $this->_test($xml_file, $argsString, $expected, array("'20110411'")); + $this->_test($xml_file, $argsString, $expected, array("'20110411'")); } - + function test_member_getAutoLogin(){ $xml_file = _XE_PATH_ . "modules/member/queries/getAutoLogin.xml"; $argsString = '$args->autologin_key = 10;'; $expected = 'SELECT [member].[user_id] as [user_id] , [member].[password] as [password] , [member_autologin].[autologin_key] as [autologin_key] - FROM [xe_member] as [member] , [xe_member_autologin] as [member_autologin] - WHERE [member_autologin].[autologin_key] = ? + FROM [xe_member] as [member] , [xe_member_autologin] as [member_autologin] + WHERE [member_autologin].[autologin_key] = ? and [member].[member_srl] = [member_autologin].[member_srl]'; $this->_test($xml_file, $argsString, $expected, array("'10'")); } - + function test_opage_getOpageList(){ $xml_file = _XE_PATH_ . "modules/opage/queries/getOpageList.xml"; $argsString = '$args->s_title = "yuhuu"; $args->module = \'opage\';'; - $expected = 'SELECT TOP 20 * + $expected = 'SELECT TOP 20 * FROM [xe_modules] as [modules] - WHERE [module] = ? and ([browser_title] like ?) + WHERE [module] = ? and ([browser_title] like ?) ORDER BY [module_srl] desc'; - $this->_test($xml_file, $argsString, $expected, array("'opage'", "'%yuhuu%'")); + $this->_test($xml_file, $argsString, $expected, array("'opage'", "'%yuhuu%'")); } - + + function test_module_getExtraVars(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getModuleExtraVars.xml"; + $argsString = '$args->module_srl = 25;'; + $expected = 'SELECT * FROM [xe_module_extra_vars] as [module_extra_vars] WHERE [module_srl] in (?)'; + $this->_test($xml_file, $argsString, $expected, array("25")); + } + + + // TODO Something fishy about this query - to be investigated /* function test_syndication_getGrantedModules(){ $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml"; $argsString = '$args->module_srl = 12; $args->name = array(\'access\',\'view\',\'list\');'; - $expected = 'select "module_srl" - from "xe_module_grants" as "module_grants" - where "name" in (?) - and ("group_srl" >= -2 - or "group_srl" = -2 - or "group_srl" = -2) + $expected = 'select "module_srl" + from "xe_module_grants" as "module_grants" + where "name" in (?) + and ("group_srl" >= -2 + or "group_srl" = -2 + or "group_srl" = -2) group by "module_srl"'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } */ } \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/mssql/MssqlUpdateOnlineTest.php b/test-phpUnit/db/xml_query/mssql/MssqlUpdateOnlineTest.php new file mode 100644 index 000000000..bcd57fbb2 --- /dev/null +++ b/test-phpUnit/db/xml_query/mssql/MssqlUpdateOnlineTest.php @@ -0,0 +1,12 @@ +regdate = 20110211; + + $output = executeQuery("counter.updateCounterUnique", $args); + $this->assertEquals(0, $output->error, $output->error + ' ' + $output->message); + } + } + +?> \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/mssql/MssqlUpdateTest.php b/test-phpUnit/db/xml_query/mssql/MssqlUpdateTest.php new file mode 100644 index 000000000..1f2b183a0 --- /dev/null +++ b/test-phpUnit/db/xml_query/mssql/MssqlUpdateTest.php @@ -0,0 +1,17 @@ +_testPreparedQuery($xml_file, $argsString, $expected, 'getUpdateSql', $expectedArgs = NULL); + } + + function test_counter_updateCounterUnique(){ + $xml_file = _XE_PATH_ . "modules/counter/queries/updateCounterUnique.xml"; + $argsString = '$args->regdate = 25;'; + $expected = 'UPDATE [xe_counter_status] SET [unique_visitor] = [unique_visitor] + ?, [pageview] = [pageview] + ? WHERE [regdate] = ?'; + $this->_test($xml_file, $argsString, $expected, array("25", 1, 1)); + } + } +?> \ No newline at end of file From 39c2c004c22b51b5a4c42108280c0266bc22dcac Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 25 Jul 2011 16:47:22 +0000 Subject: [PATCH 76/82] Prepared statements - if argument is not given as array (eg. for IN clauses) even though it should be, convert it to an array. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8633 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../queryparts/condition/Condition.class.php | 1 + .../xml/xmlquery/argument/Argument.class.php | 84 ++++++------- .../argument/ConditionArgument.class.php | 114 +++--------------- .../db/xml_query/cubrid/CubridInsertTest.php | 70 +++++------ .../cubrid/CubridSelectOnlineTest.php | 26 ++-- .../db/xml_query/mssql/MssqlSelectTest.php | 8 ++ 6 files changed, 118 insertions(+), 185 deletions(-) diff --git a/classes/db/queryparts/condition/Condition.class.php b/classes/db/queryparts/condition/Condition.class.php index 287d4fb61..e9501b516 100644 --- a/classes/db/queryparts/condition/Condition.class.php +++ b/classes/db/queryparts/condition/Condition.class.php @@ -64,6 +64,7 @@ function show(){ if($this->hasArgument() && !$this->argument->isValid()) return false; if($this->hasArgument() && ($this->_value === '\'\'')) return false; + if(is_array($this->_value) && count($this->_value) === 1 && $this->_value[0] === '') return false; switch($this->operation) { case 'equal' : case 'more' : diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 3effc5f91..14bc73a74 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -97,48 +97,48 @@ if(isset($this->value) && $this->value != ''){ $val = $this->value; $key = $this->name; - switch($filter_type) { - case 'email' : - case 'email_address' : - if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) { - $this->isValid = false; - $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key)); - } - break; - case 'homepage' : - if(!preg_match('/^(http|https)+(:\/\/)+[0-9a-z_-]+\.[^ ]+$/is', $val)) { - $this->isValid = false; - $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_homepage, $lang->{$key} ? $lang->{$key} : $key)); - } - break; - case 'userid' : - case 'user_id' : - if(!preg_match('/^[a-zA-Z]+([_0-9a-zA-Z]+)*$/is', $val)) { - $this->isValid = false; - $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_userid, $lang->{$key} ? $lang->{$key} : $key)); - } - break; - case 'number' : - case 'numbers' : - if(is_array($val)) $val = join(',', $val); - if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)){ - $this->isValid = false; - $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_number, $lang->{$key} ? $lang->{$key} : $key)); - } - break; - case 'alpha' : - if(!preg_match('/^[a-z]+$/is', $val)) { - $this->isValid = false; - $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha, $lang->{$key} ? $lang->{$key} : $key)); - } - break; - case 'alpha_number' : - if(!preg_match('/^[0-9a-z]+$/is', $val)) { - $this->isValid = false; - $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key)); - } - break; - } + switch($filter_type) { + case 'email' : + case 'email_address' : + if(!preg_match('/^[_0-9a-z-]+(\.[_0-9a-z-]+)*@[0-9a-z-]+(\.[0-9a-z-]+)*$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'homepage' : + if(!preg_match('/^(http|https)+(:\/\/)+[0-9a-z_-]+\.[^ ]+$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_homepage, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'userid' : + case 'user_id' : + if(!preg_match('/^[a-zA-Z]+([_0-9a-zA-Z]+)*$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_userid, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'number' : + case 'numbers' : + if(is_array($val)) $val = join(',', $val); + if(!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)){ + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_number, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'alpha' : + if(!preg_match('/^[a-z]+$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + case 'alpha_number' : + if(!preg_match('/^[0-9a-z]+$/is', $val)) { + $this->isValid = false; + $this->errorMessage = new Object(-1, sprintf($lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key)); + } + break; + } } } diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index 2e2267793..da938c7e8 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -1,25 +1,28 @@ -operation = $operation; - + $this->operation = $operation; + if($this->type !== 'date'){ $dbParser = XmlQueryParser::getDBParser(); $this->value = $dbParser->escapeStringValue($this->value); - } + } } - + function createConditionValue(){ if(!isset($this->value)) return; - + $name = $this->column_name; $operation = $this->operation; - $value = $this->value; + $value = $this->value; switch($operation) { case 'like_prefix' : @@ -27,7 +30,7 @@ break; case 'like_tail' : $this->value = '%'.$value; - break; + break; case 'like' : $this->value = '%'.$value.'%'; break; @@ -35,103 +38,24 @@ if(!is_array($value)) $this->value = array($value); break; } - /* - //if(!in_array($operation,array('in','notin','between')) && is_array($value)){ - // $value = join(',', $value); - //} - // Daca operatia nu este in, notin, between si coloana e de tip numeric - // daca valoarea e array -> concatenare - // daca valoarea nu e array si nici nu contine paranteze (nu e functie) -> return (int) - // altfel return valoare - - // if(!in_array($operation,array('in','notin','between')) && $type == 'number') { - // if(is_array($value)){ - // $value = join(',',$value); - // } - // if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; - // return $value; - // } - // - // if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { - // list($table_name, $column_name) = explode('.', $value); - // if($column_type[$column_name]) return $value; - // } - - switch($operation) { - case 'like_prefix' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = $value.'%'; - break; - case 'like_tail' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value; - break; - case 'like' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value.'%'; - break; - // case 'notin' : - // if(is_array($value)) - // { - // $value = $this->addQuotesArray($value); - // if($type=='number') return join(',',$value); - // else return "'". join("','",$value)."'"; - // } - // else - // { - // return $value; - // } - // break; - // case 'in' : - // if(is_array($value)) - // { - // $value = $this->addQuotesArray($value); - // if($type=='number') return join(',',$value); - // else return "'". join("','",$value)."'"; - // } - // else - // { - // return $value; - // } - // break; - // case 'between' : - // if(!is_array($value)) $value = array($value); - // $value = $this->addQuotesArray($value); - // if($type!='number') - // { - // foreach($value as $k=>$v) - // { - // $value[$k] = "'".$v."'"; - // } - // } - - //return $value; - break; - default: - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - } - $this->value = $value; - //return "'".$this->addQuotes($value)."'"; - */ - } - + function getType(){ return $this->type; } - + function setColumnType($column_type){ if(!isset($this->value)) return; if($column_type === '') return; - + $this->type = $column_type; - + //if($column_type === '') $column_type = 'varchar'; } - - + + } ?> \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php index b52a6f4d4..80a658988 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridInsertTest.php @@ -7,14 +7,14 @@ $this->_testQuery($xml_file, $argsString, $expected, 'getInsertSql'); } - + /** * Note: this test can fail when comaparing regdate from the $args with * regdate from the expected string - a few seconds difference */ - function test_module_insertModule(){ + function test_module_insertModule(){ $xml_file = _XE_PATH_ . "modules/module/queries/insertModule.xml"; - $argsString = ' $args->module_category_srl = 0; + $argsString = ' $args->module_category_srl = 0; $args->browser_title = "test"; $args->layout_srl = 0; $args->mlayout_srl = 0; @@ -22,7 +22,7 @@ $args->mid = "test"; $args->site_srl = 0; $args->module_srl = 47374;'; - $expected = 'insert into "xe_modules" + $expected = 'insert into "xe_modules" ("site_srl" , "module_srl" , "module_category_srl" @@ -34,8 +34,8 @@ , "open_rss" , "regdate" , "mlayout_srl" - , "use_mobile") - values + , "use_mobile") + values (0 , 47374 , 0 @@ -48,42 +48,42 @@ , \''.date("YmdHis").'\' , 0 , \'n\')'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - + function test_module_insertSiteTodayStatus(){ - //\''.date("YmdHis").'\' + //\''.date("YmdHis").'\' $xml_file = _XE_PATH_ . "modules/counter/queries/insertTodayStatus.xml"; - $argsString = ' $args->regdate = 0; + $argsString = ' $args->regdate = 0; $args->unique_visitor = 0; $args->pageview = 0;'; - $expected = 'insert into "xe_counter_status" + $expected = 'insert into "xe_counter_status" ("regdate" , "unique_visitor" - , "pageview") - values - (0 + , "pageview") + values + ('.date("YmdHis").' , 0 , 0)'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - - function test_module_insertCounterLog(){ + + function test_module_insertCounterLog(){ $xml_file = _XE_PATH_ . "modules/counter/queries/insertCounterLog.xml"; - $argsString = ' $args->site_srl = 0; + $argsString = ' $args->site_srl = 0; $args->regdate = "20110607120619"; $args->ipaddress = "127.0.0.1"; $args->user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24";'; - $expected = 'insert into "xe_counter_log" - ("site_srl", "regdate", "ipaddress", "user_agent") + $expected = 'insert into "xe_counter_log" + ("site_srl", "regdate", "ipaddress", "user_agent") VALUES (0, \'20110607120619\', \'127.0.0.1\', \'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24\') '; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - function test_module_insertMember(){ + function test_module_insertMember(){ $xml_file = _XE_PATH_ . "modules/member/queries/insertMember.xml"; - $argsString = ' $args->member_srl = 203; + $argsString = ' $args->member_srl = 203; $args->user_id = "cacao"; $args->email_address = "teta@ar.ro"; $args->password = "23e5484cb88f3c07bcce2920a5e6a2a7"; @@ -102,27 +102,27 @@ $args->extra_vars = "O:8:\"stdClass\":2:{s:4:\"body\";s:0:\"\";s:7:\"_filter\";s:6:\"insert\";}"; $args->list_order = -203; '; - $expected = 'INSERT INTO "xe_member" + $expected = 'INSERT INTO "xe_member" ("member_srl", "user_id", "email_address", "password", "email_id", "email_host", "user_name", "nick_name", "homepage", "allow_mailing", "allow_message", "denied", "regdate", "change_password_date", - "last_login", "is_admin", "extra_vars", "list_order") - VALUES (203, \'cacao\', \'teta@ar.ro\', \'23e5484cb88f3c07bcce2920a5e6a2a7\', \'teta\', \'ar.ro\', \'trident\', - \'aloha\', \'http://jkgjfk./ww\', \'Y\', \'Y\', \'N\', \'20110607121952\', \'20110607121952\', + "last_login", "is_admin", "extra_vars", "list_order") + VALUES (203, \'cacao\', \'teta@ar.ro\', \'23e5484cb88f3c07bcce2920a5e6a2a7\', \'teta\', \'ar.ro\', \'trident\', + \'aloha\', \'http://jkgjfk./ww\', \'Y\', \'Y\', \'N\', \'20110607121952\', \'20110607121952\', \'20110607121952\', \'N\', \'O:8:"stdClass":2:{s:4:"body";s:0:"";s:7:"_filter";s:6:"insert";}\', -203)'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - - function test_module_insertModuleExtraVars(){ + + function test_module_insertModuleExtraVars(){ $xml_file = _XE_PATH_ . "modules/module/queries/insertModuleExtraVars.xml"; - $argsString = ' $args->module_srl = 202; + $argsString = ' $args->module_srl = 202; $args->name = "_filter"; $args->value = "insert_page"; '; - $expected = 'INSERT INTO "xe_module_extra_vars" - ("module_srl", "name", "value") + $expected = 'INSERT INTO "xe_module_extra_vars" + ("module_srl", "name", "value") VALUES (202, \'_filter\', \'insert_page\') '; - $this->_test($xml_file, $argsString, $expected); - } + $this->_test($xml_file, $argsString, $expected); + } } \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php index fcc7eecb6..e0b787b1c 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php @@ -1,23 +1,23 @@ mid = 'test_4l8ci4vv0n'; $args->site_srl = 0; $output = executeQuery('module.getMidInfo', $args); $this->assertNotNull($output); $this->assertNotNull($output->data, $output->message); - $this->assertEquals($output->data->module_srl, 111); + $this->assertEquals($output->data->module_srl, 111); } - - function test_module_getInfo(){ + + function test_module_getInfo(){ $args->site_srl = 0; $output = executeQuery('module.getSiteInfo', $args); $this->assertTrue(is_a($output, 'Object')); $this->assertEquals(0, $output->error, $output->message); } - + function test_document_getDocumentList_pagination(){ $args->sort_index = 'list_order'; $args->order_type = 'asc'; @@ -25,11 +25,11 @@ $args->list_count = 30; $args->page_count = 10; $args->s_member_srl = 4; - + $output = executeQuery('document.getDocumentList', $args); - $this->assertEquals(0, $output->error, $output->message); + $this->assertEquals(0, $output->error, $output->message . PHP_EOL . $output->variables["_query"]); } - + function test_syndication_getDocumentList(){ $args->module_srl = NULL; $args->exclude_module_srl = NULL; @@ -37,7 +37,7 @@ $args->sort_index = 'list_order'; $args->order_type = 'asc'; $args->page = 5; - $args->list_count = 30; + $args->list_count = 30; $args->page_count = 10; $args->start_date = NULL; $args->end_date = NULL; @@ -45,8 +45,8 @@ $output = executeQuery('document.getDocumentList', $args); $this->assertTrue(is_int($output->page), $output->message); - } - + } + function test_member_getMemberList(){ $args->is_admin = ''; $args->is_denied = ''; @@ -54,9 +54,9 @@ $args->sort_order = 'asc'; $args->list_count = 40; $args->page_count = 10; - + $output = executeQuery('member.getMemberList', $args); - $this->assertEquals(0, $output->error, $output->message); + $this->assertEquals(0, $output->error, $output->message); } } ?> diff --git a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php index f5c0c5d25..4bf2cba5e 100644 --- a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php +++ b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php @@ -145,6 +145,14 @@ $this->_test($xml_file, $argsString, $expected, array("25")); } + function test_module_getModuleSites(){ + $xml_file = _XE_PATH_ . "modules/module/queries/getModuleSites.xml"; + //$argsString = '$args->module_srls = array(67, 65);'; + $argsString = '$args->module_srls = "67, 65";'; + $expected = 'SELECT [modules].[module_srl] as [module_srl], [sites].[domain] as [domain] FROM [xe_modules] as [modules] , [xe_sites] as [sites] WHERE [modules].[module_srl] in (?,?) and [sites].[site_srl] = [modules].[site_srl]'; + $this->_test($xml_file, $argsString, $expected, array("67", "65")); + } + // TODO Something fishy about this query - to be investigated From 1a6ede2e06953ca9bddffa221f5d6482e2804b7b Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 25 Jul 2011 16:48:01 +0000 Subject: [PATCH 77/82] Fixed counter query - it would always generate an unique constraint violation because default value was 0 for all arguments. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8634 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- modules/counter/queries/insertTodayStatus.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/counter/queries/insertTodayStatus.xml b/modules/counter/queries/insertTodayStatus.xml index 1aa8d85f6..496c78e62 100644 --- a/modules/counter/queries/insertTodayStatus.xml +++ b/modules/counter/queries/insertTodayStatus.xml @@ -3,7 +3,7 @@ - + From 620b18e532ffd3cb175c56f6953d012072623758 Mon Sep 17 00:00:00 2001 From: ucorina Date: Mon, 25 Jul 2011 17:33:27 +0000 Subject: [PATCH 78/82] Update to string array arguments - added format with SQLSRV_PHPTYPE_STRING. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8635 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBMssql.class.php | 7 +++- .../xml/xmlquery/argument/Argument.class.php | 6 ++- test-phpUnit/db/DBTest.php | 3 +- .../xml_query/mssql/MssqlSelectOnlineTest.php | 11 ++++++ .../db/xml_query/mssql/MssqlSelectTest.php | 38 +++++++++---------- 5 files changed, 39 insertions(+), 26 deletions(-) create mode 100644 test-phpUnit/db/xml_query/mssql/MssqlSelectOnlineTest.php diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index cdf1cf995..1810247f3 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -180,9 +180,12 @@ if(is_array($value)) $_param = array_merge($_param, $value); else $_param[] = $o->getUnescapedValue(); }else{ - // TODO treat arrays here too $value = $o->getUnescapedValue(); - $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); + if(is_array($value)) { + foreach($value as $v) + $_param[] = array($v, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); + } + else $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); } } } diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 14bc73a74..086e53ef2 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -35,7 +35,7 @@ } function getValue(){ - $value = $this->escapeValue($this->value); + $value = $this->getEscapedValue(); return $this->toString($value); } @@ -43,6 +43,10 @@ return $this->column_operation; } + function getEscapedValue(){ + return $this->escapeValue($this->value); + } + function getUnescapedValue(){ return $this->value; } diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php index 17b80ab90..8fa514b39 100644 --- a/test-phpUnit/db/DBTest.php +++ b/test-phpUnit/db/DBTest.php @@ -48,8 +48,7 @@ // Test query arguments $argCount = count($expectedArgs); for($i = 0; $i < $argCount; $i++){ - //echo "$i: $expectedArgs[$i] vs $queryArguments[$i]->getValue()"; - $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getValue()); + $this->assertEquals($expectedArgs[$i], $queryArguments[$i]->getEscapedValue()); } } diff --git a/test-phpUnit/db/xml_query/mssql/MssqlSelectOnlineTest.php b/test-phpUnit/db/xml_query/mssql/MssqlSelectOnlineTest.php new file mode 100644 index 000000000..44867e38f --- /dev/null +++ b/test-phpUnit/db/xml_query/mssql/MssqlSelectOnlineTest.php @@ -0,0 +1,11 @@ +module_srl = 67; + $output = executeQuery("syndication.getGrantedModule", $args); + $this->assertEquals(0, $output->error, $output->error + ' ' + $output->message); + } + } + +?> \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php index 4bf2cba5e..8d8e0f7d2 100644 --- a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php +++ b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php @@ -4,7 +4,7 @@ class MssqlSelectTest extends MssqlTest { function _test($xml_file, $argsString, $expected, $expectedArgs = NULL){ - $this->_testPreparedQuery($xml_file, $argsString, $expected, 'getSelectSql', $expectedArgs = NULL); + $this->_testPreparedQuery($xml_file, $argsString, $expected, 'getSelectSql', $expectedArgs); } function testSelectStar(){ @@ -142,7 +142,7 @@ $xml_file = _XE_PATH_ . "modules/module/queries/getModuleExtraVars.xml"; $argsString = '$args->module_srl = 25;'; $expected = 'SELECT * FROM [xe_module_extra_vars] as [module_extra_vars] WHERE [module_srl] in (?)'; - $this->_test($xml_file, $argsString, $expected, array("25")); + $this->_test($xml_file, $argsString, $expected, array(array(25))); } function test_module_getModuleSites(){ @@ -150,25 +150,21 @@ //$argsString = '$args->module_srls = array(67, 65);'; $argsString = '$args->module_srls = "67, 65";'; $expected = 'SELECT [modules].[module_srl] as [module_srl], [sites].[domain] as [domain] FROM [xe_modules] as [modules] , [xe_sites] as [sites] WHERE [modules].[module_srl] in (?,?) and [sites].[site_srl] = [modules].[site_srl]'; - $this->_test($xml_file, $argsString, $expected, array("67", "65")); + $this->_test($xml_file, $argsString, $expected, array(array(67, 65))); } - - - // TODO Something fishy about this query - to be investigated - /* - function test_syndication_getGrantedModules(){ - $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml"; - $argsString = '$args->module_srl = 12; - $args->name = array(\'access\',\'view\',\'list\');'; - $expected = 'select "module_srl" - from "xe_module_grants" as "module_grants" - where "name" in (?) - and ("group_srl" >= -2 - or "group_srl" = -2 - or "group_srl" = -2) - group by "module_srl"'; - $this->_test($xml_file, $argsString, $expected); - } - */ + function test_syndication_getGrantedModule(){ + $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModule.xml"; + $argsString = '$args->module_srl = 67;'; + $expected = 'select count(*) as [count] + from [xe_module_grants] as [module_grants] + where [module_srl] = ? + and [name] in (?,?,?) + and ( + [group_srl] >= ? + or [group_srl] = ? + or [group_srl] = ? + )'; + $this->_test($xml_file, $argsString, $expected, array(67, array('\'access\'', '\'view\'', '\'list\''), 1, -1, -2)); + } } \ No newline at end of file From cfc7d32afdb8b014ff6119eaed3b735df04d5172 Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 26 Jul 2011 14:40:46 +0000 Subject: [PATCH 79/82] Update to query argument naming - so that queries that have the same variable name specified in the XML will not fail. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8658 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- .../xml/xmlquery/argument/Argument.class.php | 2 - .../argument/ConditionArgument.class.php | 5 - .../xmlquery/argument/SortArgument.class.php | 11 ++ .../queryargument/QueryArgument.class.php | 49 +++--- .../queryargument/SortQueryArgument.class.php | 20 +++ .../tags/condition/ConditionTag.class.php | 34 ++--- .../tags/navigation/IndexTag.class.php | 26 ++-- .../tags/navigation/LimitTag.class.php | 17 ++- .../queryargument/QueryArgumentTest.php | 24 +-- .../tags/condition/ConditionTagTest.php | 54 +++---- test-phpUnit/config/config.inc.php | 2 + test-phpUnit/db/DBTest.php | 5 + .../cubrid/CubridSelectOnlineTest.php | 8 +- .../db/xml_query/cubrid/CubridSelectTest.php | 140 +++++++++--------- .../db/xml_query/mssql/MssqlSelectTest.php | 1 - 15 files changed, 209 insertions(+), 189 deletions(-) create mode 100644 classes/xml/xmlquery/argument/SortArgument.class.php create mode 100644 classes/xml/xmlquery/queryargument/SortQueryArgument.class.php diff --git a/classes/xml/xmlquery/argument/Argument.class.php b/classes/xml/xmlquery/argument/Argument.class.php index 086e53ef2..3d7256eb8 100644 --- a/classes/xml/xmlquery/argument/Argument.class.php +++ b/classes/xml/xmlquery/argument/Argument.class.php @@ -95,8 +95,6 @@ $this->value = $default_value; } - - function checkFilter($filter_type){ if(isset($this->value) && $this->value != ''){ $val = $this->value; diff --git a/classes/xml/xmlquery/argument/ConditionArgument.class.php b/classes/xml/xmlquery/argument/ConditionArgument.class.php index da938c7e8..42c8f22d0 100644 --- a/classes/xml/xmlquery/argument/ConditionArgument.class.php +++ b/classes/xml/xmlquery/argument/ConditionArgument.class.php @@ -49,13 +49,8 @@ if($column_type === '') return; $this->type = $column_type; - - //if($column_type === '') $column_type = 'varchar'; - } - - } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/argument/SortArgument.class.php b/classes/xml/xmlquery/argument/SortArgument.class.php new file mode 100644 index 000000000..639b10a06 --- /dev/null +++ b/classes/xml/xmlquery/argument/SortArgument.class.php @@ -0,0 +1,11 @@ +getUnescapedValue(); + } + + } + +?> diff --git a/classes/xml/xmlquery/queryargument/QueryArgument.class.php b/classes/xml/xmlquery/queryargument/QueryArgument.class.php index 92f9bdfd5..2dc29878c 100644 --- a/classes/xml/xmlquery/queryargument/QueryArgument.class.php +++ b/classes/xml/xmlquery/queryargument/QueryArgument.class.php @@ -1,80 +1,87 @@ -argument_name = $tag->attrs->var; if(!$this->argument_name) $this->argument_name = $tag->attrs->name; if(!$this->argument_name) $this->argument_name = str_replace('.', '_',$tag->attrs->column); - + + $this->variable_name = $this->argument_name; + + self::$number_of_arguments++; + $this->argument_name .= self::$number_of_arguments; + $name = $tag->attrs->name; if(!$name) $name = $tag->attrs->column; if(strpos($name, '.') === false) $this->column_name = $name; else { list($prefix, $name) = explode('.', $name); $this->column_name = $name; - } - + } + if($tag->attrs->operation) $this->operation = $tag->attrs->operation; - + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/validator/QueryArgumentValidator.class.php'); $this->argument_validator = new QueryArgumentValidator($tag, $this); - + } - + function getArgumentName(){ return $this->argument_name; } - + function getColumnName(){ return $this->column_name; } - + function getValidatorString(){ return $this->argument_validator->toString(); } - + function isConditionArgument(){ if($this->operation) return true; return false; } - + function toString(){ if($this->isConditionArgument()) $arg = sprintf("\n$%s_argument = new ConditionArgument('%s', %s, '%s');\n" , $this->argument_name , $this->argument_name - , '$args->'.$this->argument_name + , '$args->'.$this->variable_name , $this->operation ); - + else $arg = sprintf("\n$%s_argument = new Argument('%s', %s);\n" , $this->argument_name , $this->argument_name - , '$args->'.$this->argument_name - , $this->ignoreValue ? 'null' : '$args->'.$this->argument_name); - - + , '$args->'.$this->variable_name); + + $arg .= $this->argument_validator->toString(); - + if($this->isConditionArgument()){ $arg .= sprintf("$%s_argument->createConditionValue();\n" , $this->argument_name ); } - + $arg .= sprintf("if(!$%s_argument->isValid()) return $%s_argument->getErrorMessage();\n" , $this->argument_name , $this->argument_name ); return $arg; } - + } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/queryargument/SortQueryArgument.class.php b/classes/xml/xmlquery/queryargument/SortQueryArgument.class.php new file mode 100644 index 000000000..60b068f2d --- /dev/null +++ b/classes/xml/xmlquery/queryargument/SortQueryArgument.class.php @@ -0,0 +1,20 @@ +argument_name + , $this->argument_name + , '$args->'.$this->variable_name); + + + $arg .= $this->argument_validator->toString(); + + $arg .= sprintf("if(!$%s_argument->isValid()) return $%s_argument->getErrorMessage();\n" + , $this->argument_name + , $this->argument_name + ); + return $arg; + } + } +?> diff --git a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php index 00c83d300..38cebf2cc 100644 --- a/classes/xml/xmlquery/tags/condition/ConditionTag.class.php +++ b/classes/xml/xmlquery/tags/condition/ConditionTag.class.php @@ -1,53 +1,53 @@ - tag inside an XML Query file. Base class. + * @brief Models the tag inside an XML Query file. Base class. * */ class ConditionTag { var $operation; var $column_name; - + var $pipe; var $argument_name; var $argument; var $default_column; - + var $query; function ConditionTag($condition){ $this->operation = $condition->attrs->operation; $this->pipe = $condition->attrs->pipe; $dbParser = XmlQueryParser::getDBParser(); $this->column_name = $dbParser->parseColumnName($condition->attrs->column); - + $isColumnName = strpos($condition->attrs->default, '.'); $isColumnName = $isColumnName || strpos($condition->attrs->var, '.'); - + if($condition->node_name == 'query'){ $this->query = new QueryTag($condition, true); $this->default_column = $this->query->toString(); } else if(($condition->attrs->var && !$isColumnName) || $isColumnName === false){ - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - - $this->argument = new QueryArgument($condition); - $this->argument_name = $this->argument->getArgumentName(); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + + $this->argument = new QueryArgument($condition); + $this->argument_name = $this->argument->getArgumentName(); } else { if($condition->attrs->default) - $this->default_column = "'" . $dbParser->parseColumnName($condition->attrs->default) . "'" ; + $this->default_column = "'" . $dbParser->parseColumnName($condition->attrs->default) . "'" ; else - $this->default_column = "'" . $dbParser->parseColumnName($condition->attrs->var) . "'" ; - } + $this->default_column = "'" . $dbParser->parseColumnName($condition->attrs->var) . "'" ; + } } - + function setPipe($pipe){ $this->pipe = $pipe; } - + function getArguments(){ $arguments = array(); if($this->query) @@ -56,7 +56,7 @@ $arguments[] = $this->argument; return $arguments; } - + function getConditionString(){ return sprintf("new Condition('%s',%s,%s%s)" , $this->column_name @@ -64,6 +64,6 @@ , '"'.$this->operation.'"' , $this->pipe ? ", '" . $this->pipe . "'" : '' ); - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index 04e545696..6e1dd553e 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -1,35 +1,35 @@ -argument_name = $index->attrs->var; - + // Sort index - column by which to sort //$dbParser = XmlQueryParser::getDBParser(); //$index->attrs->default = $dbParser->parseExpression($index->attrs->default); $this->default = $index->attrs->default; require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); - $this->argument = new QueryArgument($index); - + $this->argument = new QueryArgument($index); + // Sort order - asc / desc $this->sort_order = $index->attrs->order; if(!in_array($this->sort_order, array("asc", "desc"))){ - $arg->var = $this->sort_order; - $arg->default = '"asc"'; - $this->sort_order_argument = new QueryArgument($arg); - $this->sort_order = "\$args->".$this->sort_order; + $arg->attrs->var = $this->sort_order; + $arg->attrs->default = 'asc'; + $this->sort_order_argument = new SortQueryArgument($arg); + $this->sort_order = '$'.$this->sort_order_argument->getArgumentName().'_argument'; } else $this->sort_order = '"'.$this->sort_order.'"'; } - + function toString(){ - return sprintf("new OrderByColumn(\$%s_argument, %s)", $this->argument_name, $this->sort_order); + return sprintf("new OrderByColumn(\$%s_argument, %s)", $this->argument->getArgumentName(), $this->sort_order); } function getArguments(){ @@ -38,7 +38,7 @@ if($this->sort_order_argument) $arguments[] = $this->sort_order_argument; return $arguments; - } + } } ?> \ No newline at end of file diff --git a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php index d0a22447d..bb4492045 100644 --- a/classes/xml/xmlquery/tags/navigation/LimitTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/LimitTag.class.php @@ -1,6 +1,6 @@ -page->attrs && $index->page_count->attrs){ $this->page = $index->page->attrs; $this->page_count = $index->page_count->attrs; @@ -16,17 +16,18 @@ $this->arguments[] = new QueryArgument($index->page_count); } - $this->list_count = $index->list_count->attrs; - $this->arguments[] = new QueryArgument($index->list_count); + $this->list_count = new QueryArgument($index->list_count); + $this->arguments[] = $this->list_count; } function toString(){ - if ($this->page)return sprintf("new Limit(\$%s_argument, \$%s_argument, \$%s_argument)",$this->list_count->var, $this->page->var, $this->page_count->var); - else return sprintf("new Limit(\$%s_argument)", $this->list_count->var); + $name = $this->list_count->getArgumentName(); + if ($this->page)return sprintf("new Limit(\$%s_argument, \$%s_argument, \$%s_argument)",$name, $name, $name); + else return sprintf("new Limit(\$%s_argument)", $name); } function getArguments(){ return $this->arguments; - } + } } ?> \ No newline at end of file diff --git a/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php index b13e953db..5aed5baa4 100644 --- a/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php +++ b/test-phpUnit/classes/xml/xmlquery/queryargument/QueryArgumentTest.php @@ -6,30 +6,10 @@ class QueryArgumentTest extends CubridTest { var $xmlPath = "data/"; - + function QueryArgumentTest(){ $this->xmlPath = str_replace('QueryArgumentTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; } - - function testNotNullConditionArgument(){ - $xml_file = $this->xmlPath . "condition1.xml"; - $xml_obj = Helper::getXmlObject($xml_file); - $tag = new QueryArgument($xml_obj->condition); - - $this->assertEquals("member_srl", $tag->getArgumentName()); - $this->assertEquals("member_srl", $tag->getColumnName()); - $this->assertEquals(true, $tag->isConditionArgument()); - - $actual = Helper::cleanString($tag->toString()); - $expected = Helper::cleanString('$member_srl_argument = new ConditionArgument(\'member_srl\', $args->member_srl, \'equal\'); - $member_srl_argument->checkNotNull(); - $member_srl_argument->createConditionValue(); - if(!$member_srl_argument->isValid()) return $member_srl_argument->getErrorMessage();'); - $this->assertEquals($expected, $actual); - } - - - -} + } ?> diff --git a/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php b/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php index 245dbc37f..fe8d84f44 100644 --- a/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php +++ b/test-phpUnit/classes/xml/xmlquery/tags/condition/ConditionTagTest.php @@ -6,11 +6,11 @@ class ConditionTagTest extends CubridTest { var $xmlPath = "data/"; - + function ConditionTagTest(){ $this->xmlPath = str_replace('ConditionTagTest.php', '', str_replace('\\', '/', __FILE__)) . $this->xmlPath; } - + /** * Tests a simple tag: * @@ -19,15 +19,16 @@ class ConditionTagTest extends CubridTest { $xml_file = $this->xmlPath . "condition1.xml"; $xml_obj = Helper::getXmlObject($xml_file); $tag = new ConditionTag($xml_obj->condition); - - $expected = "new Condition('\"user_id\"',\$user_id_argument,\"equal\")"; - $actual = $tag->getConditionString(); - $this->assertEquals($expected, $actual); - $arguments = $tag->getArguments(); + + $expected = "new Condition('\"user_id\"',\$" . $arguments[0]->getArgumentName() . "_argument,\"equal\")"; + $actual = $tag->getConditionString(); + $this->assertEquals($expected, $actual); + + $this->assertEquals(1, count($arguments)); - } - + } + /** * Tests a condition tag for joins - that uses no argument * @@ -39,13 +40,13 @@ class ConditionTagTest extends CubridTest { $expected = "new Condition('\"comments\".\"user_id\"','\"member\".\"user_id\"',\"equal\")"; $actual = $tag->getConditionString(); - $this->assertEquals($expected, $actual); - + $this->assertEquals($expected, $actual); + $arguments = $tag->getArguments(); - $this->assertEquals(0, count($arguments)); - } - - + $this->assertEquals(0, count($arguments)); + } + + /** * Tests a tag with pipe: * @@ -54,15 +55,16 @@ class ConditionTagTest extends CubridTest { $xml_file = $this->xmlPath . "condition2.xml"; $xml_obj = Helper::getXmlObject($xml_file); $tag = new ConditionTag($xml_obj->condition); - - $expected = "new Condition('\"type\"',\$type_argument,\"equal\", 'and')"; - $actual = $tag->getConditionString(); - $this->assertEquals($expected, $actual); - $arguments = $tag->getArguments(); + + $expected = "new Condition('\"type\"',\$" . $arguments[0]->getArgumentName() . "_argument,\"equal\", 'and')"; + $actual = $tag->getConditionString(); + $this->assertEquals($expected, $actual); + + $this->assertEquals(1, count($arguments)); - } - + } + /** * Tests that even if the column name is given in the var attribute, it knows it's just a name and not an argument * @@ -74,11 +76,11 @@ class ConditionTagTest extends CubridTest { $expected = "new Condition('\"modules\".\"module_srl\"','\"documents\".\"module_srl\"',\"equal\", 'and')"; $actual = $tag->getConditionString(); - $this->assertEquals($expected, $actual); - + $this->assertEquals($expected, $actual); + $arguments = $tag->getArguments(); - $this->assertEquals(0, count($arguments)); - } + $this->assertEquals(0, count($arguments)); + } } diff --git a/test-phpUnit/config/config.inc.php b/test-phpUnit/config/config.inc.php index b1386b2f6..6fc807eed 100644 --- a/test-phpUnit/config/config.inc.php +++ b/test-phpUnit/config/config.inc.php @@ -29,6 +29,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/argument/SortArgument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/ConditionArgument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/DefaultValue.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); @@ -48,4 +49,5 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/tags/table/TableTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/tags/condition/ConditionTag.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/SortQueryArgument.class.php'); ?> \ No newline at end of file diff --git a/test-phpUnit/db/DBTest.php b/test-phpUnit/db/DBTest.php index 8fa514b39..59f5c4a3f 100644 --- a/test-phpUnit/db/DBTest.php +++ b/test-phpUnit/db/DBTest.php @@ -26,8 +26,13 @@ } function _testPreparedQuery($xml_file, $argsString, $expected, $methodName, $expectedArgs = NULL){ + echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + echo $xml_file; + echo PHP_EOL . ' ----------------------------------- ' .PHP_EOL; + $tester = new QueryTester(); $outputString = $tester->getNewParserOutputString($xml_file, $argsString); + echo $outputString; $output = eval($outputString); if(!is_a($output, 'Query')){ diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php index e0b787b1c..1cc4b5e09 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectOnlineTest.php @@ -7,7 +7,7 @@ $args->site_srl = 0; $output = executeQuery('module.getMidInfo', $args); $this->assertNotNull($output); - $this->assertNotNull($output->data, $output->message); + $this->assertNotNull($output->data, $output->message . PHP_EOL . $output->variables["_query"]); $this->assertEquals($output->data->module_srl, 111); } @@ -15,7 +15,7 @@ $args->site_srl = 0; $output = executeQuery('module.getSiteInfo', $args); $this->assertTrue(is_a($output, 'Object')); - $this->assertEquals(0, $output->error, $output->message); + $this->assertEquals(0, $output->error, $output->message . PHP_EOL . $output->variables["_query"]); } function test_document_getDocumentList_pagination(){ @@ -44,7 +44,7 @@ $args->member_srl = NULL; $output = executeQuery('document.getDocumentList', $args); - $this->assertTrue(is_int($output->page), $output->message); + $this->assertTrue(is_int($output->page), $output->message . PHP_EOL . $output->variables["_query"]); } function test_member_getMemberList(){ @@ -56,7 +56,7 @@ $args->page_count = 10; $output = executeQuery('member.getMemberList', $args); - $this->assertEquals(0, $output->error, $output->message); + $this->assertEquals(0, $output->error, $output->message . PHP_EOL . $output->variables["_query"]); } } ?> diff --git a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php index edaa484a2..b8fe617db 100644 --- a/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php +++ b/test-phpUnit/db/xml_query/cubrid/CubridSelectTest.php @@ -6,28 +6,28 @@ function _test($xml_file, $argsString, $expected, $columnList = null){ $this->_testQuery($xml_file, $argsString, $expected, 'getSelectSql', $columnList); } - + function testSelectStar(){ $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; $argsString = '$args->module_srl = 10;'; $expected = 'SELECT * FROM "xe_module_admins" as "module_admins" , "xe_member" as "member" WHERE "module_srl" = 10 and "member"."member_srl" = "module_admins"."member_srl"'; $this->_test($xml_file, $argsString, $expected); } - + function testRquiredParameter(){ $xml_file = _XE_PATH_ . "modules/module/queries/getAdminId.xml"; $argsString = ''; $expected = 'Date incorecte! Query-ul nu a putut fi executat.'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - + function testWithoutCategoriesTag(){ $xml_file = _XE_PATH_ . "modules/module/queries/getModuleCategories.xml"; $argsString = ''; $expected = 'SELECT * FROM "xe_module_categories" as "module_categories" ORDER BY "title" asc'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - + function test_module_getDefaultModules(){ $xml_file = _XE_PATH_ . "modules/module/queries/getDefaultModules.xml"; $argsString = ''; @@ -36,14 +36,14 @@ , "modules"."mid" , "modules"."browser_title" , "module_categories"."title" as "category" - , "modules"."module_srl" - FROM "xe_modules" as "modules" - left join "xe_module_categories" as "module_categories" - on "module_categories"."module_category_srl" = "modules"."module_category_srl" - WHERE "modules"."site_srl" = 0 + , "modules"."module_srl" + FROM "xe_modules" as "modules" + left join "xe_module_categories" as "module_categories" + on "module_categories"."module_category_srl" = "modules"."module_category_srl" + WHERE "modules"."site_srl" = 0 ORDER BY "modules"."module" asc, "module_categories"."title" asc, "modules"."mid" asc'; - $this->_test($xml_file, $argsString, $expected); - } + $this->_test($xml_file, $argsString, $expected); + } function test_module_getSiteInfo(){ $xml_file = _XE_PATH_ . "modules/module/queries/getSiteInfo.xml"; @@ -71,9 +71,9 @@ , "sites"."site_srl" as "site_srl" , "sites"."domain" as "domain" , "sites"."index_module_srl" as "index_module_srl" - , "sites"."default_language" as "default_language" - FROM "xe_sites" as "sites" - left join "xe_modules" as "modules" on "modules"."module_srl" = "sites"."index_module_srl" + , "sites"."default_language" as "default_language" + FROM "xe_sites" as "sites" + left join "xe_modules" as "modules" on "modules"."module_srl" = "sites"."index_module_srl" WHERE "sites"."site_srl" = 0 '; $this->_test($xml_file, $argsString, $expected); } @@ -81,78 +81,78 @@ function test_addon_getAddonInfo(){ $xml_file = _XE_PATH_ . "modules/addon/queries/getAddonInfo.xml"; $argsString = '$args->addon = "captcha";'; - $expected = 'SELECT * + $expected = 'SELECT * FROM "xe_addons" as "addons" WHERE "addon" = \'captcha\' '; $this->_test($xml_file, $argsString, $expected); } - + function test_addon_getAddons(){ $xml_file = _XE_PATH_ . "modules/addon/queries/getAddons.xml"; $argsString = ''; - $expected = 'SELECT * + $expected = 'SELECT * FROM "xe_addons" as "addons" ORDER BY "addon" asc'; $this->_test($xml_file, $argsString, $expected); - } - + } + function test_admin_getCommentCount(){ $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentCount.xml"; $argsString = ''; - $expected = 'SELECT count(*) as "count" + $expected = 'SELECT count(*) as "count" FROM "xe_comments" as "comments"'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } function test_admin_getCommentDeclaredStatus(){ $xml_file = _XE_PATH_ . "modules/admin/queries/getCommentDeclaredStatus.xml"; $argsString = '$args->date = "20110411";'; - $expected = 'SELECT substr("regdate",1,8) as "date", count(*) as "count" + $expected = 'SELECT substr("regdate",1,8) as "date", count(*) as "count" FROM "xe_comment_declared_log" as "comment_declared_log" - WHERE "regdate" >= \'20110411\' - GROUP BY substr("regdate",1,8) + WHERE "regdate" >= \'20110411\' + GROUP BY substr("regdate",1,8) ORDER BY substr("regdate",1,8) asc limit 2'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - + function test_member_getAutoLogin(){ $xml_file = _XE_PATH_ . "modules/member/queries/getAutoLogin.xml"; $argsString = '$args->autologin_key = 10;'; $expected = 'SELECT "member"."user_id" as "user_id" , "member"."password" as "password" - , "member_autologin"."autologin_key" as "autologin_key" - FROM "xe_member" as "member" , "xe_member_autologin" as "member_autologin" - WHERE "member_autologin"."autologin_key" = \'10\' + , "member_autologin"."autologin_key" as "autologin_key" + FROM "xe_member" as "member" , "xe_member_autologin" as "member_autologin" + WHERE "member_autologin"."autologin_key" = \'10\' and "member"."member_srl" = "member_autologin"."member_srl"'; $this->_test($xml_file, $argsString, $expected); } - + function test_opage_getOpageList(){ $xml_file = _XE_PATH_ . "modules/opage/queries/getOpageList.xml"; $argsString = '$args->s_title = "yuhuu"; $args->module = \'opage\';'; - $expected = 'SELECT * + $expected = 'SELECT * FROM "xe_modules" as "modules" - WHERE "module" = \'opage\' and ("browser_title" like \'%yuhuu%\') + WHERE "module" = \'opage\' and ("browser_title" like \'%yuhuu%\') ORDER BY "module_srl" desc LIMIT 0, 20'; - $this->_test($xml_file, $argsString, $expected); + $this->_test($xml_file, $argsString, $expected); } - + function test_syndication_getGrantedModules(){ $xml_file = _XE_PATH_ . "modules/syndication/queries/getGrantedModules.xml"; $argsString = '$args->module_srl = 12; $args->name = array(\'access\',\'view\',\'list\');'; - $expected = 'select "module_srl" - from "xe_module_grants" as "module_grants" - where "name" in (\'access\',\'view\',\'list\') - and ("group_srl" >= -2 - or "group_srl" = -2 - or "group_srl" = -2) + $expected = 'select "module_srl" + from "xe_module_grants" as "module_grants" + where "name" in (\'access\',\'view\',\'list\') + and ("group_srl" >= 1 + or "group_srl" = -1 + or "group_srl" = -2) group by "module_srl"'; - $this->_test($xml_file, $argsString, $expected); - } - + $this->_test($xml_file, $argsString, $expected); + } + function test_document_getDocumentList(){ $xml_file = _XE_PATH_ . "modules/document/queries/getDocumentList.xml"; $argsString = '$args->sort_index = \'list_order\'; @@ -161,16 +161,16 @@ $args->list_count = 30; $args->page_count = 10; $args->s_member_srl = 4;'; - $expected = 'select * - from "xe_documents" as "documents" + $expected = 'select * + from "xe_documents" as "documents" where "member_srl" = 4 - order by "list_order" asc + order by "list_order" asc limit 0, 30'; - $this->_test($xml_file, $argsString, $expected); - - + $this->_test($xml_file, $argsString, $expected); + + } - + /** * Test column list */ @@ -178,25 +178,25 @@ $xml_file = _XE_PATH_ . "modules/session/queries/getSession.xml"; $argsString = '$args->session_key = \'session_key\';'; $columnList = array('session_key', 'cur_mid', 'val'); - - $expected = 'select "session_key", "cur_mid", "val" - from "xe_session" as "session" + + $expected = 'select "session_key", "cur_mid", "val" + from "xe_session" as "session" where "session_key" = \'session_key\''; - - $this->_test($xml_file, $argsString, $expected, $columnList); + + $this->_test($xml_file, $argsString, $expected, $columnList); } - + function test_module_getModuleInfoByDocument(){ $xml_file = _XE_PATH_ . "modules/module/queries/getModuleInfoByDocument.xml"; $argsString = '$args->document_srl = 10;'; - $expected = 'SELECT "modules".* - FROM "xe_modules" as "modules" - , "xe_documents" as "documents" - WHERE "documents"."document_srl" = 10 + $expected = 'SELECT "modules".* + FROM "xe_modules" as "modules" + , "xe_documents" as "documents" + WHERE "documents"."document_srl" = 10 and "modules"."module_srl" = "documents"."module_srl"'; - $this->_test($xml_file, $argsString, $expected); - } - + $this->_test($xml_file, $argsString, $expected); + } + function test_member_getMemberList(){ $xml_file = _XE_PATH_ . "modules/member/queries/getMemberList.xml"; $argsString = '$args->is_admin = \'\'; @@ -205,10 +205,10 @@ $args->sort_order = \'asc\'; $args->list_count = 40; $args->page_count = 10;'; - $expected = 'select * from "xe_member" as "member" - order by "list_order" asc + $expected = 'select * from "xe_member" as "member" + order by "list_order" asc limit 0, 40'; - $this->_test($xml_file, $argsString, $expected); - } - + $this->_test($xml_file, $argsString, $expected); + } + } \ No newline at end of file diff --git a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php index 8d8e0f7d2..5c080b1d5 100644 --- a/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php +++ b/test-phpUnit/db/xml_query/mssql/MssqlSelectTest.php @@ -147,7 +147,6 @@ function test_module_getModuleSites(){ $xml_file = _XE_PATH_ . "modules/module/queries/getModuleSites.xml"; - //$argsString = '$args->module_srls = array(67, 65);'; $argsString = '$args->module_srls = "67, 65";'; $expected = 'SELECT [modules].[module_srl] as [module_srl], [sites].[domain] as [domain] FROM [xe_modules] as [modules] , [xe_sites] as [sites] WHERE [modules].[module_srl] in (?,?) and [sites].[site_srl] = [modules].[site_srl]'; $this->_test($xml_file, $argsString, $expected, array(array(67, 65))); From f47ea5deacf9dfc260445788659b4b8b9fa5a28a Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 26 Jul 2011 14:45:08 +0000 Subject: [PATCH 80/82] Included new argument class files. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8659 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 1 + classes/xml/xmlquery/tags/navigation/IndexTag.class.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 042cc8986..6db31fa3a 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -305,6 +305,7 @@ require_once(_XE_PATH_.'classes/xml/xmlquery/DBParser.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/Argument.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/argument/SortArgument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/argument/ConditionArgument.class.php'); require_once(_XE_PATH_.'classes/xml/XmlQueryParser.class.php'); require_once(_XE_PATH_.'classes/db/queryparts/expression/Expression.class.php'); diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index 6e1dd553e..c3698ad59 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -14,7 +14,7 @@ //$dbParser = XmlQueryParser::getDBParser(); //$index->attrs->default = $dbParser->parseExpression($index->attrs->default); $this->default = $index->attrs->default; - require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/SortQueryArgument.class.php'); $this->argument = new QueryArgument($index); // Sort order - asc / desc From 532d8bc21ef89aebc6a737748f283385853a1634 Mon Sep 17 00:00:00 2001 From: ucorina Date: Tue, 26 Jul 2011 16:33:30 +0000 Subject: [PATCH 81/82] Update to pagination properties - value was sent as Object instead of string. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8660 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DBMssql.class.php | 4 +++- classes/xml/xmlquery/tags/navigation/IndexTag.class.php | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index 1810247f3..19294ad33 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -502,6 +502,8 @@ function _executeSelectAct($queryObject) { $query = $this->getSelectSql($queryObject); + if(strpos($query, "substr")) $query = str_replace ("substr", "substring", $query); + // TODO Decide if we continue to pass parameters like this $this->param = $queryObject->getArguments(); @@ -553,7 +555,7 @@ $buff = new Object (); $buff->total_count = $total_count; $buff->total_page = $total_page; - $buff->page = $queryObject->getLimit()->page; + $buff->page = $queryObject->getLimit()->page->getValue(); $buff->data = $data; $buff->page_navigation = new PageHandler($total_count, $total_page, $queryObject->getLimit()->page, $queryObject->getLimit()->page_count); }else{ diff --git a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php index c3698ad59..8fa708576 100644 --- a/classes/xml/xmlquery/tags/navigation/IndexTag.class.php +++ b/classes/xml/xmlquery/tags/navigation/IndexTag.class.php @@ -14,6 +14,7 @@ //$dbParser = XmlQueryParser::getDBParser(); //$index->attrs->default = $dbParser->parseExpression($index->attrs->default); $this->default = $index->attrs->default; + require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/QueryArgument.class.php'); require_once(_XE_PATH_.'classes/xml/xmlquery/queryargument/SortQueryArgument.class.php'); $this->argument = new QueryArgument($index); From 76dc8252532677ed708a85d4c0e9f062049b10f3 Mon Sep 17 00:00:00 2001 From: ucorina Date: Wed, 27 Jul 2011 17:54:38 +0000 Subject: [PATCH 82/82] Added some changes that were skipped at the merge in DB.class.php. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0-DB@8676 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/db/DB.class.php | 56 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 6db31fa3a..bab12766c 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -17,6 +17,17 @@ var $count_cache_path = 'files/cache/db'; + var $cond_operation = array( ///< operations for condition + 'equal' => '=', + 'more' => '>=', + 'excess' => '>', + 'less' => '<=', + 'below' => '<', + 'notequal' => '<>', + 'notnull' => 'is not null', + 'null' => 'is null', + ); + var $fd = NULL; ///< connector resource or file description var $result = NULL; ///< result @@ -43,7 +54,8 @@ if(!$db_type) $db_type = Context::getDBType(); if(!$db_type && Context::isInstalled()) return new Object(-1, 'msg_db_not_setted'); - if(!$GLOBALS['__DB__']) { + if(!isset($GLOBALS['__DB__'])) $GLOBALS['__DB__'] = array(); + if(!isset($GLOBALS['__DB__'][$db_type])) { $class_name = 'DB'.ucfirst($db_type); $class_file = _XE_PATH_."classes/db/$class_name.class.php"; if(!file_exists($class_file)) return new Object(-1, 'msg_db_not_setted'); @@ -78,6 +90,48 @@ return $oDB->_getSupportedList(); } + /** + * @brief returns list of enable in supported db + * @return list of enable in supported db + **/ + function getEnableList() + { + if(!$this->supported_list) + { + $oDB = new DB(); + $this->supported_list = $oDB->_getSupportedList(); + } + + $enableList = array(); + if(is_array($this->supported_list)) + { + foreach($this->supported_list AS $key=>$value) + if($value->enable) array_push($enableList, $value); + } + return $enableList; + } + + /** + * @brief returns list of disable in supported db + * @return list of disable in supported db + **/ + function getDisableList() + { + if(!$this->supported_list) + { + $oDB = new DB(); + $this->supported_list = $oDB->_getSupportedList(); + } + + $disableList = array(); + if(is_array($this->supported_list)) + { + foreach($this->supported_list AS $key=>$value) + if(!$value->enable) array_push($disableList, $value); + } + return $disableList; + } + /** * @brief returns list of supported db * @return list of supported db