diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..0718bf4b --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,100 @@ +name: Test +permissions: + contents: write +on: + pull_request: + push: + branches: + - master + +jobs: + phpunit: + name: PHPUnit + runs-on: ubuntu-20.04 + services: + memcached: + image: memcached:1.6 + ports: + - 11211:11211 + options: --name memcached-container + mysql: + image: mysql:5.7 + env: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: test + MYSQL_USER: test + MYSQL_PASSWORD: test + ports: + - 3306:3306 + options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 + postgres: + image: postgres:13 + env: + POSTGRES_DB: test + POSTGRES_USER: test + POSTGRES_PASSWORD: test + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + strategy: + fail-fast: false + matrix: + php-version: + - 8.1 + - 8.2 + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + coverage: pcov + ini-values: zend.assertions=1, assert.exception=1 + php-version: ${{ matrix.php-version }} + extensions: memcached + tools: cs2pr + + - name: Check drivers + run: php drivers.php + + - name: Install dependencies with Composer + uses: ramsey/composer-install@v2 + + - name: Create and set permissions on SQLite Database + run: | + touch test.db + echo $USER:$USER + sudo chown $USER:$USER test.db + chmod 777 test.db + + # Verify SQLite installation and permissions + - name: Verify SQLite setup + run: | + sqlite3 --version + ls -la test.db + sqlite3 test.db "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT);" + ls -la test.db + + - name: Verify MySQL + run: | + echo "MySQL Connection String: mysql://test:test@localhost:3306/test" + + - name: Verify PostgreSQL + run: | + echo "PostgreSQL Connection String: postgres://test:test@localhost:5432/test" + + - name: Run PHPUnit + run: | + vendor/bin/phpunit -c phpunit.xml.dist + + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v3 + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.gitignore b/.gitignore index 8cb3948e..1fba46ea 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ *.log *.db *.swp +.phpunit.cache vendor/* output/* composer.lock @@ -13,3 +14,4 @@ phpunit.xml .php_cs docs/api .phpunit.result.cache +.stan-cache diff --git a/ActiveRecord.php b/ActiveRecord.php index 5d3cb917..422b3a06 100644 --- a/ActiveRecord.php +++ b/ActiveRecord.php @@ -17,6 +17,7 @@ require __DIR__ . '/lib/DateTime.php'; require __DIR__ . '/lib/Model.php'; require __DIR__ . '/lib/Table.php'; +require __DIR__ . '/lib/Relationship.php'; require __DIR__ . '/lib/ConnectionManager.php'; require __DIR__ . '/lib/Connection.php'; require __DIR__ . '/lib/Serialization.php'; diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2d1cb147..a314af95 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,36 @@ tests, pass the `--verbose` flag to PHPUnit: vendor/bin/phpunit --verbose ``` -Some common steps for fixing skipped tests are to: +For Docker users, a docker-compose.yml has been provided in the project root that will provide: +- mysql +- postgres +- memcached + +Simply run: +```shell +docker-composer up -d +``` + +Then, the necessary services will be available and the tests should pass (although you may need to install PHP memcache extensions in a separate step, see below ). + +When you're done, you can take it down with: +```sh +docker-compose down +``` + +#### Installing memcache on Windows +If you're a Windows user, finding the correct memcache drivers can be a bit tricky, as the PECL repo seems to be in disrepair. You can find them here: + +https://github.com/nono303/PHP-memcache-dll/tree/master + +Download the .dll that matches your version of PHP, install it into your /ext dir, and add this line to your php.ini: +```ini +extension=memcache +``` + + +#### Alternate setup +If Docker is not available to you, or you would simply not use it, you will have to do your best to install the various services on your own. * Install `memcached` and the PHP memcached extension (e.g., `brew install php56-memcache memcached` on macOS) * Install the PDO drivers for PostgreSQL (e.g., `brew install php56-pdo-pgsql` on macOS) diff --git a/README.md b/README.md index ab06465b..710cb0ee 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # PHP ActiveRecord - -[![Build Status](https://travis-ci.org/jpfuentes2/php-activerecord.png?branch=master)](https://travis-ci.org/php-activerecord/activerecord) +[![Test](https://github.com/php-activerecord/activerecord/actions/workflows/test.yml/badge.svg)](https://github.com/php-activerecord/activerecord/actions/workflows/test.yml) +[![Coverage Status](https://codecov.io/gh/shmax/graphql-php-validation-toolkit/branch/master/graph/badge.svg)](https://codecov.io/gh/shmax/graphql-php-validation-toolkit/branch/master) **We encourage pull requests, and issues will be dealt with thoroughly and in a timely manner.** diff --git a/composer.json b/composer.json index 3c01fdf4..9aa7c1ed 100644 --- a/composer.json +++ b/composer.json @@ -9,16 +9,16 @@ "php": ">=8.1.0" }, "require-dev": { - "phpunit/phpunit": "^9.5.21", - "pear/pear_exception": "1.0", + "phpunit/phpunit": "^10", "friendsofphp/php-cs-fixer": "^2.1", - "pear/log": "~1.13" + "monolog/monolog": "^3.4" }, "autoload": { "files": [ "ActiveRecord.php" ] }, "scripts": { "style-check" : "php vendor/bin/php-cs-fixer fix --dry-run --verbose --diff", - "style-fix" : "php vendor/bin/php-cs-fixer fix --verbose" + "style-fix" : "php vendor/bin/php-cs-fixer fix --verbose", + "test": "phpunit" } } diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..a79b43da --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,28 @@ +version: '3.8' +services: + mysql: + image: mysql:latest + environment: + MYSQL_ROOT_PASSWORD: root_password + MYSQL_DATABASE: test + MYSQL_USER: test + MYSQL_PASSWORD: test + ports: + - "3306:3306" + + postgres: + image: postgres:latest + environment: + POSTGRES_DB: test + POSTGRES_USER: test + POSTGRES_PASSWORD: test + ports: + - "5432:5432" + + memcached: + image: memcached:latest + ports: + - "11211:11211" + environment: + - MEMCACHED_MEMORY_LIMIT=64 + - MEMCACHED_MAX_CONNECTIONS=1024 diff --git a/drivers.php b/drivers.php new file mode 100644 index 00000000..8227a20d --- /dev/null +++ b/drivers.php @@ -0,0 +1,3 @@ +add($logger)->get($logger); diff --git a/lib/Connection.php b/lib/Connection.php index 3f742994..f98d6c83 100644 --- a/lib/Connection.php +++ b/lib/Connection.php @@ -49,7 +49,7 @@ abstract class Connection */ private $logging = false; /** - * Contains a Logger object that must impelement a log() method. + * Contains a Logger object that must implement a log() method. * * @var object */ @@ -71,7 +71,7 @@ abstract class Connection * * @var string */ - public static $datetime_format = 'Y-m-d H:i:s T'; + public static $datetime_format = 'Y-m-d H:i:s'; /** * Default PDO options to set for each connection. * @@ -98,7 +98,7 @@ abstract class Connection /** * Retrieve a database connection. * - * @param string $connection_string_or_connection_name A database connection string (ex. mysql://user:pass@host[:port]/dbname) + * @param string|null $connection_string_or_connection_name A database connection string (ex. mysql://user:pass@host[:port]/dbname) * Everything after the protocol:// part is specific to the connection adapter. * OR * A connection name that is set in ActiveRecord\Config @@ -108,11 +108,11 @@ abstract class Connection * * @see parse_connection_url */ - public static function instance($connection_string_or_connection_name=null) + public static function instance(string $connection_string_or_connection_name=null) { $config = Config::instance(); - if (false === strpos($connection_string_or_connection_name, '://')) { + if (!str_contains($connection_string_or_connection_name ?? '', '://')) { $connection_string = $connection_string_or_connection_name ? $config->get_connection($connection_string_or_connection_name) : $config->get_default_connection_string(); @@ -272,7 +272,8 @@ protected function __construct($info) $host = "unix_socket=$info->host"; } - $this->connection = new PDO("$info->protocol:$host;dbname=$info->db", $info->user, $info->pass, static::$PDO_OPTIONS); + $dsn = "$info->protocol:$host;dbname=$info->db"; + $this->connection = new PDO($dsn, $info->user, $info->pass, static::$PDO_OPTIONS); } catch (PDOException $e) { throw new DatabaseException($e); } @@ -333,9 +334,9 @@ public function insert_id($sequence=null) public function query($sql, &$values=[]) { if ($this->logging) { - $this->logger->log($sql); + $this->logger->info($sql); if ($values) { - $this->logger->log($values); + $this->logger->info(var_export($values, true)); } } @@ -352,11 +353,13 @@ public function query($sql, &$values=[]) $sth->setFetchMode(PDO::FETCH_ASSOC); try { + $msg = "couldn't execute query on " . get_class($this) . ". "; + $msg .= "user: " .getenv('USER'); if (!$sth->execute($values)) { - throw new DatabaseException($this); + throw new DatabaseException($msg); } } catch (PDOException $e) { - throw new DatabaseException($e); + throw new DatabaseException($msg . ": " . $e->getMessage()); } return $sth; diff --git a/lib/ConnectionManager.php b/lib/ConnectionManager.php index 7f561f38..622f224c 100644 --- a/lib/ConnectionManager.php +++ b/lib/ConnectionManager.php @@ -31,7 +31,7 @@ class ConnectionManager extends Singleton public static function get_connection($name=null) { $config = Config::instance(); - $name = $name ? $name : $config->get_default_connection(); + $name = $name ?? $config->get_default_connection(); if (!isset(self::$connections[$name]) || !self::$connections[$name]->connection) { self::$connections[$name] = Connection::instance($config->get_connection($name)); diff --git a/lib/Model.php b/lib/Model.php index 98a71f14..f43b6837 100644 --- a/lib/Model.php +++ b/lib/Model.php @@ -551,7 +551,6 @@ public function &read_attribute($name) // this may be first access to the relationship so check Table if (($relationship = $table->get_relationship($name))) { $this->__relationships[$name] = $relationship->load($this); - return $this->__relationships[$name]; } @@ -735,12 +734,14 @@ public static function table_name() */ private function is_delegated($name, &$delegate) { - if ('' != $delegate['prefix']) { - $name = substr($name, strlen($delegate['prefix'])+1); - } + if (is_array($delegate)) { + if ('' != $delegate['prefix']) { + $name = substr($name, strlen($delegate['prefix'])+1); + } - if (is_array($delegate) && in_array($name, $delegate['delegate'])) { - return $name; + if(in_array($name, $delegate['delegate'])) { + return $name; + } } return null; diff --git a/lib/Relationship.php b/lib/Relationship.php index 405f9bc6..63609de0 100644 --- a/lib/Relationship.php +++ b/lib/Relationship.php @@ -320,7 +320,7 @@ protected function set_class_name($class_name) protected function create_conditions_from_keys(Model $model, $condition_keys=[], $value_keys=[]) { - $condition_string = implode('_and_', $condition_keys); + $condition_string = implode('_and_', $condition_keys ?? []); $condition_values = array_values($model->get_values_for($value_keys)); // return null if all the foreign key values are null so that we don't try to do a query like "id is null" @@ -506,7 +506,7 @@ public function load(Model $model) $this->set_keys(get_class($model)); // since through relationships depend on other relationships we can't do - // this initiailization in the constructor since the other relationship + // this initialization in the constructor since the other relationship // may not have been created yet and we only want this to run once if (!isset($this->initialized)) { if ($this->through) { @@ -706,8 +706,6 @@ public function load(Model $model) */ class BelongsTo extends AbstractRelationship { - private $primary_key; - public function __construct($options=[]) { parent::__construct($options); diff --git a/lib/SQLBuilder.php b/lib/SQLBuilder.php index b7c6bb65..e7e35c5a 100644 --- a/lib/SQLBuilder.php +++ b/lib/SQLBuilder.php @@ -198,9 +198,9 @@ public function delete() /** * Reverses an order clause. */ - public static function reverse_order($order) + public static function reverse_order($order = '') { - if (!trim($order)) { + if (!trim($order ?? '')) { return $order; } diff --git a/lib/Table.php b/lib/Table.php index af8414a0..b70616b7 100644 --- a/lib/Table.php +++ b/lib/Table.php @@ -567,9 +567,7 @@ private function set_delegates() $delegates = $this->class->getStaticPropertyValue('delegate', []); $new = []; - if (!array_key_exists('processed', $delegates)) { - $delegates['processed'] = false; - } + $delegates['processed'] ??= false; if (!empty($delegates) && !$delegates['processed']) { foreach ($delegates as &$delegate) { diff --git a/lib/Utils.php b/lib/Utils.php index 9afdfa5a..2b0b60c6 100644 --- a/lib/Utils.php +++ b/lib/Utils.php @@ -234,7 +234,7 @@ public static function is_a($type, $var) public static function is_blank($var) { - return 0 === strlen($var); + return 0 === strlen($var ?? ''); } private static $plural = [ diff --git a/lib/Validations.php b/lib/Validations.php index ed3d0d84..d4f125a8 100644 --- a/lib/Validations.php +++ b/lib/Validations.php @@ -272,7 +272,7 @@ public function validates_inclusion_or_exclusion_of($type, $attrs) [$enum]; } - $message = str_replace('%s', $var, $options['message']); + $message = str_replace('%s', $var ?? '', $options['message']); if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options)) { continue; @@ -516,7 +516,7 @@ public function validates_length_of($attrs) $message = str_replace('%d', $option, $message); $attribute_value = $this->model->$attribute; - $len = strlen($attribute_value); + $len = strlen($attribute_value ?? ''); $value = (int) $attr[$range_option]; if ('maximum' == $range_option && $len > $value) { diff --git a/lib/adapters/OciAdapter.php b/lib/adapters/OciAdapter.php deleted file mode 100644 index ba9e938e..00000000 --- a/lib/adapters/OciAdapter.php +++ /dev/null @@ -1,153 +0,0 @@ -dsn_params = isset($info->charset) ? ";charset=$info->charset" : ''; - $this->connection = new PDO("oci:dbname=//$info->host/$info->db$this->dsn_params", $info->user, $info->pass, static::$PDO_OPTIONS); - } catch (PDOException $e) { - throw new DatabaseException($e); - } - } - - public function supports_sequences() - { - return true; - } - - public function get_next_sequence_value($sequence_name) - { - return $this->query_and_fetch_one('SELECT ' . $this->next_sequence_value($sequence_name) . ' FROM dual'); - } - - public function next_sequence_value($sequence_name) - { - return "$sequence_name.nextval"; - } - - public function date_to_string($datetime) - { - return $datetime->format('d-M-Y'); - } - - public function datetime_to_string($datetime) - { - return $datetime->format('d-M-Y h:i:s A'); - } - - // $string = DD-MON-YYYY HH12:MI:SS(\.[0-9]+) AM - public function string_to_datetime($string) - { - return parent::string_to_datetime(str_replace('.000000', '', $string)); - } - - public function limit($sql, $offset, $limit) - { - $offset = intval($offset); - $stop = $offset + intval($limit); - - return - "SELECT * FROM (SELECT a.*, rownum ar_rnum__ FROM ($sql) a " . - "WHERE rownum <= $stop) WHERE ar_rnum__ > $offset"; - } - - public function query_column_info($table) - { - $sql = - 'SELECT c.column_name, c.data_type, c.data_length, c.data_scale, c.data_default, c.nullable, ' . - '(SELECT a.constraint_type ' . - 'FROM all_constraints a, all_cons_columns b ' . - "WHERE a.constraint_type='P' " . - 'AND a.constraint_name=b.constraint_name ' . - 'AND a.table_name = t.table_name AND b.column_name=c.column_name) AS pk ' . - 'FROM user_tables t ' . - 'INNER JOIN user_tab_columns c on(t.table_name=c.table_name) ' . - 'WHERE t.table_name=?'; - - $values = [strtoupper($table)]; - - return $this->query($sql, $values); - } - - public function query_for_tables() - { - return $this->query('SELECT table_name FROM user_tables'); - } - - public function create_column(&$column) - { - $column['column_name'] = strtolower($column['column_name']); - $column['data_type'] = strtolower(preg_replace('/\(.*?\)/', '', $column['data_type'])); - - if (null !== $column['data_default']) { - $column['data_default'] = trim($column['data_default'], "' "); - } - - if ('number' == $column['data_type']) { - if ($column['data_scale'] > 0) { - $column['data_type'] = 'decimal'; - } elseif (0 == $column['data_scale']) { - $column['data_type'] = 'int'; - } - } - - $c = new Column(); - $c->inflected_name = Inflector::instance()->variablize($column['column_name']); - $c->name = $column['column_name']; - $c->nullable = 'Y' == $column['nullable'] ? true : false; - $c->pk = 'P' == $column['pk'] ? true : false; - $c->length = $column['data_length']; - - if ('timestamp' == $column['data_type']) { - $c->raw_type = 'datetime'; - } else { - $c->raw_type = $column['data_type']; - } - - $c->map_raw_type(); - $c->default = $c->cast($column['data_default'], $this); - - return $c; - } - - public function set_encoding($charset) - { - // is handled in the constructor - } - - public function native_database_types() - { - return [ - 'primary_key' => 'NUMBER(38) NOT NULL PRIMARY KEY', - 'string' => ['name' => 'VARCHAR2', 'length' => 255], - 'text' => ['name' => 'CLOB'], - 'integer' => ['name' => 'NUMBER', 'length' => 38], - 'float' => ['name' => 'NUMBER'], - 'datetime' => ['name' => 'DATE'], - 'timestamp' => ['name' => 'DATE'], - 'time' => ['name' => 'DATE'], - 'date' => ['name' => 'DATE'], - 'binary' => ['name' => 'BLOB'], - 'boolean' => ['name' => 'NUMBER', 'length' => 1] - ]; - } -} diff --git a/lib/adapters/PgsqlAdapter.php b/lib/adapters/PgsqlAdapter.php index 7e8a8cb8..66b25eb1 100644 --- a/lib/adapters/PgsqlAdapter.php +++ b/lib/adapters/PgsqlAdapter.php @@ -44,22 +44,29 @@ public function query_column_info($table) REPLACE(pg_catalog.format_type(a.atttypid, a.atttypmod), 'character varying', 'varchar') AS type, a.attnotnull AS not_nullable, (SELECT 't' - FROM pg_index - WHERE c.oid = pg_index.indrelid - AND a.attnum = ANY (pg_index.indkey) - AND pg_index.indisprimary = 't' - ) IS NOT NULL AS pk, - REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE((SELECT pg_attrdef.adsrc - FROM pg_attrdef - WHERE c.oid = pg_attrdef.adrelid - AND pg_attrdef.adnum=a.attnum - ),'::[a-z_ ]+',''),'''$',''),'^''','') AS default -FROM pg_attribute a, pg_class c, pg_type t + FROM pg_index + WHERE c.oid = pg_index.indrelid + AND a.attnum = ANY (pg_index.indkey) + AND pg_index.indisprimary = 't' + ) IS NOT NULL AS pk, + REGEXP_REPLACE( + REGEXP_REPLACE( + REGEXP_REPLACE( + pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid), + '::[a-z_ ]+', '' + ), + '''$','' + ), + '^''','' + ) AS "default" +FROM pg_attribute a +JOIN pg_class c ON a.attrelid = c.oid +JOIN pg_type t ON a.atttypid = t.oid +LEFT JOIN pg_attrdef ON c.oid = pg_attrdef.adrelid AND a.attnum = pg_attrdef.adnum WHERE c.relname = ? AND a.attnum > 0 - AND a.attrelid = c.oid - AND a.atttypid = t.oid -ORDER BY a.attnum +ORDER BY a.attnum; + SQL; $values = [$table]; diff --git a/lib/cache/Memcache.php b/lib/cache/Memcache.php index 4a6f7ac7..e00674ee 100644 --- a/lib/cache/Memcache.php +++ b/lib/cache/Memcache.php @@ -23,7 +23,7 @@ class Memcache public function __construct($options) { $this->memcache = new \Memcache(); - $options['port'] = isset($options['port']) ? $options['port'] : self::DEFAULT_PORT; + $options['port'] = $options['port'] ?? self::DEFAULT_PORT; if (!@$this->memcache->connect($options['host'], $options['port'])) { if ($error = error_get_last()) { @@ -47,7 +47,7 @@ public function read($key) public function write($key, $value, $expire) { - $this->memcache->set($key, $value, null, $expire); + $this->memcache->set($key, $value, 0, $expire); } public function delete($key) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 41e4ea6a..b2e75b9a 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,18 +1,26 @@ - - + + + + ./lib + + - ./test/ + ./test/ diff --git a/test/ActiveRecordCacheTest.php b/test/ActiveRecordCacheTest.php index f412b14f..b92563b0 100644 --- a/test/ActiveRecordCacheTest.php +++ b/test/ActiveRecordCacheTest.php @@ -2,9 +2,9 @@ use ActiveRecord\Cache; -class ActiveRecordCacheTest extends DatabaseTest +class ActiveRecordCacheTest extends DatabaseTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { if (!extension_loaded('memcache')) { $this->markTestSkipped('The memcache extension is not available'); @@ -12,11 +12,11 @@ public function set_up($connection_name=null) return; } - parent::set_up($connection_name); + parent::setUp($connection_name); ActiveRecord\Config::instance()->set_cache('memcache://localhost'); } - public function tear_down() + public function tearDown(): void { Cache::flush(); Cache::initialize(null); @@ -24,21 +24,21 @@ public function tear_down() public function test_default_expire() { - $this->assert_equals(30, Cache::$options['expire']); + $this->assertEquals(30, Cache::$options['expire']); } public function test_explicit_default_expire() { ActiveRecord\Config::instance()->set_cache('memcache://localhost', ['expire' => 1]); - $this->assert_equals(1, Cache::$options['expire']); + $this->assertEquals(1, Cache::$options['expire']); } public function test_caches_column_meta_data() { Author::first(); - $table_name = Author::table()->get_fully_qualified_table_name(!($this->conn instanceof ActiveRecord\PgsqlAdapter)); + $table_name = Author::table()->get_fully_qualified_table_name(!($this->connection instanceof ActiveRecord\PgsqlAdapter)); $value = Cache::$adapter->read("get_meta_data-$table_name"); - $this->assert_true(is_array($value)); + $this->assertTrue(is_array($value)); } } diff --git a/test/ActiveRecordFindTest.php b/test/ActiveRecordFindTest.php index abb72018..a0cda892 100644 --- a/test/ActiveRecordFindTest.php +++ b/test/ActiveRecordFindTest.php @@ -1,26 +1,22 @@ expectException(\ActiveRecord\RecordNotFound::class); Author::find(); } public function test_find_by_pk() { $author = Author::find(3); - $this->assert_equals(3, $author->id); + $this->assertEquals(3, $author->id); } - /** - * @expectedException \ActiveRecord\RecordNotFound - */ public function test_find_by_pkno_results() { + $this->expectException(\ActiveRecord\RecordNotFound::class); Author::find(99999999); } @@ -30,57 +26,53 @@ public function test_find_by_multiple_pk_with_partial_match() Author::find(1, 999999999); $this->fail(); } catch (ActiveRecord\RecordNotFound $e) { - $this->assert_true(false !== strpos($e->getMessage(), 'found 1, but was looking for 2')); + $this->assertTrue(false !== strpos($e->getMessage(), 'found 1, but was looking for 2')); } } public function test_find_by_pk_with_options() { $author = Author::find(3, ['order' => 'name']); - $this->assert_equals(3, $author->id); - $this->assert_true(false !== strpos(Author::table()->last_sql, 'ORDER BY name')); + $this->assertEquals(3, $author->id); + $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name')); } public function test_find_by_pk_array() { $authors = Author::find(1, '2'); - $this->assert_equals(2, count($authors)); - $this->assert_equals(1, $authors[0]->id); - $this->assert_equals(2, $authors[1]->id); + $this->assertEquals(2, count($authors)); + $this->assertEquals(1, $authors[0]->id); + $this->assertEquals(2, $authors[1]->id); } public function test_find_by_pk_array_with_options() { $authors = Author::find(1, '2', ['order' => 'name']); - $this->assert_equals(2, count($authors)); - $this->assert_true(false !== strpos(Author::table()->last_sql, 'ORDER BY name')); + $this->assertEquals(2, count($authors)); + $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name')); } - /** - * @expectedException \ActiveRecord\RecordNotFound - */ public function test_find_nothing_with_sql_in_string() { + $this->expectException(\ActiveRecord\RecordNotFound::class); Author::first('name = 123123123'); } public function test_find_all() { $authors = Author::find('all', ['conditions' => ['author_id IN(?)', [1, 2, 3]]]); - $this->assert_true(count($authors) >= 3); + $this->assertTrue(count($authors) >= 3); } public function test_find_all_with_no_bind_values() { $authors = Author::find('all', ['conditions' => ['author_id IN(1,2,3)']]); - $this->assert_equals(1, $authors[0]->author_id); + $this->assertEquals(1, $authors[0]->author_id); } - /** - * @expectedException \ActiveRecord\DatabaseException - */ public function test_find_all_with_empty_array_bind_value_throws_exception() { + $this->expectException(\ActiveRecord\DatabaseException::class); $authors = Author::find('all', ['conditions' => ['author_id IN(?)', []]]); $this->assertCount(0, $authors); } @@ -88,112 +80,112 @@ public function test_find_all_with_empty_array_bind_value_throws_exception() public function test_find_hash_using_alias() { $venues = Venue::all(['conditions' => ['marquee' => 'Warner Theatre', 'city' => ['Washington', 'New York']]]); - $this->assert_true(count($venues) >= 1); + $this->assertTrue(count($venues) >= 1); } public function test_find_hash_using_alias_with_null() { $venues = Venue::all(['conditions' => ['marquee' => null]]); - $this->assert_equals(0, count($venues)); + $this->assertEquals(0, count($venues)); } public function test_dynamic_finder_using_alias() { - $this->assert_not_null(Venue::find_by_marquee('Warner Theatre')); + $this->assertNotNull(Venue::find_by_marquee('Warner Theatre')); } public function test_find_all_hash() { $books = Book::find('all', ['conditions' => ['author_id' => 1]]); - $this->assert_true(count($books) > 0); + $this->assertTrue(count($books) > 0); } public function test_find_all_hash_with_order() { $books = Book::find('all', ['conditions' => ['author_id' => 1], 'order' => 'name DESC']); - $this->assert_true(count($books) > 0); + $this->assertTrue(count($books) > 0); } public function test_find_all_no_args() { $author = Author::all(); - $this->assert_true(count($author) > 1); + $this->assertTrue(count($author) > 1); } public function test_find_all_no_results() { $authors = Author::find('all', ['conditions' => ['author_id IN(11111111111,22222222222,333333333333)']]); - $this->assert_equals([], $authors); + $this->assertEquals([], $authors); } public function test_find_first() { $author = Author::find('first', ['conditions' => ['author_id IN(?)', [1, 2, 3]]]); - $this->assert_equals(1, $author->author_id); - $this->assert_equals('Tito', $author->name); + $this->assertEquals(1, $author->author_id); + $this->assertEquals('Tito', $author->name); } public function test_find_first_no_results() { - $this->assert_null(Author::find('first', ['conditions' => 'author_id=1111111'])); + $this->assertNull(Author::find('first', ['conditions' => 'author_id=1111111'])); } public function test_find_first_using_pk() { $author = Author::find('first', 3); - $this->assert_equals(3, $author->author_id); + $this->assertEquals(3, $author->author_id); } public function test_find_first_with_conditions_as_string() { $author = Author::find('first', ['conditions' => 'author_id=3']); - $this->assert_equals(3, $author->author_id); + $this->assertEquals(3, $author->author_id); } public function test_find_all_with_conditions_as_string() { $author = Author::find('all', ['conditions' => 'author_id in(2,3)']); - $this->assert_equals(2, count($author)); + $this->assertEquals(2, count($author)); } public function test_find_by_sql() { $author = Author::find_by_sql('SELECT * FROM authors WHERE author_id in(1,2)'); - $this->assert_equals(1, $author[0]->author_id); - $this->assert_equals(2, count($author)); + $this->assertEquals(1, $author[0]->author_id); + $this->assertEquals(2, count($author)); } public function test_find_by_sqltakes_values_array() { $author = Author::find_by_sql('SELECT * FROM authors WHERE author_id=?', [1]); - $this->assert_not_null($author); + $this->assertNotNull($author); } public function test_find_with_conditions() { $author = Author::find('first', ['conditions' => ['author_id=? and name=?', 1, 'Tito']]); - $this->assert_equals(1, $author->author_id); + $this->assertEquals(1, $author->author_id); } public function test_find_last() { $author = Author::last(); - $this->assert_equals(4, $author->author_id); - $this->assert_equals('Uncle Bob', $author->name); + $this->assertEquals(4, $author->author_id); + $this->assertEquals('Uncle Bob', $author->name); } public function test_find_last_using_string_condition() { $author = Author::find('last', ['conditions' => 'author_id IN(1,2,3,4)']); - $this->assert_equals(4, $author->author_id); - $this->assert_equals('Uncle Bob', $author->name); + $this->assertEquals(4, $author->author_id); + $this->assertEquals('Uncle Bob', $author->name); } public function test_limit_before_order() { $authors = Author::all(['limit' => 2, 'order' => 'author_id desc', 'conditions' => 'author_id in(1,2)']); - $this->assert_equals(2, $authors[0]->author_id); - $this->assert_equals(1, $authors[1]->author_id); + $this->assertEquals(2, $authors[0]->author_id); + $this->assertEquals(1, $authors[1]->author_id); } public function test_for_each() @@ -202,10 +194,10 @@ public function test_for_each() $res = Author::all(); foreach ($res as $author) { - $this->assert_true($author instanceof ActiveRecord\Model); + $this->assertTrue($author instanceof ActiveRecord\Model); ++$i; } - $this->assert_true($i > 0); + $this->assertTrue($i > 0); } public function test_fetch_all() @@ -213,121 +205,113 @@ public function test_fetch_all() $i = 0; foreach (Author::all() as $author) { - $this->assert_true($author instanceof ActiveRecord\Model); + $this->assertTrue($author instanceof ActiveRecord\Model); ++$i; } - $this->assert_true($i > 0); + $this->assertTrue($i > 0); } public function test_count() { - $this->assert_equals(1, Author::count(1)); - $this->assert_equals(2, Author::count([1, 2])); - $this->assert_true(Author::count() > 1); - $this->assert_equals(0, Author::count(['conditions' => 'author_id=99999999999999'])); - $this->assert_equals(2, Author::count(['conditions' => 'author_id=1 or author_id=2'])); - $this->assert_equals(1, Author::count(['name' => 'Tito', 'author_id' => 1])); + $this->assertEquals(1, Author::count(1)); + $this->assertEquals(2, Author::count([1, 2])); + $this->assertTrue(Author::count() > 1); + $this->assertEquals(0, Author::count(['conditions' => 'author_id=99999999999999'])); + $this->assertEquals(2, Author::count(['conditions' => 'author_id=1 or author_id=2'])); + $this->assertEquals(1, Author::count(['name' => 'Tito', 'author_id' => 1])); } public function test_gh149_empty_count() { $total = Author::count(); - $this->assert_equals($total, Author::count(null)); - $this->assert_equals($total, Author::count([])); + $this->assertEquals($total, Author::count(null)); + $this->assertEquals($total, Author::count([])); } public function test_exists() { - $this->assert_true(Author::exists(1)); - $this->assert_true(Author::exists(['conditions' => 'author_id=1'])); - $this->assert_true(Author::exists(['conditions' => ['author_id=? and name=?', 1, 'Tito']])); - $this->assert_false(Author::exists(9999999)); - $this->assert_false(Author::exists(['conditions' => 'author_id=999999'])); + $this->assertTrue(Author::exists(1)); + $this->assertTrue(Author::exists(['conditions' => 'author_id=1'])); + $this->assertTrue(Author::exists(['conditions' => ['author_id=? and name=?', 1, 'Tito']])); + $this->assertFalse(Author::exists(9999999)); + $this->assertFalse(Author::exists(['conditions' => 'author_id=999999'])); } public function test_find_by_call_static() { - $this->assert_equals('Tito', Author::find_by_name('Tito')->name); - $this->assert_equals('Tito', Author::find_by_author_id_and_name(1, 'Tito')->name); - $this->assert_equals('George W. Bush', Author::find_by_author_id_or_name(2, 'Tito', ['order' => 'author_id desc'])->name); - $this->assert_equals('Tito', Author::find_by_name(['Tito', 'George W. Bush'], ['order' => 'name desc'])->name); + $this->assertEquals('Tito', Author::find_by_name('Tito')->name); + $this->assertEquals('Tito', Author::find_by_author_id_and_name(1, 'Tito')->name); + $this->assertEquals('George W. Bush', Author::find_by_author_id_or_name(2, 'Tito', ['order' => 'author_id desc'])->name); + $this->assertEquals('Tito', Author::find_by_name(['Tito', 'George W. Bush'], ['order' => 'name desc'])->name); } public function test_find_by_call_static_no_results() { - $this->assert_null(Author::find_by_name('SHARKS WIT LASERZ')); - $this->assert_null(Author::find_by_name_or_author_id()); + $this->assertNull(Author::find_by_name('SHARKS WIT LASERZ')); + $this->assertNull(Author::find_by_name_or_author_id()); } - /** - * @expectedException \ActiveRecord\DatabaseException - */ public function test_find_by_call_static_invalid_column_name() { + $this->expectException(\ActiveRecord\DatabaseException::class); Author::find_by_sharks(); } public function test_find_all_by_call_static() { $x = Author::find_all_by_name('Tito'); - $this->assert_equals('Tito', $x[0]->name); - $this->assert_equals(1, count($x)); + $this->assertEquals('Tito', $x[0]->name); + $this->assertEquals(1, count($x)); $x = Author::find_all_by_author_id_or_name(2, 'Tito', ['order' => 'name asc']); - $this->assert_equals(2, count($x)); - $this->assert_equals('George W. Bush', $x[0]->name); + $this->assertEquals(2, count($x)); + $this->assertEquals('George W. Bush', $x[0]->name); } public function test_find_all_by_call_static_no_results() { $x = Author::find_all_by_name('SHARKSSSSSSS'); - $this->assert_equals(0, count($x)); + $this->assertEquals(0, count($x)); } public function test_find_all_by_call_static_with_array_values_and_options() { $author = Author::find_all_by_name(['Tito', 'Bill Clinton'], ['order' => 'name desc']); - $this->assert_equals('Tito', $author[0]->name); - $this->assert_equals('Bill Clinton', $author[1]->name); + $this->assertEquals('Tito', $author[0]->name); + $this->assertEquals('Bill Clinton', $author[1]->name); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_find_all_by_call_static_undefined_method() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); Author::find_sharks('Tito'); } public function test_find_all_takes_limit_options() { $authors = Author::all(['limit' => 1, 'offset' => 2, 'order' => 'name desc']); - $this->assert_equals('George W. Bush', $authors[0]->name); + $this->assertEquals('George W. Bush', $authors[0]->name); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_find_by_call_static_with_invalid_field_name() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); Author::find_by_some_invalid_field_name('Tito'); } public function test_find_with_select() { $author = Author::first(['select' => 'name, 123 as bubba', 'order' => 'name desc']); - $this->assert_equals('Uncle Bob', $author->name); - $this->assert_equals(123, $author->bubba); + $this->assertEquals('Uncle Bob', $author->name); + $this->assertEquals(123, $author->bubba); } public function test_find_with_select_non_selected_fields_should_not_have_attributes() { + $this->expectException(\ActiveRecord\UndefinedPropertyException::class); $author = Author::first(['select' => 'name, 123 as bubba']); - try { - $author->id; - $this->fail('expected ActiveRecord\UndefinedPropertyExecption'); - } catch (ActiveRecord\UndefinedPropertyException $e) { - } + $author->id; + $this->fail('expected ActiveRecord\UndefinedPropertyExecption'); } public function test_joins_on_model_with_association_and_explicit_joins() @@ -347,108 +331,92 @@ public function test_joins_on_model_with_explicit_joins() public function test_group() { $venues = Venue::all(['select' => 'state', 'group' => 'state']); - $this->assert_true(count($venues) > 0); + $this->assertTrue(count($venues) > 0); $this->assert_sql_has('GROUP BY state', ActiveRecord\Table::load('Venue')->last_sql); } public function test_group_with_order_and_limit_and_having() { $venues = Venue::all(['select' => 'state', 'group' => 'state', 'having' => 'length(state) = 2', 'order' => 'state', 'limit' => 2]); - $this->assert_true(count($venues) > 0); - $this->assert_sql_has($this->conn->limit('SELECT state FROM venues GROUP BY state HAVING length(state) = 2 ORDER BY state', null, 2), Venue::table()->last_sql); + $this->assertTrue(count($venues) > 0); + $this->assert_sql_has($this->connection->limit('SELECT state FROM venues GROUP BY state HAVING length(state) = 2 ORDER BY state', null, 2), Venue::table()->last_sql); } public function test_escape_quotes() { $author = Author::find_by_name("Tito's"); - $this->assert_not_equals("Tito's", Author::table()->last_sql); + $this->assertNotEquals("Tito's", Author::table()->last_sql); } public function test_from() { $author = Author::find('first', ['from' => 'books', 'order' => 'author_id asc']); - $this->assert_true($author instanceof Author); - $this->assert_not_null($author->book_id); + $this->assertTrue($author instanceof Author); + $this->assertNotNull($author->book_id); $author = Author::find('first', ['from' => 'authors', 'order' => 'author_id asc']); - $this->assert_true($author instanceof Author); - $this->assert_equals(1, $author->id); + $this->assertTrue($author instanceof Author); + $this->assertEquals(1, $author->id); } public function test_having() { - if ($this->conn instanceof ActiveRecord\OciAdapter) { - $author = Author::first([ - 'select' => 'to_char(created_at,\'YYYY-MM-DD\') as created_at', - 'group' => 'to_char(created_at,\'YYYY-MM-DD\')', - 'having' => "to_char(created_at,'YYYY-MM-DD') > '2009-01-01'"]); - $this->assert_sql_has("GROUP BY to_char(created_at,'YYYY-MM-DD') HAVING to_char(created_at,'YYYY-MM-DD') > '2009-01-01'", Author::table()->last_sql); - } else { - $author = Author::first([ - 'select' => 'date(created_at) as created_at', - 'group' => 'date(created_at)', - 'having' => "date(created_at) > '2009-01-01'"]); - $this->assert_sql_has("GROUP BY date(created_at) HAVING date(created_at) > '2009-01-01'", Author::table()->last_sql); - } + Author::first([ + 'select' => 'date(created_at) as created_at', + 'group' => 'date(created_at)', + 'having' => "date(created_at) > '2009-01-01'"]); + $this->assert_sql_has("GROUP BY date(created_at) HAVING date(created_at) > '2009-01-01'", Author::table()->last_sql); } - /** - * @expectedException \ActiveRecord\DatabaseException - */ public function test_from_with_invalid_table() { - $author = Author::find('first', ['from' => 'wrong_authors_table']); + $this->expectException(\ActiveRecord\DatabaseException::class); + Author::find('first', ['from' => 'wrong_authors_table']); } public function test_find_with_hash() { - $this->assert_not_null(Author::find(['name' => 'Tito'])); - $this->assert_not_null(Author::find('first', ['name' => 'Tito'])); - $this->assert_equals(1, count(Author::find('all', ['name' => 'Tito']))); - $this->assert_equals(1, count(Author::all(['name' => 'Tito']))); + $this->assertNotNull(Author::find(['name' => 'Tito'])); + $this->assertNotNull(Author::find('first', ['name' => 'Tito'])); + $this->assertEquals(1, count(Author::find('all', ['name' => 'Tito']))); + $this->assertEquals(1, count(Author::all(['name' => 'Tito']))); } public function test_find_or_create_by_on_existing_record() { - $this->assert_not_null(Author::find_or_create_by_name('Tito')); + $this->assertNotNull(Author::find_or_create_by_name('Tito')); } public function test_find_or_create_by_creates_new_record() { $author = Author::find_or_create_by_name_and_encrypted_password('New Guy', 'pencil'); - $this->assert_true($author->author_id > 0); - $this->assert_equals('pencil', $author->encrypted_password); + $this->assertTrue($author->author_id > 0); + $this->assertEquals('pencil', $author->encrypted_password); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_find_or_create_by_throws_exception_when_using_or() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); Author::find_or_create_by_name_or_encrypted_password('New Guy', 'pencil'); } - /** - * @expectedException \ActiveRecord\RecordNotFound - */ public function test_find_by_zero() { + $this->expectException(\ActiveRecord\RecordNotFound::class); Author::find(0); } - /** - * @expectedException \ActiveRecord\RecordNotFound - */ public function test_find_by_null() { + $this->expectException(\ActiveRecord\RecordNotFound::class); Author::find(null); } public function test_count_by() { - $this->assert_equals(2, Venue::count_by_state('VA')); - $this->assert_equals(3, Venue::count_by_state_or_name('VA', 'Warner Theatre')); - $this->assert_equals(0, Venue::count_by_state_and_name('VA', 'zzzzzzzzzzzzz')); + $this->assertEquals(2, Venue::count_by_state('VA')); + $this->assertEquals(3, Venue::count_by_state_or_name('VA', 'Warner Theatre')); + $this->assertEquals(0, Venue::count_by_state_and_name('VA', 'zzzzzzzzzzzzz')); } public function test_find_by_pk_should_not_use_limit() @@ -464,7 +432,7 @@ public function test_find_by_datetime() $arnow->setTimestamp($now->getTimestamp()); Author::find(1)->update_attribute('created_at', $now); - $this->assert_not_null(Author::find_by_created_at($now)); - $this->assert_not_null(Author::find_by_created_at($arnow)); + $this->assertNotNull(Author::find_by_created_at($now)); + $this->assertNotNull(Author::find_by_created_at($arnow)); } } diff --git a/test/ActiveRecordTest.php b/test/ActiveRecordTest.php index 8c77e17e..14630bb4 100644 --- a/test/ActiveRecordTest.php +++ b/test/ActiveRecordTest.php @@ -1,73 +1,69 @@ options = ['conditions' => 'blah', 'order' => 'blah']; } public function test_options_is_not() { - $this->assert_false(Author::is_options_hash(null)); - $this->assert_false(Author::is_options_hash('')); - $this->assert_false(Author::is_options_hash('tito')); - $this->assert_false(Author::is_options_hash([])); - $this->assert_false(Author::is_options_hash([1, 2, 3])); + $this->assertFalse(Author::is_options_hash(null)); + $this->assertFalse(Author::is_options_hash('')); + $this->assertFalse(Author::is_options_hash('tito')); + $this->assertFalse(Author::is_options_hash([])); + $this->assertFalse(Author::is_options_hash([1, 2, 3])); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_options_hash_with_unknown_keys() { - $this->assert_false(Author::is_options_hash(['conditions' => 'blah', 'sharks' => 'laserz', 'dubya' => 'bush'])); + $this->expectException(\ActiveRecord\ActiveRecordException::class); + $this->assertFalse(Author::is_options_hash(['conditions' => 'blah', 'sharks' => 'laserz', 'dubya' => 'bush'])); } public function test_options_is_hash() { - $this->assert_true(Author::is_options_hash($this->options)); + $this->assertTrue(Author::is_options_hash($this->options)); } public function test_extract_and_validate_options() { $args = ['first', $this->options]; - $this->assert_equals($this->options, Author::extract_and_validate_options($args)); - $this->assert_equals(['first'], $args); + $this->assertEquals($this->options, Author::extract_and_validate_options($args)); + $this->assertEquals(['first'], $args); } public function test_extract_and_validate_options_with_array_in_args() { $args = ['first', [1, 2], $this->options]; - $this->assert_equals($this->options, Author::extract_and_validate_options($args)); + $this->assertEquals($this->options, Author::extract_and_validate_options($args)); } public function test_extract_and_validate_options_removes_options_hash() { $args = ['first', $this->options]; Author::extract_and_validate_options($args); - $this->assert_equals(['first'], $args); + $this->assertEquals(['first'], $args); } public function test_extract_and_validate_options_nope() { $args = ['first']; - $this->assert_equals([], Author::extract_and_validate_options($args)); - $this->assert_equals(['first'], $args); + $this->assertEquals([], Author::extract_and_validate_options($args)); + $this->assertEquals(['first'], $args); } public function test_extract_and_validate_options_nope_because_wasnt_at_end() { $args = ['first', $this->options, [1, 2]]; - $this->assert_equals([], Author::extract_and_validate_options($args)); + $this->assertEquals([], Author::extract_and_validate_options($args)); } - /** - * @expectedException \ActiveRecord\UndefinedPropertyException - */ public function test_invalid_attribute() { + $this->expectException(\ActiveRecord\UndefinedPropertyException::class); $author = Author::find('first', ['conditions' => 'author_id=1']); $author->some_invalid_field_name; } @@ -81,8 +77,8 @@ public function test_invalid_attributes() $exceptions = explode("\r\n", $e->getMessage()); } - $this->assert_equals(1, substr_count($exceptions[0], 'invalid_attribute')); - $this->assert_equals(1, substr_count($exceptions[1], 'another_invalid_attribute')); + $this->assertEquals(1, substr_count($exceptions[0], 'invalid_attribute')); + $this->assertEquals(1, substr_count($exceptions[1], 'another_invalid_attribute')); } public function test_getter_undefined_property_exception_includes_model_name() @@ -112,34 +108,34 @@ public function test_get_values_for() { $books = Book::find_by_name('Ancient Art of Main Tanking'); $ret = $books->get_values_for(['book_id', 'author_id']); - $this->assert_equals(['book_id', 'author_id'], array_keys($ret)); - $this->assert_equals([1, 1], array_values($ret)); + $this->assertEquals(['book_id', 'author_id'], array_keys($ret)); + $this->assertEquals([1, 1], array_values($ret)); } public function test_hyphenated_column_names_to_underscore() { - if ($this->conn instanceof ActiveRecord\OciAdapter) { + if ($this->connection instanceof ActiveRecord\OciAdapter) { return; } $keys = array_keys(RmBldg::first()->attributes()); - $this->assert_true(in_array('rm_name', $keys)); + $this->assertTrue(in_array('rm_name', $keys)); } public function test_column_names_with_spaces() { - if ($this->conn instanceof ActiveRecord\OciAdapter) { + if ($this->connection instanceof ActiveRecord\OciAdapter) { return; } $keys = array_keys(RmBldg::first()->attributes()); - $this->assert_true(in_array('space_out', $keys)); + $this->assertTrue(in_array('space_out', $keys)); } public function test_mixed_case_column_name() { $keys = array_keys(Author::first()->attributes()); - $this->assert_true(in_array('mixedcasefield', $keys)); + $this->assertTrue(in_array('mixedcasefield', $keys)); } public function test_mixed_case_primary_key_save() @@ -147,17 +143,17 @@ public function test_mixed_case_primary_key_save() $venue = Venue::find(1); $venue->name = 'should not throw exception'; $venue->save(); - $this->assert_equals($venue->name, Venue::find(1)->name); + $this->assertEquals($venue->name, Venue::find(1)->name); } public function test_reload() { $venue = Venue::find(1); - $this->assert_equals('NY', $venue->state); + $this->assertEquals('NY', $venue->state); $venue->state = 'VA'; - $this->assert_equals('VA', $venue->state); + $this->assertEquals('VA', $venue->state); $venue->reload(); - $this->assert_equals('NY', $venue->state); + $this->assertEquals('NY', $venue->state); } public function test_reload_protected_attribute() @@ -166,27 +162,27 @@ public function test_reload_protected_attribute() $book->name = 'Should not stay'; $book->reload(); - $this->assert_not_equals('Should not stay', $book->name); + $this->assertNotEquals('Should not stay', $book->name); } public function test_active_record_model_home_not_set() { $home = ActiveRecord\Config::instance()->get_model_directory(); ActiveRecord\Config::instance()->set_model_directory(__FILE__); - $this->assert_equals(false, class_exists('TestAutoload')); + $this->assertEquals(false, class_exists('TestAutoload')); ActiveRecord\Config::instance()->set_model_directory($home); } public function test_auto_load_with_namespaced_model() { - $this->assert_true(class_exists('NamespaceTest\Book')); + $this->assertTrue(class_exists('NamespaceTest\Book')); } public function test_namespace_gets_stripped_from_table_name() { $model = new NamespaceTest\Book(); - $this->assert_equals('books', $model->table()->table); + $this->assertEquals('books', $model->table()->table); } public function test_namespace_gets_stripped_from_inferred_foreign_key() @@ -194,9 +190,9 @@ public function test_namespace_gets_stripped_from_inferred_foreign_key() $model = new NamespaceTest\Book(); $table = ActiveRecord\Table::load(get_class($model)); - $this->assert_equals($table->get_relationship('parent_book')->foreign_key[0], 'book_id'); - $this->assert_equals($table->get_relationship('parent_book_2')->foreign_key[0], 'book_id'); - $this->assert_equals($table->get_relationship('parent_book_3')->foreign_key[0], 'book_id'); + $this->assertEquals($table->get_relationship('parent_book')->foreign_key[0], 'book_id'); + $this->assertEquals($table->get_relationship('parent_book_2')->foreign_key[0], 'book_id'); + $this->assertEquals($table->get_relationship('parent_book_3')->foreign_key[0], 'book_id'); } public function test_namespaced_relationship_associates_correctly() @@ -204,30 +200,30 @@ public function test_namespaced_relationship_associates_correctly() $model = new NamespaceTest\Book(); $table = ActiveRecord\Table::load(get_class($model)); - $this->assert_not_null($table->get_relationship('parent_book')); - $this->assert_not_null($table->get_relationship('parent_book_2')); - $this->assert_not_null($table->get_relationship('parent_book_3')); + $this->assertNotNull($table->get_relationship('parent_book')); + $this->assertNotNull($table->get_relationship('parent_book_2')); + $this->assertNotNull($table->get_relationship('parent_book_3')); - $this->assert_not_null($table->get_relationship('pages')); - $this->assert_not_null($table->get_relationship('pages_2')); + $this->assertNotNull($table->get_relationship('pages')); + $this->assertNotNull($table->get_relationship('pages_2')); - $this->assert_null($table->get_relationship('parent_book_4')); - $this->assert_null($table->get_relationship('pages_3')); + $this->assertNull($table->get_relationship('parent_book_4')); + $this->assertNull($table->get_relationship('pages_3')); // Should refer to the same class - $this->assert_same( + $this->assertSame( ltrim($table->get_relationship('parent_book')->class_name, '\\'), ltrim($table->get_relationship('parent_book_2')->class_name, '\\') ); // Should refer to different classes - $this->assert_not_same( + $this->assertNotSame( ltrim($table->get_relationship('parent_book_2')->class_name, '\\'), ltrim($table->get_relationship('parent_book_3')->class_name, '\\') ); // Should refer to the same class - $this->assert_same( + $this->assertSame( ltrim($table->get_relationship('pages')->class_name, '\\'), ltrim($table->get_relationship('pages_2')->class_name, '\\') ); @@ -236,77 +232,77 @@ public function test_namespaced_relationship_associates_correctly() public function test_should_have_all_column_attributes_when_initializing_with_array() { $author = new Author(['name' => 'Tito']); - $this->assert_true(count(array_keys($author->attributes())) >= 9); + $this->assertTrue(count(array_keys($author->attributes())) >= 9); } public function test_defaults() { $author = new Author(); - $this->assert_equals('default_name', $author->name); + $this->assertEquals('default_name', $author->name); } public function test_alias_attribute_getter() { $venue = Venue::find(1); - $this->assert_equals($venue->marquee, $venue->name); - $this->assert_equals($venue->mycity, $venue->city); + $this->assertEquals($venue->marquee, $venue->name); + $this->assertEquals($venue->mycity, $venue->city); } public function test_alias_attribute_setter() { $venue = Venue::find(1); $venue->marquee = 'new name'; - $this->assert_equals($venue->marquee, 'new name'); - $this->assert_equals($venue->marquee, $venue->name); + $this->assertEquals($venue->marquee, 'new name'); + $this->assertEquals($venue->marquee, $venue->name); $venue->name = 'another name'; - $this->assert_equals($venue->name, 'another name'); - $this->assert_equals($venue->marquee, $venue->name); + $this->assertEquals($venue->name, 'another name'); + $this->assertEquals($venue->marquee, $venue->name); } public function test_alias_from_mass_attributes() { $venue = new Venue(['marquee' => 'meme', 'id' => 123]); - $this->assert_equals('meme', $venue->name); - $this->assert_equals($venue->marquee, $venue->name); + $this->assertEquals('meme', $venue->name); + $this->assertEquals($venue->marquee, $venue->name); } public function test_gh18_isset_on_aliased_attribute() { - $this->assert_true(isset(Venue::first()->marquee)); + $this->assertTrue(isset(Venue::first()->marquee)); } public function test_attr_accessible() { $book = new BookAttrAccessible(['name' => 'should not be set', 'author_id' => 1]); - $this->assert_null($book->name); - $this->assert_equals(1, $book->author_id); + $this->assertNull($book->name); + $this->assertEquals(1, $book->author_id); $book->name = 'test'; - $this->assert_equals('test', $book->name); + $this->assertEquals('test', $book->name); } public function test_attr_protected() { $book = new BookAttrAccessible(['book_id' => 999]); - $this->assert_null($book->book_id); + $this->assertNull($book->book_id); $book->book_id = 999; - $this->assert_equals(999, $book->book_id); + $this->assertEquals(999, $book->book_id); } public function test_isset() { $book = new Book(); - $this->assert_true(isset($book->name)); - $this->assert_false(isset($book->sharks)); + $this->assertTrue(isset($book->name)); + $this->assertFalse(isset($book->sharks)); $author = Author::find(1); - $this->assert_true(isset($author->awesome_person)); + $this->assertTrue(isset($author->awesome_person)); } public function test_readonly_only_halt_on_write_method() { $book = Book::first(['readonly' => true]); - $this->assert_true($book->is_readonly()); + $this->assertTrue($book->is_readonly()); try { $book->save(); @@ -315,35 +311,35 @@ public function test_readonly_only_halt_on_write_method() } $book->name = 'some new name'; - $this->assert_equals($book->name, 'some new name'); + $this->assertEquals($book->name, 'some new name'); } public function test_cast_when_using_setter() { $book = new Book(); $book->book_id = '1'; - $this->assert_same(1, $book->book_id); + $this->assertSame(1, $book->book_id); } public function test_cast_when_loading() { $book = Book::find(1); - $this->assert_same(1, $book->book_id); - $this->assert_same('Ancient Art of Main Tanking', $book->name); + $this->assertSame(1, $book->book_id); + $this->assertSame('Ancient Art of Main Tanking', $book->name); } public function test_cast_defaults() { $book = new Book(); - $this->assert_same(0.0, $book->special); + $this->assertSame(0.0, $book->special); } public function test_transaction_committed() { $original = Author::count(); $ret = Author::transaction(function () { Author::create(['name' => 'blah']); }); - $this->assert_equals($original+1, Author::count()); - $this->assert_true($ret); + $this->assertEquals($original+1, Author::count()); + $this->assertTrue($ret); } public function test_transaction_committed_when_returning_true() @@ -354,8 +350,8 @@ public function test_transaction_committed_when_returning_true() return true; }); - $this->assert_equals($original+1, Author::count()); - $this->assert_true($ret); + $this->assertEquals($original+1, Author::count()); + $this->assertTrue($ret); } public function test_transaction_rolledback_by_returning_false() @@ -368,8 +364,8 @@ public function test_transaction_rolledback_by_returning_false() return false; }); - $this->assert_equals($original, Author::count()); - $this->assert_false($ret); + $this->assertEquals($original, Author::count()); + $this->assertFalse($ret); } public function test_transaction_rolledback_by_throwing_exception() @@ -386,34 +382,34 @@ public function test_transaction_rolledback_by_throwing_exception() $exception = $e; } - $this->assert_not_null($exception); - $this->assert_equals($original, Author::count()); + $this->assertNotNull($exception); + $this->assertEquals($original, Author::count()); } public function test_delegate() { $event = Event::first(); - $this->assert_equals($event->venue->state, $event->state); - $this->assert_equals($event->venue->address, $event->address); + $this->assertEquals($event->venue->state, $event->state); + $this->assertEquals($event->venue->address, $event->address); } public function test_delegate_prefix() { $event = Event::first(); - $this->assert_equals($event->host->name, $event->woot_name); + $this->assertEquals($event->host->name, $event->woot_name); } public function test_delegate_returns_null_if_relationship_does_not_exist() { $event = new Event(); - $this->assert_null($event->state); + $this->assertNull($event->state); } public function test_delegate_set_attribute() { $event = Event::first(); $event->state = 'MEXICO'; - $this->assert_equals('MEXICO', $event->venue->state); + $this->assertEquals('MEXICO', $event->venue->state); } public function test_delegate_getter_gh_98() @@ -421,8 +417,8 @@ public function test_delegate_getter_gh_98() Venue::$use_custom_get_state_getter = true; $event = Event::first(); - $this->assert_equals('ny', $event->venue->state); - $this->assert_equals('ny', $event->state); + $this->assertEquals('ny', $event->venue->state); + $this->assertEquals('ny', $event->state); Venue::$use_custom_get_state_getter = false; } @@ -433,40 +429,40 @@ public function test_delegate_setter_gh_98() $event = Event::first(); $event->state = 'MEXICO'; - $this->assert_equals('MEXICO#', $event->venue->state); + $this->assertEquals('MEXICO#', $event->venue->state); Venue::$use_custom_set_state_setter = false; } public function test_table_name_with_underscores() { - $this->assert_not_null(AwesomePerson::first()); + $this->assertNotNull(AwesomePerson::first()); } public function test_model_should_default_as_new_record() { $author = new Author(); - $this->assert_true($author->is_new_record()); + $this->assertTrue($author->is_new_record()); } public function test_setter() { $author = new Author(); $author->password = 'plaintext'; - $this->assert_equals(md5('plaintext'), $author->encrypted_password); + $this->assertEquals(md5('plaintext'), $author->encrypted_password); } public function test_setter_with_same_name_as_an_attribute() { $author = new Author(); $author->name = 'bob'; - $this->assert_equals('BOB', $author->name); + $this->assertEquals('BOB', $author->name); } public function test_getter() { $book = Book::first(); - $this->assert_equals(strtoupper($book->name), $book->upper_name); + $this->assertEquals(strtoupper($book->name), $book->upper_name); } public function test_getter_with_same_name_as_an_attribute() @@ -474,7 +470,7 @@ public function test_getter_with_same_name_as_an_attribute() Book::$use_custom_get_name_getter = true; $book = new Book(); $book->name = 'bob'; - $this->assert_equals('BOB', $book->name); + $this->assertEquals('BOB', $book->name); Book::$use_custom_get_name_getter = false; } @@ -487,14 +483,12 @@ public function test_setting_invalid_date_should_set_date_to_null() public function test_table_name() { - $this->assert_equals('authors', Author::table_name()); + $this->assertEquals('authors', Author::table_name()); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_undefined_instance_method() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); Author::first()->find_by_name('sdf'); } @@ -505,41 +499,41 @@ public function test_clear_cache_for_specific_class() ActiveRecord\Table::clear_cache('Book'); $book_table3 = ActiveRecord\Table::load('Book'); - $this->assert_true($book_table1 === $book_table2); - $this->assert_true($book_table1 !== $book_table3); + $this->assertTrue($book_table1 === $book_table2); + $this->assertTrue($book_table1 !== $book_table3); } public function test_flag_dirty() { $author = new Author(); $author->flag_dirty('some_date'); - $this->assert_has_keys('some_date', $author->dirty_attributes()); - $this->assert_true($author->attribute_is_dirty('some_date')); + $this->assertArrayHasKey('some_date', $author->dirty_attributes()); + $this->assertTrue($author->attribute_is_dirty('some_date')); $author->save(); - $this->assert_false($author->attribute_is_dirty('some_date')); + $this->assertFalse($author->attribute_is_dirty('some_date')); } public function test_flag_dirty_attribute_which_does_not_exit() { $author = new Author(); $author->flag_dirty('some_inexistant_property'); - $this->assert_null($author->dirty_attributes()); - $this->assert_false($author->attribute_is_dirty('some_inexistant_property')); + $this->assertNull($author->dirty_attributes()); + $this->assertFalse($author->attribute_is_dirty('some_inexistant_property')); } public function test_gh245_dirty_attribute_should_not_raise_php_notice_if_not_dirty() { $event = new Event(['title' => 'Fun']); - $this->assert_false($event->attribute_is_dirty('description')); - $this->assert_true($event->attribute_is_dirty('title')); + $this->assertFalse($event->attribute_is_dirty('description')); + $this->assertTrue($event->attribute_is_dirty('title')); } public function test_assigning_php_datetime_gets_converted_to_date_class_with_defaults() { $author = new Author(); $author->created_at = $now = new \DateTime(); - $this->assert_is_a('ActiveRecord\\DateTime', $author->created_at); - $this->assert_datetime_equals($now, $author->created_at); + $this->assertInstanceOf('ActiveRecord\\DateTime', $author->created_at); + $this->assertEquals($now->format(DateTime::ATOM), $author->created_at->format(DateTime::ATOM)); } public function test_assigning_php_datetime_gets_converted_to_date_class_with_custom_date_class() @@ -547,36 +541,36 @@ public function test_assigning_php_datetime_gets_converted_to_date_class_with_cu ActiveRecord\Config::instance()->set_date_class('\\DateTime'); // use PHP built-in DateTime $author = new Author(); $author->created_at = $now = new \DateTime(); - $this->assert_is_a('DateTime', $author->created_at); - $this->assert_datetime_equals($now, $author->created_at); + $this->assertInstanceOf('DateTime', $author->created_at); + $this->assertEquals($now->format(DateTime::ATOM), $author->created_at->format(DateTime::ATOM)); } public function test_assigning_from_mass_assignment_php_datetime_gets_converted_to_ar_datetime() { $author = new Author(['created_at' => new \DateTime()]); - $this->assert_is_a('ActiveRecord\\DateTime', $author->created_at); + $this->assertInstanceOf('ActiveRecord\\DateTime', $author->created_at); } public function test_get_real_attribute_name() { $venue = new Venue(); - $this->assert_equals('name', $venue->get_real_attribute_name('name')); - $this->assert_equals('name', $venue->get_real_attribute_name('marquee')); - $this->assert_equals(null, $venue->get_real_attribute_name('invalid_field')); + $this->assertEquals('name', $venue->get_real_attribute_name('name')); + $this->assertEquals('name', $venue->get_real_attribute_name('marquee')); + $this->assertEquals(null, $venue->get_real_attribute_name('invalid_field')); } public function test_id_setter_works_with_table_without_pk_named_attribute() { $author = new Author(['id' => 123]); - $this->assert_equals(123, $author->author_id); + $this->assertEquals(123, $author->author_id); } public function test_query() { $row = Author::query('SELECT COUNT(*) AS n FROM authors', null)->fetch(); - $this->assert_true($row['n'] > 1); + $this->assertTrue($row['n'] > 1); $row = Author::query('SELECT COUNT(*) AS n FROM authors WHERE name=?', ['Tito'])->fetch(); - $this->assert_equals(['n' => 1], $row); + $this->assertEquals(['n' => 1], $row); } } diff --git a/test/ActiveRecordWriteTest.php b/test/ActiveRecordWriteTest.php index 4ed570d6..3b4d50e9 100644 --- a/test/ActiveRecordWriteTest.php +++ b/test/ActiveRecordWriteTest.php @@ -24,7 +24,7 @@ class AuthorExplicitSequence extends ActiveRecord\Model public static $sequence = 'blah_seq'; } -class ActiveRecordWriteTest extends DatabaseTest +class ActiveRecordWriteTest extends DatabaseTestCase { private function make_new_book_and($save=true) { @@ -41,6 +41,7 @@ private function make_new_book_and($save=true) public function test_save() { + $this->expectNotToPerformAssertions(); $venue = new Venue(['name' => 'Tito']); $venue->save(); } @@ -49,15 +50,13 @@ public function test_insert() { $author = new Author(['name' => 'Blah Blah']); $author->save(); - $this->assert_not_null(Author::find($author->id)); + $this->assertNotNull(Author::find($author->id)); } - /** - * @expectedException \ActiveRecord\DatabaseException - */ public function test_insert_with_no_sequence_defined() { - if (!$this->conn->supports_sequences()) { + $this->expectException(\ActiveRecord\DatabaseException::class); + if (!$this->connection->supports_sequences()) { throw new ActiveRecord\DatabaseException(''); } AuthorWithoutSequence::create(['name' => 'Bob!']); @@ -67,31 +66,31 @@ public function test_insert_should_quote_keys() { $author = new Author(['name' => 'Blah Blah']); $author->save(); - $this->assert_true(false !== strpos($author->connection()->last_query, $author->connection()->quote_name('updated_at'))); + $this->assertTrue(false !== strpos($author->connection()->last_query, $author->connection()->quote_name('updated_at'))); } public function test_save_auto_increment_id() { $venue = new Venue(['name' => 'Bob']); $venue->save(); - $this->assert_true($venue->id > 0); + $this->assertTrue($venue->id > 0); } public function test_sequence_was_set() { - if ($this->conn->supports_sequences()) { - $this->assert_equals($this->conn->get_sequence_name('authors', 'author_id'), Author::table()->sequence); + if ($this->connection->supports_sequences()) { + $this->assertEquals($this->connection->get_sequence_name('authors', 'author_id'), Author::table()->sequence); } else { - $this->assert_null(Author::table()->sequence); + $this->assertNull(Author::table()->sequence); } } public function test_sequence_was_explicitly_set() { - if ($this->conn->supports_sequences()) { - $this->assert_equals(AuthorExplicitSequence::$sequence, AuthorExplicitSequence::table()->sequence); + if ($this->connection->supports_sequences()) { + $this->assertEquals(AuthorExplicitSequence::$sequence, AuthorExplicitSequence::table()->sequence); } else { - $this->assert_null(Author::table()->sequence); + $this->assertNull(Author::table()->sequence); } } @@ -100,7 +99,7 @@ public function test_delete() $author = Author::find(1); $author->delete(); - $this->assert_false(Author::exists(1)); + $this->assertFalse(Author::exists(1)); } public function test_delete_by_find_all() @@ -112,7 +111,7 @@ public function test_delete_by_find_all() } $res = Book::all(); - $this->assert_equals(0, count($res)); + $this->assertEquals(0, count($res)); } public function test_update() @@ -122,8 +121,8 @@ public function test_update() $book->name = $new_name; $book->save(); - $this->assert_same($new_name, $book->name); - $this->assert_same($new_name, $book->name, Book::find(1)->name); + $this->assertSame($new_name, $book->name); + $this->assertSame($new_name, $book->name, Book::find(1)->name); } public function test_update_should_quote_keys() @@ -131,7 +130,7 @@ public function test_update_should_quote_keys() $book = Book::find(1); $book->name = 'new name'; $book->save(); - $this->assert_true(false !== strpos($book->connection()->last_query, $book->connection()->quote_name('name'))); + $this->assertTrue(false !== strpos($book->connection()->last_query, $book->connection()->quote_name('name'))); } public function test_update_attributes() @@ -141,15 +140,13 @@ public function test_update_attributes() $attrs = ['name' => $new_name]; $book->update_attributes($attrs); - $this->assert_same($new_name, $book->name); - $this->assert_same($new_name, $book->name, Book::find(1)->name); + $this->assertSame($new_name, $book->name); + $this->assertSame($new_name, $book->name, Book::find(1)->name); } - /** - * @expectedException \ActiveRecord\UndefinedPropertyException - */ public function test_update_attributes_undefined_property() { + $this->expectException(\ActiveRecord\UndefinedPropertyException::class); $book = Book::find(1); $book->update_attributes(['name' => 'new name', 'invalid_attribute' => true, 'another_invalid_attribute' => 'blah']); } @@ -160,15 +157,13 @@ public function test_update_attribute() $new_name = 'some stupid self-help book'; $book->update_attribute('name', $new_name); - $this->assert_same($new_name, $book->name); - $this->assert_same($new_name, $book->name, Book::find(1)->name); + $this->assertSame($new_name, $book->name); + $this->assertSame($new_name, $book->name, Book::find(1)->name); } - /** - * @expectedException \ActiveRecord\UndefinedPropertyException - */ public function test_update_attribute_undefined_property() { + $this->expectException(\ActiveRecord\UndefinedPropertyException::class); $book = Book::find(1); $book->update_attribute('invalid_attribute', true); } @@ -178,26 +173,26 @@ public function test_save_null_value() $book = Book::first(); $book->name = null; $book->save(); - $this->assert_same(null, Book::find($book->id)->name); + $this->assertSame(null, Book::find($book->id)->name); } public function test_save_blank_value() { // oracle doesn't do blanks. probably an option to enable? - if ($this->conn instanceof ActiveRecord\OciAdapter) { + if ($this->connection instanceof ActiveRecord\OciAdapter) { return; } $book = Book::find(1); $book->name = ''; $book->save(); - $this->assert_same('', Book::find(1)->name); + $this->assertSame('', Book::find(1)->name); } public function test_dirty_attributes() { $book = $this->make_new_book_and(false); - $this->assert_equals(['name', 'special'], array_keys($book->dirty_attributes())); + $this->assertEquals(['name', 'special'], array_keys($book->dirty_attributes())); } public function test_id_type() @@ -208,30 +203,30 @@ public function test_id_type() $bookFromFind = Book::find($book->id); // both should be ints - $this->assert_same($book->id, $bookFromFind->id); + $this->assertSame($book->id, $bookFromFind->id); } public function test_dirty_attributes_cleared_after_saving() { $book = $this->make_new_book_and(); - $this->assert_true(false !== strpos($book->table()->last_sql, 'name')); - $this->assert_true(false !== strpos($book->table()->last_sql, 'special')); - $this->assert_equals(null, $book->dirty_attributes()); + $this->assertTrue(false !== strpos($book->table()->last_sql, 'name')); + $this->assertTrue(false !== strpos($book->table()->last_sql, 'special')); + $this->assertEquals(null, $book->dirty_attributes()); } public function test_dirty_attributes_cleared_after_inserting() { $book = $this->make_new_book_and(); - $this->assert_equals(null, $book->dirty_attributes()); + $this->assertEquals(null, $book->dirty_attributes()); } public function test_no_dirty_attributes_but_still_insert_record() { $book = new Book(); - $this->assert_equals(null, $book->dirty_attributes()); + $this->assertEquals(null, $book->dirty_attributes()); $book->save(); - $this->assert_equals(null, $book->dirty_attributes()); - $this->assert_not_null($book->id); + $this->assertEquals(null, $book->dirty_attributes()); + $this->assertNotNull($book->id); } public function test_dirty_attributes_cleared_after_updating() @@ -239,7 +234,7 @@ public function test_dirty_attributes_cleared_after_updating() $book = Book::first(); $book->name = 'rivers cuomo'; $book->save(); - $this->assert_equals(null, $book->dirty_attributes()); + $this->assertEquals(null, $book->dirty_attributes()); } public function test_dirty_attributes_after_reloading() @@ -247,24 +242,24 @@ public function test_dirty_attributes_after_reloading() $book = Book::first(); $book->name = 'rivers cuomo'; $book->reload(); - $this->assert_equals(null, $book->dirty_attributes()); + $this->assertEquals(null, $book->dirty_attributes()); } public function test_dirty_attributes_with_mass_assignment() { $book = Book::first(); $book->set_attributes(['name' => 'rivers cuomo']); - $this->assert_equals(['name'], array_keys($book->dirty_attributes())); + $this->assertEquals(['name'], array_keys($book->dirty_attributes())); } public function test_timestamps_set_before_save() { $author = new Author(); $author->save(); - $this->assert_not_null($author->created_at, $author->updated_at); + $this->assertNotNull($author->created_at, $author->updated_at); $author->reload(); - $this->assert_not_null($author->created_at, $author->updated_at); + $this->assertNotNull($author->created_at, $author->updated_at); } public function test_timestamps_updated_at_only_set_before_update() @@ -278,39 +273,35 @@ public function test_timestamps_updated_at_only_set_before_update() $author->name = 'test'; $author->save(); - $this->assert_not_null($author->updated_at); - $this->assert_same($created_at, $author->created_at); - $this->assert_not_equals($updated_at, $author->updated_at); + $this->assertNotNull($author->updated_at); + $this->assertSame($created_at, $author->created_at); + $this->assertNotEquals($updated_at, $author->updated_at); } public function test_create() { $author = Author::create(['name' => 'Blah Blah']); - $this->assert_not_null(Author::find($author->id)); + $this->assertNotNull(Author::find($author->id)); } public function test_create_should_set_created_at() { $author = Author::create(['name' => 'Blah Blah']); - $this->assert_not_null($author->created_at); + $this->assertNotNull($author->created_at); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_update_with_no_primary_key_defined() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); Author::table()->pk = []; $author = Author::first(); $author->name = 'blahhhhhhhhhh'; $author->save(); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_delete_with_no_primary_key_defined() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); Author::table()->pk = []; $author = author::first(); $author->delete(); @@ -319,14 +310,12 @@ public function test_delete_with_no_primary_key_defined() public function test_inserting_with_explicit_pk() { $author = Author::create(['author_id' => 9999, 'name' => 'blah']); - $this->assert_equals(9999, $author->author_id); + $this->assertEquals(9999, $author->author_id); } - /** - * @expectedException \ActiveRecord\ReadOnlyException - */ public function test_readonly() { + $this->expectException(\ActiveRecord\ReadOnlyException::class); $author = Author::first(['readonly' => true]); $author->save(); } @@ -336,16 +325,16 @@ public function test_modified_attributes_in_before_handlers_get_saved() $author = DirtyAuthor::first(); $author->encrypted_password = 'coco'; $author->save(); - $this->assert_equals('i saved', DirtyAuthor::find($author->id)->name); + $this->assertEquals('i saved', DirtyAuthor::find($author->id)->name); } public function test_is_dirty() { $author = Author::first(); - $this->assert_equals(false, $author->is_dirty()); + $this->assertEquals(false, $author->is_dirty()); $author->name = 'coco'; - $this->assert_equals(true, $author->is_dirty()); + $this->assertEquals(true, $author->is_dirty()); } public function test_set_date_flags_dirty() @@ -353,7 +342,7 @@ public function test_set_date_flags_dirty() $author = Author::create(['some_date' => new DateTime()]); $author = Author::find($author->id); $author->some_date->setDate(2010, 1, 1); - $this->assert_has_keys('some_date', $author->dirty_attributes()); + $this->assertArrayHasKey('some_date', $author->dirty_attributes()); } public function test_set_date_flags_dirty_with_php_datetime() @@ -361,49 +350,49 @@ public function test_set_date_flags_dirty_with_php_datetime() $author = Author::create(['some_date' => new \DateTime()]); $author = Author::find($author->id); $author->some_date->setDate(2010, 1, 1); - $this->assert_has_keys('some_date', $author->dirty_attributes()); + $this->assertArrayHasKey('some_date', $author->dirty_attributes()); } public function test_delete_all_with_conditions_as_string() { $num_affected = Author::delete_all(['conditions' => 'parent_author_id = 2']); - $this->assert_equals(2, $num_affected); + $this->assertEquals(2, $num_affected); } public function test_delete_all_with_conditions_as_hash() { $num_affected = Author::delete_all(['conditions' => ['parent_author_id' => 2]]); - $this->assert_equals(2, $num_affected); + $this->assertEquals(2, $num_affected); } public function test_delete_all_with_conditions_as_array() { $num_affected = Author::delete_all(['conditions' => ['parent_author_id = ?', 2]]); - $this->assert_equals(2, $num_affected); + $this->assertEquals(2, $num_affected); } public function test_delete_all_with_limit_and_order() { - if (!$this->conn->accepts_limit_and_order_for_update_and_delete()) { - $this->mark_test_skipped('Only MySQL & Sqlite accept limit/order with UPDATE clause'); + if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { + $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with UPDATE clause'); } $num_affected = Author::delete_all(['conditions' => ['parent_author_id = ?', 2], 'limit' => 1, 'order' => 'name asc']); - $this->assert_equals(1, $num_affected); - $this->assert_true(false !== strpos(Author::table()->last_sql, 'ORDER BY name asc LIMIT 1')); + $this->assertEquals(1, $num_affected); + $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name asc LIMIT 1')); } public function test_update_all_with_set_as_string() { $num_affected = Author::update_all(['set' => 'parent_author_id = 2']); - $this->assert_equals(2, $num_affected); - $this->assert_equals(4, Author::count_by_parent_author_id(2)); + $this->assertEquals(2, $num_affected); + $this->assertEquals(4, Author::count_by_parent_author_id(2)); } public function test_update_all_with_set_as_hash() { $num_affected = Author::update_all(['set' => ['parent_author_id' => 2]]); - $this->assert_equals(2, $num_affected); + $this->assertEquals(2, $num_affected); } /** @@ -412,30 +401,30 @@ public function test_update_all_with_set_as_hash() public function test_update_all_with_conditions_as_string() { $num_affected = Author::update_all(['set' => 'parent_author_id = 2', 'conditions' => 'name = "Tito"']); - $this->assert_equals(1, $num_affected); + $this->assertEquals(1, $num_affected); } public function test_update_all_with_conditions_as_hash() { $num_affected = Author::update_all(['set' => 'parent_author_id = 2', 'conditions' => ['name' => 'Tito']]); - $this->assert_equals(1, $num_affected); + $this->assertEquals(1, $num_affected); } public function test_update_all_with_conditions_as_array() { $num_affected = Author::update_all(['set' => 'parent_author_id = 2', 'conditions' => ['name = ?', 'Tito']]); - $this->assert_equals(1, $num_affected); + $this->assertEquals(1, $num_affected); } public function test_update_all_with_limit_and_order() { - if (!$this->conn->accepts_limit_and_order_for_update_and_delete()) { - $this->mark_test_skipped('Only MySQL & Sqlite accept limit/order with UPDATE clause'); + if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { + $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with UPDATE clause'); } $num_affected = Author::update_all(['set' => 'parent_author_id = 2', 'limit' => 1, 'order' => 'name asc']); - $this->assert_equals(1, $num_affected); - $this->assert_true(false !== strpos(Author::table()->last_sql, 'ORDER BY name asc LIMIT 1')); + $this->assertEquals(1, $num_affected); + $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name asc LIMIT 1')); } public function test_update_native_datetime() @@ -443,7 +432,7 @@ public function test_update_native_datetime() $author = Author::create(['name' => 'Blah Blah']); $native_datetime = new \DateTime('1983-12-05'); $author->some_date = $native_datetime; - $this->assert_false($native_datetime === $author->some_date); + $this->assertFalse($native_datetime === $author->some_date); } public function test_update_our_datetime() @@ -451,6 +440,6 @@ public function test_update_our_datetime() $author = Author::create(['name' => 'Blah Blah']); $our_datetime = new DateTime('1983-12-05'); $author->some_date = $our_datetime; - $this->assert_true($our_datetime === $author->some_date); + $this->assertTrue($our_datetime === $author->some_date); } } diff --git a/test/CacheModelTest.php b/test/CacheModelTest.php index 9ba178dc..43361db5 100644 --- a/test/CacheModelTest.php +++ b/test/CacheModelTest.php @@ -2,16 +2,16 @@ use ActiveRecord\Cache; -class CacheModelTest extends DatabaseTest +class CacheModelTest extends DatabaseTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { if (!extension_loaded('memcache')) { $this->markTestSkipped('The memcache extension is not available'); return; } - parent::set_up($connection_name); + parent::setUp($connection_name); ActiveRecord\Config::instance()->set_cache('memcache://localhost'); } @@ -24,7 +24,7 @@ protected static function set_method_public($className, $methodName) return $method; } - public function tear_down() + public function tearDown(): void { Cache::flush(); Cache::initialize(null); @@ -32,12 +32,12 @@ public function tear_down() public function test_default_expire() { - $this->assert_equals(30, Author::table()->cache_model_expire); + $this->assertEquals(30, Author::table()->cache_model_expire); } public function test_explicit_expire() { - $this->assert_equals(2592000, Publisher::table()->cache_model_expire); + $this->assertEquals(2592000, Publisher::table()->cache_model_expire); } public function test_cache_key() @@ -45,7 +45,7 @@ public function test_cache_key() $method = $this->set_method_public('Author', 'cache_key'); $author = Author::first(); - $this->assert_equals('Author-1', $method->invokeArgs($author, [])); + $this->assertEquals('Author-1', $method->invokeArgs($author, [])); } public function test_model_cache_find_by_pk() diff --git a/test/CacheTest.php b/test/CacheTest.php index 8f146df9..2ffde541 100644 --- a/test/CacheTest.php +++ b/test/CacheTest.php @@ -1,10 +1,11 @@ markTestSkipped('The memcache extension is not available'); @@ -15,7 +16,7 @@ public function set_up() Cache::initialize('memcache://localhost'); } - public function tear_down() + public function tearDown(): void { Cache::flush(); } @@ -27,41 +28,42 @@ private function cache_get() public function test_initialize() { - $this->assert_not_null(Cache::$adapter); + $this->assertNotNull(Cache::$adapter); } public function test_initialize_with_null() { Cache::initialize(null); - $this->assert_null(Cache::$adapter); + $this->assertNull(Cache::$adapter); } public function test_get_returns_the_value() { - $this->assert_equals('abcd', $this->cache_get()); + $this->assertEquals('abcd', $this->cache_get()); } public function test_get_writes_to_the_cache() { $this->cache_get(); - $this->assert_equals('abcd', Cache::$adapter->read('1337')); + $this->assertEquals('abcd', Cache::$adapter->read('1337')); } public function test_get_does_not_execute_closure_on_cache_hit() { + $this->expectNotToPerformAssertions(); $this->cache_get(); Cache::get('1337', function () { throw new Exception('I better not execute!'); }); } public function test_cache_adapter_returns_false_on_cache_miss() { - $this->assert_same(false, Cache::$adapter->read('some-key')); + $this->assertSame(false, Cache::$adapter->read('some-key')); } public function test_get_works_without_caching_enabled() { Cache::$adapter = null; - $this->assert_equals('abcd', $this->cache_get()); + $this->assertEquals('abcd', $this->cache_get()); } public function test_cache_expire() @@ -70,22 +72,19 @@ public function test_cache_expire() $this->cache_get(); sleep(2); - $this->assert_same(false, Cache::$adapter->read('1337')); + $this->assertSame(false, Cache::$adapter->read('1337')); } public function test_namespace_is_set_properly() { Cache::$options['namespace'] = 'myapp'; $this->cache_get(); - $this->assert_same('abcd', Cache::$adapter->read('myapp::1337')); + $this->assertSame('abcd', Cache::$adapter->read('myapp::1337')); } - /** - * @expectedException \ActiveRecord\CacheException - * @expectedExceptionMessage Connection refused - */ public function test_exception_when_connect_fails() { + $this->expectException(\ActiveRecord\CacheException::class); Cache::initialize('memcache://127.0.0.1:1234'); } } diff --git a/test/CallbackTest.php b/test/CallbackTest.php index 2a4bb9fa..56e542d4 100644 --- a/test/CallbackTest.php +++ b/test/CallbackTest.php @@ -1,10 +1,10 @@ assert_true(in_array($method_name, $this->callback->get_callbacks($callback_name))); + $this->assertTrue(in_array($method_name, $this->callback->get_callbacks($callback_name))); } public function assert_implicit_save($first_method, $second_method) @@ -27,7 +27,7 @@ public function assert_implicit_save($first_method, $second_method) $this->callback->register($first_method, function ($model) use (&$i_ran, $first_method) { $i_ran[] = $first_method; }); $this->callback->register($second_method, function ($model) use (&$i_ran, $second_method) { $i_ran[] = $second_method; }); $this->callback->invoke(null, $second_method); - $this->assert_equals([$first_method, $second_method], $i_ran); + $this->assertEquals([$first_method, $second_method], $i_ran); } public function test_gh_266_calling_save_in_after_save_callback_uses_update_instead_of_insert() @@ -37,8 +37,8 @@ public function test_gh_266_calling_save_in_after_save_callback_uses_update_inst $venue->city = 'Awesome City'; $venue->save(); - $this->assert_true(VenueAfterCreate::exists(['conditions'=> ['name'=>'changed!']])); - $this->assert_false(VenueAfterCreate::exists(['conditions'=> ['name'=>'change me']])); + $this->assertTrue(VenueAfterCreate::exists(['conditions'=> ['name'=>'changed!']])); + $this->assertFalse(VenueAfterCreate::exists(['conditions'=> ['name'=>'change me']])); } public function test_generic_callback_was_auto_registered() @@ -58,19 +58,15 @@ public function test_register_non_generic() $this->assert_has_callback('after_construct', 'non_generic_after_construct'); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_register_invalid_callback() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); $this->callback->register('invalid_callback'); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_register_callback_with_undefined_method() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); $this->callback->register('after_construct', 'do_not_define_me'); } @@ -82,6 +78,7 @@ public function test_register_with_string_definition() public function test_register_with_closure() { + $this->expectNotToPerformAssertions(); $this->callback->register('after_construct', function ($mode) { }); } @@ -101,14 +98,14 @@ public function test_register_appends_to_registry() { $this->callback->register('after_construct'); $this->callback->register('after_construct', 'non_generic_after_construct'); - $this->assert_equals(['after_construct', 'after_construct', 'non_generic_after_construct'], $this->callback->get_callbacks('after_construct')); + $this->assertEquals(['after_construct', 'after_construct', 'non_generic_after_construct'], $this->callback->get_callbacks('after_construct')); } public function test_register_prepends_to_registry() { $this->callback->register('after_construct'); $this->callback->register('after_construct', 'non_generic_after_construct', ['prepend' => true]); - $this->assert_equals(['non_generic_after_construct', 'after_construct', 'after_construct'], $this->callback->get_callbacks('after_construct')); + $this->assertEquals(['non_generic_after_construct', 'after_construct', 'after_construct'], $this->callback->get_callbacks('after_construct')); } public function test_registers_via_static_array_definition() @@ -122,11 +119,9 @@ public function test_registers_via_static_string_definition() $this->assert_has_callback('before_destroy', 'before_destroy_using_string'); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_register_via_static_with_invalid_definition() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); $class_name = 'Venues_' . md5(uniqid()); eval("class $class_name extends ActiveRecord\\Model { static \$table_name = 'venues'; static \$after_save = 'method_that_does_not_exist'; };"); new $class_name(); @@ -137,31 +132,31 @@ public function test_can_register_same_multiple_times() { $this->callback->register('after_construct'); $this->callback->register('after_construct'); - $this->assert_equals(['after_construct', 'after_construct', 'after_construct'], $this->callback->get_callbacks('after_construct')); + $this->assertEquals(['after_construct', 'after_construct', 'after_construct'], $this->callback->get_callbacks('after_construct')); } public function test_register_closure_callback() { $closure = function ($model) {}; $this->callback->register('after_save', $closure); - $this->assert_equals([$closure], $this->callback->get_callbacks('after_save')); + $this->assertEquals([$closure], $this->callback->get_callbacks('after_save')); } public function test_get_callbacks_returns_array() { $this->callback->register('after_construct'); - $this->assert_true(is_array($this->callback->get_callbacks('after_construct'))); + $this->assertTrue(is_array($this->callback->get_callbacks('after_construct'))); } public function test_get_callbacks_returns_null() { - $this->assert_null($this->callback->get_callbacks('this_callback_name_should_never_exist')); + $this->assertNull($this->callback->get_callbacks('this_callback_name_should_never_exist')); } public function test_invoke_runs_all_callbacks() { if (method_exists($this, 'createMock')) { - $mock = $this->create_mock('VenueCB', ['after_destroy_one', 'after_destroy_two']); + $mock = $this->createMock('VenueCB', ['after_destroy_one', 'after_destroy_two']); } else { $mock = $this->get_mock('VenueCB', ['after_destroy_one', 'after_destroy_two']); } @@ -175,7 +170,7 @@ public function test_invoke_closure() $i_ran = false; $this->callback->register('after_validation', function ($model) use (&$i_ran) { $i_ran = true; }); $this->callback->invoke(null, 'after_validation'); - $this->assert_true($i_ran); + $this->assertTrue($i_ran); } public function test_invoke_implicitly_calls_save_first() @@ -186,31 +181,29 @@ public function test_invoke_implicitly_calls_save_first() $this->assert_implicit_save('after_save', 'after_update'); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_invoke_unregistered_callback() { - $mock = $this->get_mock_builder('VenueCB', ['columns']); + $this->expectException(\ActiveRecord\ActiveRecordException::class); + $mock = $this->getMockBuilder('VenueCB', ['columns']); $this->callback->invoke($mock, 'before_validation_on_create'); } public function test_before_callbacks_pass_on_false_return_callback_returned_false() { $this->callback->register('before_validation', function ($model) { return false; }); - $this->assert_false($this->callback->invoke(null, 'before_validation')); + $this->assertFalse($this->callback->invoke(null, 'before_validation')); } public function test_before_callbacks_does_not_pass_on_false_for_after_callbacks() { $this->callback->register('after_validation', function ($model) { return false; }); - $this->assert_true($this->callback->invoke(null, 'after_validation')); + $this->assertTrue($this->callback->invoke(null, 'after_validation')); } public function test_gh_28_after_create_should_be_invoked_after_auto_incrementing_pk_is_set() { $that = $this; - VenueCB::$after_create = function ($model) use ($that) { $that->assert_not_null($model->id); }; + VenueCB::$after_create = function ($model) use ($that) { $that->assertNotNull($model->id); }; ActiveRecord\Table::clear_cache('VenueCB'); $venue = VenueCB::find(1); $venue = new VenueCB($venue->attributes()); @@ -235,9 +228,9 @@ public function test_before_create_returned_false_halts_execution() $v->id = null; VenueCB::create($v->attributes()); - $this->assert_true($i_should_have_ran); - $this->assert_false($i_ran); - $this->assert_true(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'INSERT')); + $this->assertTrue($i_should_have_ran); + $this->assertFalse($i_ran); + $this->assertTrue(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'INSERT')); } public function test_before_save_returned_false_halts_execution() @@ -256,10 +249,10 @@ public function test_before_save_returned_false_halts_execution() $v->name .= 'test'; $ret = $v->save(); - $this->assert_true($i_should_have_ran); - $this->assert_false($i_ran); - $this->assert_false($ret); - $this->assert_true(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'UPDATE')); + $this->assertTrue($i_should_have_ran); + $this->assertFalse($i_ran); + $this->assertFalse($ret); + $this->assertTrue(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'UPDATE')); } public function test_before_destroy_returned_false_halts_execution() @@ -275,9 +268,9 @@ public function test_before_destroy_returned_false_halts_execution() $v = VenueCB::find(1); $ret = $v->delete(); - $this->assert_false($i_ran); - $this->assert_false($ret); - $this->assert_true(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'DELETE')); + $this->assertFalse($i_ran); + $this->assertFalse($ret); + $this->assertTrue(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'DELETE')); } public function test_before_validation_returned_false_halts_execution() @@ -290,7 +283,7 @@ public function test_before_validation_returned_false_halts_execution() $v->name .= 'test'; $ret = $v->save(); - $this->assert_false($ret); - $this->assert_true(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'UPDATE')); + $this->assertFalse($ret); + $this->assertTrue(false === strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'UPDATE')); } } diff --git a/test/ColumnTest.php b/test/ColumnTest.php index 8873efac..7781652d 100644 --- a/test/ColumnTest.php +++ b/test/ColumnTest.php @@ -3,23 +3,24 @@ use ActiveRecord\Column; use ActiveRecord\DatabaseException; use ActiveRecord\DateTime; +use PHPUnit\Framework\TestCase; -class ColumnTest extends SnakeCase_PHPUnit_Framework_TestCase +class ColumnTest extends TestCase { - public function set_up() + public function setUp($connection_name = null): void { $this->column = new Column(); try { $this->conn = ActiveRecord\ConnectionManager::get_connection(ActiveRecord\Config::instance()->get_default_connection()); } catch (DatabaseException $e) { - $this->mark_test_skipped('failed to connect using default connection. ' . $e->getMessage()); + $this->markTestSkipped('failed to connect using default connection. ' . $e->getMessage()); } } public function assert_mapped_type($type, $raw_type) { $this->column->raw_type = $raw_type; - $this->assert_equals($type, $this->column->map_raw_type()); + $this->assertEquals($type, $this->column->map_raw_type()); } public function assert_cast($type, $casted_value, $original_value) @@ -28,9 +29,9 @@ public function assert_cast($type, $casted_value, $original_value) $value = $this->column->cast($original_value, $this->conn); if (null != $original_value && (Column::DATETIME == $type || Column::DATE == $type)) { - $this->assert_true($value instanceof DateTime); + $this->assertTrue($value instanceof DateTime); } else { - $this->assert_same($casted_value, $value); + $this->assertSame($casted_value, $value); } } @@ -74,7 +75,7 @@ public function test_map_raw_type_changes_integer_to_int() { $this->column->raw_type = 'integer'; $this->column->map_raw_type(); - $this->assert_equals('int', $this->column->raw_type); + $this->assertEquals('int', $this->column->raw_type); } public function test_cast() @@ -118,43 +119,43 @@ public function test_empty_and_null_date_strings_should_return_null() { $column = new Column(); $column->type = Column::DATE; - $this->assert_equals(null, $column->cast(null, $this->conn)); - $this->assert_equals(null, $column->cast('', $this->conn)); + $this->assertEquals(null, $column->cast(null, $this->conn)); + $this->assertEquals(null, $column->cast('', $this->conn)); } public function test_empty_and_null_datetime_strings_should_return_null() { $column = new Column(); $column->type = Column::DATETIME; - $this->assert_equals(null, $column->cast(null, $this->conn)); - $this->assert_equals(null, $column->cast('', $this->conn)); + $this->assertEquals(null, $column->cast(null, $this->conn)); + $this->assertEquals(null, $column->cast('', $this->conn)); } public function test_native_date_time_attribute_copies_exact_tz() { - $dt = new \DateTime(null, new \DateTimeZone('America/New_York')); + $dt = new \DateTime('', new \DateTimeZone('America/New_York')); $column = new Column(); $column->type = Column::DATETIME; $dt2 = $column->cast($dt, $this->conn); - $this->assert_equals($dt->getTimestamp(), $dt2->getTimestamp()); - $this->assert_equals($dt->getTimeZone(), $dt2->getTimeZone()); - $this->assert_equals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); + $this->assertEquals($dt->getTimestamp(), $dt2->getTimestamp()); + $this->assertEquals($dt->getTimeZone(), $dt2->getTimeZone()); + $this->assertEquals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); } public function test_ar_date_time_attribute_copies_exact_tz() { - $dt = new DateTime(null, new \DateTimeZone('America/New_York')); + $dt = new DateTime('', new \DateTimeZone('America/New_York')); $column = new Column(); $column->type = Column::DATETIME; $dt2 = $column->cast($dt, $this->conn); - $this->assert_equals($dt->getTimestamp(), $dt2->getTimestamp()); - $this->assert_equals($dt->getTimeZone(), $dt2->getTimeZone()); - $this->assert_equals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); + $this->assertEquals($dt->getTimestamp(), $dt2->getTimestamp()); + $this->assertEquals($dt->getTimeZone(), $dt2->getTimeZone()); + $this->assertEquals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); } } diff --git a/test/ConfigTest.php b/test/ConfigTest.php index 881b5dba..e24d286d 100644 --- a/test/ConfigTest.php +++ b/test/ConfigTest.php @@ -2,11 +2,124 @@ use ActiveRecord\Config; use ActiveRecord\ConfigException; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class TestLogger +class TestLogger implements LoggerInterface { - private function log() + public function emergency(string|\Stringable $message, array $context = []): void { + + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function alert(string|\Stringable $message, array $context = []): void { + + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function critical(string|\Stringable $message, array $context = []): void { + + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function error(string|\Stringable $message, array $context = []): void { + + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function warning(string|\Stringable $message, array $context = []): void { + + } + + /** + * Normal but significant events. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function notice(string|\Stringable $message, array $context = []): void { + + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function info(string|\Stringable $message, array $context = []): void { + + } + + /** + * Detailed debug information. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function debug(string|\Stringable $message, array $context = []): void { + + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []): void { + } } @@ -28,102 +141,94 @@ public static function createFromFormat($format, $time) } } -class ConfigTest extends SnakeCase_PHPUnit_Framework_TestCase +class ConfigTest extends TestCase { - public function set_up() + public function setUp(): void { $this->config = new Config(); $this->connections = ['development' => 'mysql://blah/development', 'test' => 'mysql://blah/test']; $this->config->set_connections($this->connections); } - /** - * @expectedException \ActiveRecord\ConfigException - */ public function test_set_connections_must_be_array() { + $this->expectException(\ActiveRecord\ConfigException::class); $this->config->set_connections(null); } public function test_get_connections() { - $this->assert_equals($this->connections, $this->config->get_connections()); + $this->assertEquals($this->connections, $this->config->get_connections()); } public function test_get_connection() { - $this->assert_equals($this->connections['development'], $this->config->get_connection('development')); + $this->assertEquals($this->connections['development'], $this->config->get_connection('development')); } public function test_get_invalid_connection() { - $this->assert_null($this->config->get_connection('whiskey tango foxtrot')); + $this->assertNull($this->config->get_connection('whiskey tango foxtrot')); } public function test_get_default_connection_and_connection() { $this->config->set_default_connection('development'); - $this->assert_equals('development', $this->config->get_default_connection()); - $this->assert_equals($this->connections['development'], $this->config->get_default_connection_string()); + $this->assertEquals('development', $this->config->get_default_connection()); + $this->assertEquals($this->connections['development'], $this->config->get_default_connection_string()); } public function test_get_default_connection_and_connection_string_defaults_to_development() { - $this->assert_equals('development', $this->config->get_default_connection()); - $this->assert_equals($this->connections['development'], $this->config->get_default_connection_string()); + $this->assertEquals('development', $this->config->get_default_connection()); + $this->assertEquals($this->connections['development'], $this->config->get_default_connection_string()); } public function test_get_default_connection_string_when_connection_name_is_not_valid() { $this->config->set_default_connection('little mac'); - $this->assert_null($this->config->get_default_connection_string()); + $this->assertNull($this->config->get_default_connection_string()); } public function test_default_connection_is_set_when_only_one_connection_is_present() { $this->config->set_connections(['development' => $this->connections['development']]); - $this->assert_equals('development', $this->config->get_default_connection()); + $this->assertEquals('development', $this->config->get_default_connection()); } public function test_set_connections_with_default() { $this->config->set_connections($this->connections, 'test'); - $this->assert_equals('test', $this->config->get_default_connection()); + $this->assertEquals('test', $this->config->get_default_connection()); } public function test_get_date_class_with_default() { - $this->assert_equals('ActiveRecord\\DateTime', $this->config->get_date_class()); + $this->assertEquals('ActiveRecord\\DateTime', $this->config->get_date_class()); } - /** - * @expectedException \ActiveRecord\ConfigException - */ public function test_set_date_class_when_class_doesnt_exist() { + $this->expectException(\ActiveRecord\ConfigException::class); $this->config->set_date_class('doesntexist'); } - /** - * @expectedException \ActiveRecord\ConfigException - */ public function test_set_date_class_when_class_doesnt_have_format_or_createfromformat() { + $this->expectException(\ActiveRecord\ConfigException::class); $this->config->set_date_class('TestLogger'); } - /** - * @expectedException \ActiveRecord\ConfigException - */ public function test_set_date_class_when_class_doesnt_have_createfromformat() { + $this->expectException(\ActiveRecord\ConfigException::class); $this->config->set_date_class('TestDateTimeWithoutCreateFromFormat'); } public function test_set_date_class_with_valid_class() { $this->config->set_date_class('TestDateTime'); - $this->assert_equals('TestDateTime', $this->config->get_date_class()); + $this->assertEquals('TestDateTime', $this->config->get_date_class()); } public function test_initialize_closure() @@ -131,18 +236,8 @@ public function test_initialize_closure() $test = $this; Config::initialize(function ($cfg) use ($test) { - $test->assert_not_null($cfg); - $test->assert_equals('ActiveRecord\Config', get_class($cfg)); + $test->assertNotNull($cfg); + $test->assertEquals('ActiveRecord\Config', get_class($cfg)); }); } - - public function test_logger_object_must_implement_log_method() - { - try { - $this->config->set_logger(new TestLogger()); - $this->fail(); - } catch (ConfigException $e) { - $this->assert_equals($e->getMessage(), 'Logger object must implement a public log method'); - } - } } diff --git a/test/ConnectionManagerTest.php b/test/ConnectionManagerTest.php index eb278f6a..1d54f8ef 100644 --- a/test/ConnectionManagerTest.php +++ b/test/ConnectionManagerTest.php @@ -3,17 +3,17 @@ use ActiveRecord\Config; use ActiveRecord\ConnectionManager; -class ConnectionManagerTest extends DatabaseTest +class ConnectionManagerTest extends DatabaseTestCase { public function test_get_connection_with_null_connection() { - $this->assert_not_null(ConnectionManager::get_connection(null)); - $this->assert_not_null(ConnectionManager::get_connection()); + $this->assertNotNull(ConnectionManager::get_connection(null)); + $this->assertNotNull(ConnectionManager::get_connection()); } public function test_get_connection() { - $this->assert_not_null(ConnectionManager::get_connection('mysql')); + $this->assertNotNull(ConnectionManager::get_connection('mysql')); } public function test_get_connection_uses_existing_object() @@ -21,7 +21,7 @@ public function test_get_connection_uses_existing_object() $a = ConnectionManager::get_connection('mysql'); $a->harro = 'harro there'; - $this->assert_same($a, ConnectionManager::get_connection('mysql')); + $this->assertSame($a, ConnectionManager::get_connection('mysql')); } public function test_gh_91_get_connection_with_null_connection_is_always_default() @@ -31,8 +31,8 @@ public function test_gh_91_get_connection_with_null_connection_is_always_default $conn_three = ConnectionManager::get_connection('mysql'); $conn_four = ConnectionManager::get_connection(); - $this->assert_same($conn_one, $conn_three); - $this->assert_same($conn_two, $conn_three); - $this->assert_same($conn_four, $conn_three); + $this->assertSame($conn_one, $conn_three); + $this->assertSame($conn_two, $conn_three); + $this->assertSame($conn_four, $conn_three); } } diff --git a/test/ConnectionTest.php b/test/ConnectionTest.php index ab185d15..bade2f05 100644 --- a/test/ConnectionTest.php +++ b/test/ConnectionTest.php @@ -1,79 +1,76 @@ expectException(\ActiveRecord\DatabaseException::class); ActiveRecord\Connection::parse_connection_url('mysql://user:pass@'); } public function test_connection_info() { $info = ActiveRecord\Connection::parse_connection_url('mysql://user:pass@127.0.0.1:3306/dbname'); - $this->assert_equals('mysql', $info->protocol); - $this->assert_equals('user', $info->user); - $this->assert_equals('pass', $info->pass); - $this->assert_equals('127.0.0.1', $info->host); - $this->assert_equals(3306, $info->port); - $this->assert_equals('dbname', $info->db); + $this->assertEquals('mysql', $info->protocol); + $this->assertEquals('user', $info->user); + $this->assertEquals('pass', $info->pass); + $this->assertEquals('127.0.0.1', $info->host); + $this->assertEquals(3306, $info->port); + $this->assertEquals('dbname', $info->db); } public function test_gh_103_sqlite_connection_string_relative() { $info = ActiveRecord\Connection::parse_connection_url('sqlite://../some/path/to/file.db'); - $this->assert_equals('../some/path/to/file.db', $info->host); + $this->assertEquals('../some/path/to/file.db', $info->host); } - /** - * @expectedException \ActiveRecord\DatabaseException - */ public function test_gh_103_sqlite_connection_string_absolute() { - $info = ActiveRecord\Connection::parse_connection_url('sqlite:///some/path/to/file.db'); + $this->expectException(\ActiveRecord\DatabaseException::class); + ActiveRecord\Connection::parse_connection_url('sqlite:///some/path/to/file.db'); } public function test_gh_103_sqlite_connection_string_unix() { $info = ActiveRecord\Connection::parse_connection_url('sqlite://unix(/some/path/to/file.db)'); - $this->assert_equals('/some/path/to/file.db', $info->host); + $this->assertEquals('/some/path/to/file.db', $info->host); $info = ActiveRecord\Connection::parse_connection_url('sqlite://unix(/some/path/to/file.db)/'); - $this->assert_equals('/some/path/to/file.db', $info->host); + $this->assertEquals('/some/path/to/file.db', $info->host); $info = ActiveRecord\Connection::parse_connection_url('sqlite://unix(/some/path/to/file.db)/dummy'); - $this->assert_equals('/some/path/to/file.db', $info->host); + $this->assertEquals('/some/path/to/file.db', $info->host); } public function test_gh_103_sqlite_connection_string_windows() { $info = ActiveRecord\Connection::parse_connection_url('sqlite://windows(c%3A/some/path/to/file.db)'); - $this->assert_equals('c:/some/path/to/file.db', $info->host); + $this->assertEquals('c:/some/path/to/file.db', $info->host); } public function test_parse_connection_url_with_unix_sockets() { $info = ActiveRecord\Connection::parse_connection_url('mysql://user:password@unix(/tmp/mysql.sock)/database'); - $this->assert_equals('/tmp/mysql.sock', $info->host); + $this->assertEquals('/tmp/mysql.sock', $info->host); } public function test_parse_connection_url_with_decode_option() { $info = ActiveRecord\Connection::parse_connection_url('mysql://h%20az:h%40i@127.0.0.1/test?decode=true'); - $this->assert_equals('h az', $info->user); - $this->assert_equals('h@i', $info->pass); + $this->assertEquals('h az', $info->user); + $this->assertEquals('h@i', $info->pass); } public function test_encoding() { $info = ActiveRecord\Connection::parse_connection_url('mysql://test:test@127.0.0.1/test?charset=utf8'); - $this->assert_equals('utf8', $info->charset); + $this->assertEquals('utf8', $info->charset); } } diff --git a/test/DateFormatTest.php b/test/DateFormatTest.php index 6f22f181..e1f31bc2 100644 --- a/test/DateFormatTest.php +++ b/test/DateFormatTest.php @@ -1,6 +1,6 @@ save(); $author = Author::first(); - $this->assert_is_a('ActiveRecord\\DateTime', $author->some_date); + $this->assertInstanceOf('ActiveRecord\\DateTime', $author->some_date); } } diff --git a/test/DateTimeTest.php b/test/DateTimeTest.php index c4df54ad..0f960351 100644 --- a/test/DateTimeTest.php +++ b/test/DateTimeTest.php @@ -2,16 +2,17 @@ use ActiveRecord\DatabaseException; use ActiveRecord\DateTime as DateTime; +use PHPUnit\Framework\TestCase; -class DateTimeTest extends SnakeCase_PHPUnit_Framework_TestCase +class DateTimeTest extends TestCase { - public function set_up() + public function setUp(): void { $this->date = new DateTime(); $this->original_format = DateTime::$DEFAULT_FORMAT; } - public function tear_down() + public function tearDown(): void { DateTime::$DEFAULT_FORMAT = $this->original_format; } @@ -21,7 +22,7 @@ private function get_model() try { $model = new Author(); } catch (DatabaseException $e) { - $this->mark_test_skipped('failed to connect. ' . $e->getMessage()); + $this->markTestSkipped('failed to connect. ' . $e->getMessage()); } return $model; @@ -37,7 +38,7 @@ private function assert_dirtifies($method /*, method params, ...*/) array_shift($args); call_user_func_array([$datetime, $method], $args); - $this->assert_has_keys('some_date', $model->dirty_attributes()); + $this->assertArrayHasKey('some_date', $model->dirty_attributes()); } public function test_should_flag_the_attribute_dirty() @@ -62,7 +63,7 @@ public function test_set_iso_date() $b = new DateTime(); $b->setISODate(2001, 1); - $this->assert_datetime_equals($a, $b); + $this->assertEquals($a->format(DateTime::ATOM), $b->format(DateTime::ATOM)); } public function test_set_time() @@ -73,82 +74,82 @@ public function test_set_time() $b = new DateTime(); $b->setTime(1, 1); - $this->assert_datetime_equals($a, $b); + $this->assertEquals($a->format(DateTime::ATOM), $b->format(DateTime::ATOM)); } public function test_get_format_with_friendly() { - $this->assert_equals('Y-m-d H:i:s', DateTime::get_format('db')); + $this->assertEquals('Y-m-d H:i:s', DateTime::get_format('db')); } public function test_get_format_with_format() { - $this->assert_equals('Y-m-d', DateTime::get_format('Y-m-d')); + $this->assertEquals('Y-m-d', DateTime::get_format('Y-m-d')); } public function test_get_format_with_null() { - $this->assert_equals(\DateTime::RFC2822, DateTime::get_format()); + $this->assertEquals(\DateTime::RFC2822, DateTime::get_format()); } public function test_format() { - $this->assert_true(is_string($this->date->format())); - $this->assert_true(is_string($this->date->format('Y-m-d'))); + $this->assertTrue(is_string($this->date->format())); + $this->assertTrue(is_string($this->date->format('Y-m-d'))); } public function test_format_by_friendly_name() { $d = date(DateTime::get_format('db')); - $this->assert_equals($d, $this->date->format('db')); + $this->assertEquals($d, $this->date->format('db')); } public function test_format_by_custom_format() { $format = 'Y/m/d'; - $this->assert_equals(date($format), $this->date->format($format)); + $this->assertEquals(date($format), $this->date->format($format)); } public function test_format_uses_default() { $d = date(DateTime::$FORMATS[DateTime::$DEFAULT_FORMAT]); - $this->assert_equals($d, $this->date->format()); + $this->assertEquals($d, $this->date->format()); } public function test_all_formats() { foreach (DateTime::$FORMATS as $name => $format) { - $this->assert_equals(date($format), $this->date->format($name)); + $this->assertEquals(date($format), $this->date->format($name)); } } public function test_change_default_format_to_format_string() { DateTime::$DEFAULT_FORMAT = 'H:i:s'; - $this->assert_equals(date(DateTime::$DEFAULT_FORMAT), $this->date->format()); + $this->assertEquals(date(DateTime::$DEFAULT_FORMAT), $this->date->format()); } public function test_change_default_format_to_friently() { DateTime::$DEFAULT_FORMAT = 'short'; - $this->assert_equals(date(DateTime::$FORMATS['short']), $this->date->format()); + $this->assertEquals(date(DateTime::$FORMATS['short']), $this->date->format()); } public function test_to_string() { - $this->assert_equals(date(DateTime::get_format()), '' . $this->date); + $this->assertEquals(date(DateTime::get_format()), '' . $this->date); } public function test_create_from_format_error_handling() { $d = DateTime::createFromFormat('H:i:s Y-d-m', '!!!'); - $this->assert_false($d); + $this->assertFalse($d); } public function test_create_from_format_without_tz() { $d = DateTime::createFromFormat('H:i:s Y-d-m', '03:04:05 2000-02-01'); - $this->assert_equals(new DateTime('2000-01-02 03:04:05'), $d); + $this->assertEquals(new DateTime('2000-01-02 03:04:05'), $d); } public function test_create_from_format_with_tz() @@ -156,7 +157,7 @@ public function test_create_from_format_with_tz() $d = DateTime::createFromFormat('Y-m-d H:i:s', '2000-02-01 03:04:05', new \DateTimeZone('Etc/GMT-10')); $d2 = new DateTime('2000-01-31 17:04:05'); - $this->assert_equals($d2->getTimestamp(), $d->getTimestamp()); + $this->assertEquals($d2->getTimestamp(), $d->getTimestamp()); } public function test_native_date_time_attribute_copies_exact_tz() @@ -168,9 +169,9 @@ public function test_native_date_time_attribute_copies_exact_tz() $model->assign_attribute('updated_at', $dt); $dt2 = $model->read_attribute('updated_at'); - $this->assert_equals($dt->getTimestamp(), $dt2->getTimestamp()); - $this->assert_equals($dt->getTimeZone(), $dt2->getTimeZone()); - $this->assert_equals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); + $this->assertEquals($dt->getTimestamp(), $dt2->getTimestamp()); + $this->assertEquals($dt->getTimeZone(), $dt2->getTimeZone()); + $this->assertEquals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); } public function test_ar_date_time_attribute_copies_exact_tz() @@ -182,9 +183,9 @@ public function test_ar_date_time_attribute_copies_exact_tz() $model->assign_attribute('updated_at', $dt); $dt2 = $model->read_attribute('updated_at'); - $this->assert_equals($dt->getTimestamp(), $dt2->getTimestamp()); - $this->assert_equals($dt->getTimeZone(), $dt2->getTimeZone()); - $this->assert_equals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); + $this->assertEquals($dt->getTimestamp(), $dt2->getTimestamp()); + $this->assertEquals($dt->getTimeZone(), $dt2->getTimeZone()); + $this->assertEquals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); } public function test_clone() @@ -198,20 +199,20 @@ public function test_clone() $cloned_datetime = clone $datetime; // Assert initial state - $this->assert_false($model->attribute_is_dirty($model_attribute)); + $this->assertFalse($model->attribute_is_dirty($model_attribute)); $cloned_datetime->add(new DateInterval('PT1S')); // Assert that modifying the cloned object didn't flag the model - $this->assert_false($model->attribute_is_dirty($model_attribute)); + $this->assertFalse($model->attribute_is_dirty($model_attribute)); $datetime->add(new DateInterval('PT1S')); // Assert that modifying the model-attached object did flag the model - $this->assert_true($model->attribute_is_dirty($model_attribute)); + $this->assertTrue($model->attribute_is_dirty($model_attribute)); // Assert that the dates are equal but not the same instance - $this->assert_equals($datetime, $cloned_datetime); - $this->assert_not_same($datetime, $cloned_datetime); + $this->assertEquals($datetime, $cloned_datetime); + $this->assertNotSame($datetime, $cloned_datetime); } } diff --git a/test/ExpressionsTest.php b/test/ExpressionsTest.php index 54e5b5bd..45c35672 100644 --- a/test/ExpressionsTest.php +++ b/test/ExpressionsTest.php @@ -5,59 +5,58 @@ use ActiveRecord\ConnectionManager; use ActiveRecord\DatabaseException; use ActiveRecord\Expressions; +use PHPUnit\Framework\TestCase; -class ExpressionsTest extends SnakeCase_PHPUnit_Framework_TestCase +class ExpressionsTest extends TestCase { public function test_values() { $c = new Expressions(null, 'a=? and b=?', 1, 2); - $this->assert_equals([1, 2], $c->values()); + $this->assertEquals([1, 2], $c->values()); } public function test_one_variable() { $c = new Expressions(null, 'name=?', 'Tito'); - $this->assert_equals('name=?', $c->to_s()); - $this->assert_equals(['Tito'], $c->values()); + $this->assertEquals('name=?', $c->to_s()); + $this->assertEquals(['Tito'], $c->values()); } public function test_array_variable() { $c = new Expressions(null, 'name IN(?) and id=?', ['Tito', 'George'], 1); - $this->assert_equals([['Tito', 'George'], 1], $c->values()); + $this->assertEquals([['Tito', 'George'], 1], $c->values()); } public function test_multiple_variables() { $c = new Expressions(null, 'name=? and book=?', 'Tito', 'Sharks'); - $this->assert_equals('name=? and book=?', $c->to_s()); - $this->assert_equals(['Tito', 'Sharks'], $c->values()); + $this->assertEquals('name=? and book=?', $c->to_s()); + $this->assertEquals(['Tito', 'Sharks'], $c->values()); } public function test_to_string() { $c = new Expressions(null, 'name=? and book=?', 'Tito', 'Sharks'); - $this->assert_equals('name=? and book=?', $c->to_s()); + $this->assertEquals('name=? and book=?', $c->to_s()); } public function test_to_string_with_array_variable() { $c = new Expressions(null, 'name IN(?) and id=?', ['Tito', 'George'], 1); - $this->assert_equals('name IN(?,?) and id=?', $c->to_s()); + $this->assertEquals('name IN(?,?) and id=?', $c->to_s()); } public function test_to_string_with_null_options() { $c = new Expressions(null, 'name=? and book=?', 'Tito', 'Sharks'); $x = null; - $this->assert_equals('name=? and book=?', $c->to_s(false, $x)); + $this->assertEquals('name=? and book=?', $c->to_s(false, $x)); } - /** - * @expectedException \ActiveRecord\ExpressionsException - */ public function test_insufficient_variables() { + $this->expectException(\ActiveRecord\ExpressionsException::class); $c = new Expressions(null, 'name=? and id=?', 'Tito'); $c->to_s(); } @@ -65,77 +64,77 @@ public function test_insufficient_variables() public function test_no_values() { $c = new Expressions(null, "name='Tito'"); - $this->assert_equals("name='Tito'", $c->to_s()); - $this->assert_equals(0, count($c->values())); + $this->assertEquals("name='Tito'", $c->to_s()); + $this->assertEquals(0, count($c->values())); } public function test_null_variable() { $a = new Expressions(null, 'name=?', null); - $this->assert_equals('name=?', $a->to_s()); - $this->assert_equals([null], $a->values()); + $this->assertEquals('name=?', $a->to_s()); + $this->assertEquals([null], $a->values()); } public function test_zero_variable() { $a = new Expressions(null, 'name=?', 0); - $this->assert_equals('name=?', $a->to_s()); - $this->assert_equals([0], $a->values()); + $this->assertEquals('name=?', $a->to_s()); + $this->assertEquals([0], $a->values()); } public function test_empty_array_variable() { $a = new Expressions(null, 'id IN(?)', []); - $this->assert_equals('id IN(?)', $a->to_s()); - $this->assert_equals([[]], $a->values()); + $this->assertEquals('id IN(?)', $a->to_s()); + $this->assertEquals([[]], $a->values()); } public function test_ignore_invalid_parameter_marker() { $a = new Expressions(null, "question='Do you love backslashes?' and id in(?)", [1, 2]); - $this->assert_equals("question='Do you love backslashes?' and id in(?,?)", $a->to_s()); + $this->assertEquals("question='Do you love backslashes?' and id in(?,?)", $a->to_s()); } public function test_ignore_parameter_marker_with_escaped_quote() { $a = new Expressions(null, "question='Do you love''s backslashes?' and id in(?)", [1, 2]); - $this->assert_equals("question='Do you love''s backslashes?' and id in(?,?)", $a->to_s()); + $this->assertEquals("question='Do you love''s backslashes?' and id in(?,?)", $a->to_s()); } public function test_ignore_parameter_marker_with_backspace_escaped_quote() { $a = new Expressions(null, "question='Do you love\\'s backslashes?' and id in(?)", [1, 2]); - $this->assert_equals("question='Do you love\\'s backslashes?' and id in(?,?)", $a->to_s()); + $this->assertEquals("question='Do you love\\'s backslashes?' and id in(?,?)", $a->to_s()); } public function test_substitute() { $a = new Expressions(null, 'name=? and id=?', 'Tito', 1); - $this->assert_equals("name='Tito' and id=1", $a->to_s(true)); + $this->assertEquals("name='Tito' and id=1", $a->to_s(true)); } public function test_substitute_quotes_scalars_but_not_others() { $a = new Expressions(null, 'id in(?)', [1, '2', 3.5]); - $this->assert_equals("id in(1,'2',3.5)", $a->to_s(true)); + $this->assertEquals("id in(1,'2',3.5)", $a->to_s(true)); } public function test_substitute_where_value_has_question_mark() { $a = new Expressions(null, 'name=? and id=?', '??????', 1); - $this->assert_equals("name='??????' and id=1", $a->to_s(true)); + $this->assertEquals("name='??????' and id=1", $a->to_s(true)); } public function test_substitute_array_value() { $a = new Expressions(null, 'id in(?)', [1, 2]); - $this->assert_equals('id in(1,2)', $a->to_s(true)); + $this->assertEquals('id in(1,2)', $a->to_s(true)); } public function test_substitute_escapes_quotes() { $a = new Expressions(null, 'name=? or name in(?)', "Tito's Guild", [1, "Tito's Guild"]); - $this->assert_equals("name='Tito''s Guild' or name in(1,'Tito''s Guild')", $a->to_s(true)); + $this->assertEquals("name='Tito''s Guild' or name in(1,'Tito''s Guild')", $a->to_s(true)); } public function test_substitute_escape_quotes_with_connections_escape_method() @@ -143,33 +142,31 @@ public function test_substitute_escape_quotes_with_connections_escape_method() try { $conn = ConnectionManager::get_connection(); } catch (DatabaseException $e) { - $this->mark_test_skipped('failed to connect. ' . $e->getMessage()); + $this->markTestSkipped('failed to connect. ' . $e->getMessage()); } $a = new Expressions(null, 'name=?', "Tito's Guild"); $a->set_connection($conn); $escaped = $conn->escape("Tito's Guild"); - $this->assert_equals("name=$escaped", $a->to_s(true)); + $this->assertEquals("name=$escaped", $a->to_s(true)); } public function test_bind() { $a = new Expressions(null, 'name=? and id=?', 'Tito'); $a->bind(2, 1); - $this->assert_equals(['Tito', 1], $a->values()); + $this->assertEquals(['Tito', 1], $a->values()); } public function test_bind_overwrite_existing() { $a = new Expressions(null, 'name=? and id=?', 'Tito', 1); $a->bind(2, 99); - $this->assert_equals(['Tito', 99], $a->values()); + $this->assertEquals(['Tito', 99], $a->values()); } - /** - * @expectedException \ActiveRecord\ExpressionsException - */ public function test_bind_invalid_parameter_number() { + $this->expectException(\ActiveRecord\ExpressionsException::class); $a = new Expressions(null, 'name=?'); $a->bind(0, 99); } @@ -177,32 +174,32 @@ public function test_bind_invalid_parameter_number() public function test_subsitute_using_alternate_values() { $a = new Expressions(null, 'name=?', 'Tito'); - $this->assert_equals("name='Tito'", $a->to_s(true)); + $this->assertEquals("name='Tito'", $a->to_s(true)); $x = ['values' => ['Hocus']]; - $this->assert_equals("name='Hocus'", $a->to_s(true, $x)); + $this->assertEquals("name='Hocus'", $a->to_s(true, $x)); } public function test_null_value() { $a = new Expressions(null, 'name=?', null); - $this->assert_equals('name=NULL', $a->to_s(true)); + $this->assertEquals('name=NULL', $a->to_s(true)); } public function test_hash_with_default_glue() { $a = new Expressions(null, ['id' => 1, 'name' => 'Tito']); - $this->assert_equals('id=? AND name=?', $a->to_s()); + $this->assertEquals('id=? AND name=?', $a->to_s()); } public function test_hash_with_glue() { $a = new Expressions(null, ['id' => 1, 'name' => 'Tito'], ', '); - $this->assert_equals('id=?, name=?', $a->to_s()); + $this->assertEquals('id=?, name=?', $a->to_s()); } public function test_hash_with_array() { $a = new Expressions(null, ['id' => 1, 'name' => ['Tito', 'Mexican']]); - $this->assert_equals('id=? AND name IN(?,?)', $a->to_s()); + $this->assertEquals('id=? AND name IN(?,?)', $a->to_s()); } } diff --git a/test/HasManyThroughTest.php b/test/HasManyThroughTest.php index 008957a5..50a9f649 100644 --- a/test/HasManyThroughTest.php +++ b/test/HasManyThroughTest.php @@ -5,20 +5,20 @@ use foo\bar\biz\Newsletter; use foo\bar\biz\User; -class HasManyThroughTest extends DatabaseTest +class HasManyThroughTest extends DatabaseTestCase { public function test_gh101_has_many_through() { $user = User::find(1); $newsletter = Newsletter::find(1); - $this->assert_equals($newsletter->id, $user->newsletters[0]->id); - $this->assert_equals( + $this->assertEquals($newsletter->id, $user->newsletters[0]->id); + $this->assertEquals( 'foo\bar\biz\Newsletter', get_class($user->newsletters[0]) ); - $this->assert_equals($user->id, $newsletter->users[0]->id); - $this->assert_equals( + $this->assertEquals($user->id, $newsletter->users[0]->id); + $this->assertEquals( 'foo\bar\biz\User', get_class($newsletter->users[0]) ); @@ -32,17 +32,17 @@ public function test_gh101_has_many_through_include() ] ]); - $this->assert_equals(1, $user->id); - $this->assert_equals(1, $user->user_newsletters[0]->id); + $this->assertEquals(1, $user->id); + $this->assertEquals(1, $user->user_newsletters[0]->id); } public function test_gh107_has_many_through_include_eager() { $venue = Venue::find(1, ['include' => ['events']]); - $this->assert_equals(1, $venue->events[0]->id); + $this->assertEquals(1, $venue->events[0]->id); $venue = Venue::find(1, ['include' => ['hosts']]); - $this->assert_equals(1, $venue->hosts[0]->id); + $this->assertEquals(1, $venue->hosts[0]->id); } public function test_gh107_has_many_though_include_eager_with_namespace() @@ -53,8 +53,8 @@ public function test_gh107_has_many_though_include_eager_with_namespace() ] ]); - $this->assert_equals(1, $user->id); - $this->assert_equals(1, $user->newsletters[0]->id); + $this->assertEquals(1, $user->id); + $this->assertEquals(1, $user->newsletters[0]->id); } } // vim: noet ts=4 nobinary diff --git a/test/InflectorTest.php b/test/InflectorTest.php index e1e6ef20..61d34b06 100644 --- a/test/InflectorTest.php +++ b/test/InflectorTest.php @@ -1,28 +1,30 @@ inflector = ActiveRecord\Inflector::instance(); } public function test_underscorify() { - $this->assert_equals('rm__name__bob', $this->inflector->variablize('rm--name bob')); - $this->assert_equals('One_Two_Three', $this->inflector->underscorify('OneTwoThree')); + $this->assertEquals('rm__name__bob', $this->inflector->variablize('rm--name bob')); + $this->assertEquals('One_Two_Three', $this->inflector->underscorify('OneTwoThree')); } public function test_tableize() { - $this->assert_equals('angry_people', $this->inflector->tableize('AngryPerson')); - $this->assert_equals('my_sqls', $this->inflector->tableize('MySQL')); + $this->assertEquals('angry_people', $this->inflector->tableize('AngryPerson')); + $this->assertEquals('my_sqls', $this->inflector->tableize('MySQL')); } public function test_keyify() { - $this->assert_equals('building_type_id', $this->inflector->keyify('BuildingType')); + $this->assertEquals('building_type_id', $this->inflector->keyify('BuildingType')); } } diff --git a/test/ModelCallbackTest.php b/test/ModelCallbackTest.php index d4719b0c..88bd1332 100644 --- a/test/ModelCallbackTest.php +++ b/test/ModelCallbackTest.php @@ -1,10 +1,10 @@ venue = new Venue(); $this->callback = Venue::table()->callback; @@ -34,13 +34,13 @@ public function register_and_invoke_callbacks($callbacks, $return, $closure) public function assert_fires($callbacks, $closure) { $executed = $this->register_and_invoke_callbacks($callbacks, true, $closure); - $this->assert_equals(count((array) $callbacks), count((array) $executed)); + $this->assertEquals(count((array) $callbacks), count((array) $executed)); } public function assert_does_not_fire($callbacks, $closure) { $executed = $this->register_and_invoke_callbacks($callbacks, true, $closure); - $this->assert_equals(0, count($executed)); + $this->assertEquals(0, count($executed)); } public function assert_fires_returns_false($callbacks, $only_fire, $closure) @@ -53,7 +53,7 @@ public function assert_fires_returns_false($callbacks, $only_fire, $closure) sort($only_fire); $intersect = array_intersect($only_fire, $executed); sort($intersect); - $this->assert_equals($only_fire, $intersect); + $this->assertEquals($only_fire, $intersect); } public function test_after_construct_fires_by_default() diff --git a/test/MysqlAdapterTest.php b/test/MysqlAdapterTest.php index 9f9626bc..849aef18 100644 --- a/test/MysqlAdapterTest.php +++ b/test/MysqlAdapterTest.php @@ -4,34 +4,34 @@ require_once __DIR__ . '/../lib/adapters/MysqlAdapter.php'; -class MysqlAdapterTest extends AdapterTest +class MysqlAdapterTest extends AdapterTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up('mysql'); + parent::setUp('mysql'); } public function test_enum() { - $author_columns = $this->conn->columns('authors'); - $this->assert_equals('enum', $author_columns['some_enum']->raw_type); - $this->assert_equals(Column::STRING, $author_columns['some_enum']->type); - $this->assert_same(null, $author_columns['some_enum']->length); + $author_columns = $this->connection->columns('authors'); + $this->assertEquals('enum', $author_columns['some_enum']->raw_type); + $this->assertEquals(Column::STRING, $author_columns['some_enum']->type); + $this->assertSame(null, $author_columns['some_enum']->length); } public function test_set_charset() { $connection_string = ActiveRecord\Config::instance()->get_connection($this->connection_name); $conn = ActiveRecord\Connection::instance($connection_string . '?charset=utf8'); - $this->assert_equals('SET NAMES ?', $conn->last_query); + $this->assertEquals('SET NAMES ?', $conn->last_query); } public function test_limit_with_null_offset_does_not_contain_offset() { $ret = []; $sql = 'SELECT * FROM authors ORDER BY name ASC'; - $this->conn->query_and_fetch($this->conn->limit($sql, null, 1), function ($row) use (&$ret) { $ret[] = $row; }); + $this->connection->query_and_fetch($this->connection->limit($sql, null, 1), function ($row) use (&$ret) { $ret[] = $row; }); - $this->assert_true(false !== strpos($this->conn->last_query, 'LIMIT 1')); + $this->assertTrue(false !== strpos($this->connection->last_query, 'LIMIT 1')); } } diff --git a/test/OciAdapterTest.php b/test/OciAdapterTest.php deleted file mode 100644 index 3c7f7c26..00000000 --- a/test/OciAdapterTest.php +++ /dev/null @@ -1,60 +0,0 @@ -assert_equals('authors_seq', $this->conn->get_sequence_name('authors', 'author_id')); - } - - public function test_columns_text() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_equals('varchar2', $author_columns['some_text']->raw_type); - $this->assert_equals(100, $author_columns['some_text']->length); - } - - public function test_datetime_to_string() - { - $this->assert_equals('01-Jan-2009 01:01:01 AM', $this->conn->datetime_to_string(date_create('2009-01-01 01:01:01 EST'))); - } - - public function test_date_to_string() - { - $this->assert_equals('01-Jan-2009', $this->conn->date_to_string(date_create('2009-01-01 01:01:01 EST'))); - } - - public function test_insert_id() - { - } - - public function test_insert_id_with_params() - { - } - - public function test_insert_id_should_return_explicitly_inserted_id() - { - } - - public function test_columns_time() - { - } - - public function test_columns_sequence() - { - } - - public function test_set_charset() - { - $connection_string = ActiveRecord\Config::instance()->get_connection($this->connection_name); - $conn = ActiveRecord\Connection::instance($connection_string . '?charset=utf8'); - $this->assert_equals(';charset=utf8', $conn->dsn_params); - } -} diff --git a/test/PgsqlAdapterTest.php b/test/PgsqlAdapterTest.php index ae8463a9..cc8343b5 100644 --- a/test/PgsqlAdapterTest.php +++ b/test/PgsqlAdapterTest.php @@ -4,41 +4,41 @@ require_once __DIR__ . '/../lib/adapters/PgsqlAdapter.php'; -class PgsqlAdapterTest extends AdapterTest +class PgsqlAdapterTest extends AdapterTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up('pgsql'); + parent::setUp('pgsql'); } public function test_insert_id() { - $this->conn->query("INSERT INTO authors(author_id,name) VALUES(nextval('authors_author_id_seq'),'name')"); - $this->assert_true($this->conn->insert_id('authors_author_id_seq') > 0); + $this->connection->query("INSERT INTO authors(author_id,name) VALUES(nextval('authors_author_id_seq'),'name')"); + $this->assertTrue($this->connection->insert_id('authors_author_id_seq') > 0); } public function test_insert_id_with_params() { $x = ['name']; - $this->conn->query("INSERT INTO authors(author_id,name) VALUES(nextval('authors_author_id_seq'),?)", $x); - $this->assert_true($this->conn->insert_id('authors_author_id_seq') > 0); + $this->connection->query("INSERT INTO authors(author_id,name) VALUES(nextval('authors_author_id_seq'),?)", $x); + $this->assertTrue($this->connection->insert_id('authors_author_id_seq') > 0); } public function test_insert_id_should_return_explicitly_inserted_id() { - $this->conn->query('INSERT INTO authors(author_id,name) VALUES(99,\'name\')'); - $this->assert_true($this->conn->insert_id('authors_author_id_seq') > 0); + $this->connection->query('INSERT INTO authors(author_id,name) VALUES(99,\'name\')'); + $this->assertTrue($this->connection->insert_id('authors_author_id_seq') > 0); } public function test_set_charset() { $connection_string = ActiveRecord\Config::instance()->get_connection($this->connection_name); $conn = ActiveRecord\Connection::instance($connection_string . '?charset=utf8'); - $this->assert_equals("SET NAMES 'utf8'", $conn->last_query); + $this->assertEquals("SET NAMES 'utf8'", $conn->last_query); } public function test_gh96_columns_not_duplicated_by_index() { - $this->assert_equals(3, $this->conn->query_column_info('user_newsletters')->rowCount()); + $this->assertEquals(3, $this->connection->query_column_info('user_newsletters')->rowCount()); } } diff --git a/test/RelationshipTest.php b/test/RelationshipTest.php index bc12b93a..e17df061 100644 --- a/test/RelationshipTest.php +++ b/test/RelationshipTest.php @@ -11,14 +11,14 @@ class AuthorWithNonModelRelationship extends ActiveRecord\Model public static $has_many = [['books', 'class_name' => 'NotModel']]; } -class RelationshipTest extends DatabaseTest +class RelationshipTest extends DatabaseTestCase { protected $relationship_name; protected $relationship_names = ['has_many', 'belongs_to', 'has_one']; - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up($connection_name); + parent::setUp($connection_name); Event::$belongs_to = [['venue'], ['host']]; Venue::$has_many = [['events', 'order' => 'id asc'], ['hosts', 'through' => 'events', 'order' => 'hosts.id asc']]; @@ -27,7 +27,7 @@ public function set_up($connection_name=null) Host::$has_many = [['events', 'order' => 'id asc']]; foreach ($this->relationship_names as $name) { - if (preg_match("/$name/", $this->getName(), $match)) { + if (preg_match("/$name/", $this->name(), $match)) { $this->relationship_name = $match[0]; } } @@ -58,24 +58,24 @@ protected function get_relationship($type=null) protected function assert_default_belongs_to($event, $association_name='venue') { - $this->assert_true($event->$association_name instanceof Venue); - $this->assert_equals(5, $event->id); - $this->assert_equals('West Chester', $event->$association_name->city); - $this->assert_equals(6, $event->$association_name->id); + $this->assertTrue($event->$association_name instanceof Venue); + $this->assertEquals(5, $event->id); + $this->assertEquals('West Chester', $event->$association_name->city); + $this->assertEquals(6, $event->$association_name->id); } protected function assert_default_has_many($venue, $association_name='events') { - $this->assert_equals(2, $venue->id); - $this->assert_true(count($venue->$association_name) > 1); - $this->assert_equals('Yeah Yeah Yeahs', $venue->{$association_name}[0]->title); + $this->assertEquals(2, $venue->id); + $this->assertTrue(count($venue->$association_name) > 1); + $this->assertEquals('Yeah Yeah Yeahs', $venue->{$association_name}[0]->title); } protected function assert_default_has_one($employee, $association_name='position') { - $this->assert_true($employee->$association_name instanceof Position); - $this->assert_equals('physicist', $employee->$association_name->title); - $this->assert_not_null($employee->id, $employee->$association_name->title); + $this->assertTrue($employee->$association_name instanceof Position); + $this->assertEquals('physicist', $employee->$association_name->title); + $this->assertNotNull($employee->id, $employee->$association_name->title); } public function test_has_many_basic() @@ -102,11 +102,9 @@ public function test_gh_256_eager_loading_three_levels_deep() $this->assertEquals('Yeah Yeah Yeahs', $bill_events[0]->title); } - /** - * @expectedException \ActiveRecord\RelationshipException - */ public function test_joins_on_model_via_undeclared_association() { + $this->expectException(\ActiveRecord\RelationshipException::class); $x = JoinBook::first(['joins' => ['undeclared']]); } @@ -114,14 +112,14 @@ public function test_joins_only_loads_given_model_attributes() { $x = Event::first(['joins' => ['venue']]); $this->assert_sql_has('SELECT events.*', Event::table()->last_sql); - $this->assert_false(array_key_exists('city', $x->attributes())); + $this->assertFalse(array_key_exists('city', $x->attributes())); } public function test_joins_combined_with_select_loads_all_attributes() { $x = Event::first(['select' => 'events.*, venues.city as venue_city', 'joins' => ['venue']]); $this->assert_sql_has('SELECT events.*, venues.city as venue_city', Event::table()->last_sql); - $this->assert_true(array_key_exists('venue_city', $x->attributes())); + $this->assertTrue(array_key_exists('venue_city', $x->attributes())); } public function test_belongs_to_basic() @@ -132,13 +130,13 @@ public function test_belongs_to_basic() public function test_belongs_to_returns_null_when_no_record() { $event = Event::find(6); - $this->assert_null($event->venue); + $this->assertNull($event->venue); } public function test_belongs_to_returns_null_when_foreign_key_is_null() { - $event = Event::create(['title' => 'venueless event']); - $this->assert_null($event->venue); + $event = Event::create(['title' => 'venueless event', 'host_id'=>1]); + $this->assertNull($event->venue); } public function test_belongs_to_with_explicit_class_name() @@ -153,8 +151,8 @@ public function test_belongs_to_with_explicit_foreign_key() Book::$belongs_to = [['explicit_author', 'class_name' => 'Author', 'foreign_key' => 'secondary_author_id']]; $book = Book::find(1); - $this->assert_equals(2, $book->secondary_author_id); - $this->assert_equals($book->secondary_author_id, $book->explicit_author->author_id); + $this->assertEquals(2, $book->secondary_author_id); + $this->assertEquals($book->secondary_author_id, $book->explicit_author->author_id); Book::$belongs_to = $old; } @@ -169,7 +167,7 @@ public function test_belongs_to_with_select() $event->venue->name; $this->fail('expected Exception ActiveRecord\UndefinedPropertyException'); } catch (ActiveRecord\UndefinedPropertyException $e) { - $this->assert_true(false !== strpos($e->getMessage(), 'name')); + $this->assertTrue(false !== strpos($e->getMessage(), 'name')); } } @@ -186,7 +184,7 @@ public function test_belongs_to_with_readonly() } $event->venue->name = 'new name'; - $this->assert_equals($event->venue->name, 'new name'); + $this->assertEquals($event->venue->name, 'new name'); } public function test_belongs_to_with_plural_attribute_name() @@ -199,8 +197,8 @@ public function test_belongs_to_with_conditions_and_non_qualifying_record() { Event::$belongs_to[0]['conditions'] = "state = 'NY'"; $event = $this->get_relationship(); - $this->assert_equals(5, $event->id); - $this->assert_null($event->venue); + $this->assertEquals(5, $event->id); + $this->assertNull($event->venue); } public function test_belongs_to_with_conditions_and_qualifying_record() @@ -214,14 +212,14 @@ public function test_belongs_to_build_association() $event = $this->get_relationship(); $values = ['city' => 'Richmond', 'state' => 'VA']; $venue = $event->build_venue($values); - $this->assert_equals($values, array_intersect_key($values, $venue->attributes())); + $this->assertEquals($values, array_intersect_key($values, $venue->attributes())); } public function test_has_many_build_association() { $author = Author::first(); - $this->assert_equals($author->id, $author->build_books()->author_id); - $this->assert_equals($author->id, $author->build_book()->author_id); + $this->assertEquals($author->id, $author->build_books()->author_id); + $this->assertEquals($author->id, $author->build_book()->author_id); } public function test_belongs_to_create_association() @@ -229,7 +227,7 @@ public function test_belongs_to_create_association() $event = $this->get_relationship(); $values = ['city' => 'Richmond', 'state' => 'VA', 'name' => 'Club 54', 'address' => '123 street']; $venue = $event->create_venue($values); - $this->assert_not_null($venue->id); + $this->assertNotNull($venue->id); } public function test_build_association_overwrites_guarded_foreign_keys() @@ -239,15 +237,15 @@ public function test_build_association_overwrites_guarded_foreign_keys() $book = $author->build_book(); - $this->assert_not_null($book->author_id); + $this->assertNotNull($book->author_id); } public function test_belongs_to_can_be_self_referential() { Author::$belongs_to = [['parent_author', 'class_name' => 'Author', 'foreign_key' => 'parent_author_id']]; $author = Author::find(1); - $this->assert_equals(1, $author->id); - $this->assert_equals(3, $author->parent_author->id); + $this->assertEquals(1, $author->id); + $this->assertEquals(3, $author->parent_author->id); } public function test_belongs_to_with_an_invalid_option() @@ -273,7 +271,7 @@ public function test_has_many_with_select() $venue->events[0]->description; $this->fail('expected Exception ActiveRecord\UndefinedPropertyException'); } catch (ActiveRecord\UndefinedPropertyException $e) { - $this->assert_true(false !== strpos($e->getMessage(), 'description')); + $this->assertTrue(false !== strpos($e->getMessage(), 'description')); } } @@ -290,7 +288,7 @@ public function test_has_many_with_readonly() } $venue->events[0]->description = 'new desc'; - $this->assert_equals($venue->events[0]->description, 'new desc'); + $this->assertEquals($venue->events[0]->description, 'new desc'); } public function test_has_many_with_singular_attribute_name() @@ -303,16 +301,16 @@ public function test_has_many_with_conditions_and_non_qualifying_record() { Venue::$has_many[0]['conditions'] = "title = 'pr0n @ railsconf'"; $venue = $this->get_relationship(); - $this->assert_equals(2, $venue->id); - $this->assert_true(empty($venue->events), is_array($venue->events)); + $this->assertEquals(2, $venue->id); + $this->assertTrue(empty($venue->events), is_array($venue->events)); } public function test_has_many_with_conditions_and_qualifying_record() { Venue::$has_many[0]['conditions'] = "title = 'Yeah Yeah Yeahs'"; $venue = $this->get_relationship(); - $this->assert_equals(2, $venue->id); - $this->assert_equals($venue->events[0]->title, 'Yeah Yeah Yeahs'); + $this->assertEquals(2, $venue->id); + $this->assertEquals($venue->events[0]->title, 'Yeah Yeah Yeahs'); } public function test_has_many_with_sql_clause_options() @@ -323,22 +321,22 @@ public function test_has_many_with_sql_clause_options() 'limit' => 2, 'offset' => 1]; Venue::first()->events; - $this->assert_sql_has($this->conn->limit('SELECT type FROM events WHERE venue_id=? GROUP BY type', 1, 2), Event::table()->last_sql); + $this->assert_sql_has($this->connection->limit('SELECT type FROM events WHERE venue_id=? GROUP BY type', 1, 2), Event::table()->last_sql); } public function test_has_many_through() { $hosts = Venue::find(2)->hosts; - $this->assert_equals(2, $hosts[0]->id); - $this->assert_equals(3, $hosts[1]->id); + $this->assertEquals(2, $hosts[0]->id); + $this->assertEquals(3, $hosts[1]->id); } public function test_gh27_has_many_through_with_explicit_keys() { $property = Property::first(); - $this->assert_equals(1, $property->amenities[0]->amenity_id); - $this->assert_equals(2, $property->amenities[1]->amenity_id); + $this->assertEquals(1, $property->amenities[0]->amenity_id); + $this->assertEquals(2, $property->amenities[1]->amenity_id); } public function test_gh16_has_many_through_inside_a_loop_should_not_cause_an_exception() @@ -349,20 +347,18 @@ public function test_gh16_has_many_through_inside_a_loop_should_not_cause_an_exc $count += count($venue->hosts); } - $this->assert_true($count >= 5); + $this->assertTrue($count >= 5); } - /** - * @expectedException \ActiveRecord\HasManyThroughAssociationException - */ public function test_has_many_through_no_association() { + $this->expectException(\ActiveRecord\HasManyThroughAssociationException::class); Event::$belongs_to = [['host']]; Venue::$has_many[1] = ['hosts', 'through' => 'blahhhhhhh']; $venue = $this->get_relationship(); $n = $venue->hosts; - $this->assert_true(count($n) > 0); + $this->assertTrue(count($n) > 0); } public function test_has_many_through_with_select() @@ -371,8 +367,8 @@ public function test_has_many_through_with_select() Venue::$has_many[1] = ['hosts', 'through' => 'events', 'select' => 'hosts.*, events.*']; $venue = $this->get_relationship(); - $this->assert_true(count($venue->hosts) > 0); - $this->assert_not_null($venue->hosts[0]->title); + $this->assertTrue(count($venue->hosts) > 0); + $this->assertNotNull($venue->hosts[0]->title); } public function test_has_many_through_with_conditions() @@ -381,7 +377,7 @@ public function test_has_many_through_with_conditions() Venue::$has_many[1] = ['hosts', 'through' => 'events', 'conditions' => ['events.title != ?', 'Love Overboard']]; $venue = $this->get_relationship(); - $this->assert_true(1 === count($venue->hosts)); + $this->assertTrue(1 === count($venue->hosts)); $this->assert_sql_has('events.title !=', ActiveRecord\Table::load('Host')->last_sql); } @@ -391,14 +387,12 @@ public function test_has_many_through_using_source() Venue::$has_many[1] = ['hostess', 'through' => 'events', 'source' => 'host']; $venue = $this->get_relationship(); - $this->assert_true(count($venue->hostess) > 0); + $this->assertTrue(count($venue->hostess) > 0); } - /** - * @expectedException \ReflectionException - */ public function test_has_many_through_with_invalid_class_name() { + $this->expectException(\ReflectionException::class); Event::$belongs_to = [['host']]; Venue::$has_one = [['invalid_assoc']]; Venue::$has_many[1] = ['hosts', 'through' => 'invalid_assoc']; @@ -419,10 +413,10 @@ public function test_has_many_with_explicit_keys() $author = Author::find(4); foreach ($author->explicit_books as $book) { - $this->assert_equals($book->secondary_author_id, $author->parent_author_id); + $this->assertEquals($book->secondary_author_id, $author->parent_author_id); } - $this->assert_true(false !== strpos(ActiveRecord\Table::load('Book')->last_sql, 'secondary_author_id')); + $this->assertTrue(false !== strpos(ActiveRecord\Table::load('Book')->last_sql, 'secondary_author_id')); Author::$has_many = $old; } @@ -447,7 +441,7 @@ public function test_has_one_with_select() $employee->position->active; $this->fail('expected Exception ActiveRecord\UndefinedPropertyException'); } catch (ActiveRecord\UndefinedPropertyException $e) { - $this->assert_true(false !== strpos($e->getMessage(), 'active')); + $this->assertTrue(false !== strpos($e->getMessage(), 'active')); } } @@ -463,8 +457,8 @@ public function test_has_one_with_conditions_and_non_qualifying_record() { Employee::$has_one[0]['conditions'] = "title = 'programmer'"; $employee = $this->get_relationship(); - $this->assert_equals(1, $employee->id); - $this->assert_null($employee->position); + $this->assertEquals(1, $employee->id); + $this->assertNull($employee->position); } public function test_has_one_with_conditions_and_qualifying_record() @@ -486,15 +480,15 @@ public function test_has_one_with_readonly() } $employee->position->title = 'new title'; - $this->assert_equals($employee->position->title, 'new title'); + $this->assertEquals($employee->position->title, 'new title'); } public function test_has_one_can_be_self_referential() { Author::$has_one[1] = ['parent_author', 'class_name' => 'Author', 'foreign_key' => 'parent_author_id']; $author = Author::find(1); - $this->assert_equals(1, $author->id); - $this->assert_equals(3, $author->parent_author->id); + $this->assertEquals(1, $author->id); + $this->assertEquals(3, $author->parent_author->id); } public function test_has_one_with_joins() @@ -508,34 +502,32 @@ public function test_has_one_with_explicit_keys() Book::$has_one = [['explicit_author', 'class_name' => 'Author', 'foreign_key' => 'parent_author_id', 'primary_key' => 'secondary_author_id']]; $book = Book::find(1); - $this->assert_equals($book->secondary_author_id, $book->explicit_author->parent_author_id); - $this->assert_true(false !== strpos(ActiveRecord\Table::load('Author')->last_sql, 'parent_author_id')); + $this->assertEquals($book->secondary_author_id, $book->explicit_author->parent_author_id); + $this->assertTrue(false !== strpos(ActiveRecord\Table::load('Author')->last_sql, 'parent_author_id')); } public function test_dont_attempt_to_load_if_all_foreign_keys_are_null() { $event = new Event(); $event->venue; - $this->assert_sql_doesnt_has($this->conn->last_query, 'is IS NULL'); + $this->assert_sql_doesnt_has($this->connection->last_query, 'is IS NULL'); } public function test_relationship_on_table_with_underscores() { - $this->assert_equals(1, Author::find(1)->awesome_person->is_awesome); + $this->assertEquals(1, Author::find(1)->awesome_person->is_awesome); } public function test_has_one_through() { Venue::$has_many = [['events'], ['hosts', 'through' => 'events']]; $venue = Venue::first(); - $this->assert_true(count($venue->hosts) > 0); + $this->assertTrue(count($venue->hosts) > 0); } - /** - * @expectedException \ActiveRecord\RelationshipException - */ public function test_throw_error_if_relationship_is_not_a_model() { + $this->expectException(\ActiveRecord\RelationshipException::class); AuthorWithNonModelRelationship::first()->books; } @@ -545,7 +537,7 @@ public function test_gh93_and_gh100_eager_loading_respects_association_options() $venues = Venue::find([2, 6], ['include' => 'events']); $this->assert_sql_has('WHERE length(title) = ? AND venue_id IN(?,?) ORDER BY id asc', ActiveRecord\Table::load('Event')->last_sql); - $this->assert_equals(1, count($venues[0]->events)); + $this->assertEquals(1, count($venues[0]->events)); } public function test_eager_loading_has_many_x() @@ -554,10 +546,10 @@ public function test_eager_loading_has_many_x() $this->assert_sql_has('WHERE venue_id IN(?,?)', ActiveRecord\Table::load('Event')->last_sql); foreach ($venues[0]->events as $event) { - $this->assert_equals($event->venue_id, $venues[0]->id); + $this->assertEquals($event->venue_id, $venues[0]->id); } - $this->assert_equals(2, count($venues[0]->events)); + $this->assertEquals(2, count($venues[0]->events)); } public function test_eager_loading_has_many_with_no_related_rows() @@ -565,7 +557,7 @@ public function test_eager_loading_has_many_with_no_related_rows() $venues = Venue::find([7, 8], ['include' => 'events']); foreach ($venues as $v) { - $this->assert_true(empty($v->events)); + $this->assertTrue(empty($v->events)); } $this->assert_sql_has('WHERE id IN(?,?)', ActiveRecord\Table::load('Venue')->last_sql); @@ -580,15 +572,15 @@ public function test_eager_loading_has_many_array_of_includes() $assocs = ['books', 'awesome_people']; foreach ($assocs as $assoc) { - $this->assert_internal_type('array', $authors[0]->$assoc); + $this->assertIsArray($authors[0]->$assoc); foreach ($authors[0]->$assoc as $a) { - $this->assert_equals($authors[0]->author_id, $a->author_id); + $this->assertEquals($authors[0]->author_id, $a->author_id); } } foreach ($assocs as $assoc) { - $this->assert_internal_type('array', $authors[1]->$assoc); + $this->assertIsArray($authors[1]->$assoc); } $this->assert_sql_has('WHERE author_id IN(?,?)', ActiveRecord\Table::load('Author')->last_sql); @@ -600,14 +592,14 @@ public function test_eager_loading_has_many_nested() { $venues = Venue::find([1, 2], ['include' => ['events' => ['host']]]); - $this->assert_equals(2, count($venues)); + $this->assertEquals(2, count($venues)); foreach ($venues as $v) { - $this->assert_true(count($v->events) > 0); + $this->assertTrue(count($v->events) > 0); foreach ($v->events as $e) { - $this->assert_equals($e->host_id, $e->host->id); - $this->assert_equals($v->id, $e->venue_id); + $this->assertEquals($e->host_id, $e->host->id); + $this->assertEquals($v->id, $e->venue_id); } } @@ -621,7 +613,7 @@ public function test_eager_loading_belongs_to() $events = Event::find([1, 2, 3, 5, 7], ['include' => 'venue']); foreach ($events as $event) { - $this->assert_equals($event->venue_id, $event->venue->id); + $this->assertEquals($event->venue_id, $event->venue->id); } $this->assert_sql_has('WHERE id IN(?,?,?,?,?)', ActiveRecord\Table::load('Venue')->last_sql); @@ -632,8 +624,8 @@ public function test_eager_loading_belongs_to_array_of_includes() $events = Event::find([1, 2, 3, 5, 7], ['include' => ['venue', 'host']]); foreach ($events as $event) { - $this->assert_equals($event->venue_id, $event->venue->id); - $this->assert_equals($event->host_id, $event->host->id); + $this->assertEquals($event->venue_id, $event->venue->id); + $this->assertEquals($event->host_id, $event->host->id); } $this->assert_sql_has('WHERE id IN(?,?,?,?,?)', ActiveRecord\Table::load('Event')->last_sql); @@ -650,8 +642,8 @@ public function test_eager_loading_belongs_to_nested() $assocs = ['author', 'awesome_people']; foreach ($books as $book) { - $this->assert_equals($book->author_id, $book->author->author_id); - $this->assert_equals($book->author->author_id, $book->author->awesome_people[0]->author_id); + $this->assertEquals($book->author_id, $book->author->author_id); + $this->assertEquals($book->author->author_id, $book->author->awesome_people[0]->author_id); } $this->assert_sql_has('WHERE book_id IN(?,?)', ActiveRecord\Table::load('Book')->last_sql); @@ -667,7 +659,7 @@ public function test_eager_loading_belongs_to_with_no_related_rows() $events = Event::find([$e1->id, $e2->id], ['include' => 'venue']); foreach ($events as $e) { - $this->assert_null($e->venue); + $this->assertNull($e->venue); } $this->assert_sql_has('WHERE id IN(?,?)', ActiveRecord\Table::load('Event')->last_sql); @@ -681,9 +673,9 @@ public function test_eager_loading_clones_related_objects() $venue = $events[0]->venue; $venue->name = 'new name'; - $this->assert_equals($venue->id, $events[1]->venue->id); - $this->assert_not_equals($venue->name, $events[1]->venue->name); - $this->assert_not_equals(spl_object_hash($venue), spl_object_hash($events[1]->venue)); + $this->assertEquals($venue->id, $events[1]->venue->id); + $this->assertNotEquals($venue->name, $events[1]->venue->name); + $this->assertNotEquals(spl_object_hash($venue), spl_object_hash($events[1]->venue)); } public function test_eager_loading_clones_nested_related_objects() @@ -694,9 +686,9 @@ public function test_eager_loading_clones_nested_related_objects() $changed_host = $venues[3]->events[0]->host; $changed_host->name = 'changed'; - $this->assert_equals($changed_host->id, $unchanged_host->id); - $this->assert_not_equals($changed_host->name, $unchanged_host->name); - $this->assert_not_equals(spl_object_hash($changed_host), spl_object_hash($unchanged_host)); + $this->assertEquals($changed_host->id, $unchanged_host->id); + $this->assertNotEquals($changed_host->name, $unchanged_host->name); + $this->assertNotEquals(spl_object_hash($changed_host), spl_object_hash($unchanged_host)); } public function test_gh_23_relationships_with_joins_to_same_table_should_alias_table_name() @@ -714,9 +706,9 @@ public function test_gh_23_relationships_with_joins_to_same_table_should_alias_t $book = Book::find(2, ['joins' => ['to', 'from_', 'another'], 'select' => $select]); - $this->assert_not_null($book->from_author_name); - $this->assert_not_null($book->to_author_name); - $this->assert_not_null($book->another_author_name); + $this->assertNotNull($book->from_author_name); + $this->assertNotNull($book->to_author_name); + $this->assertNotNull($book->another_author_name); Book::$belongs_to = $old; } @@ -724,14 +716,12 @@ public function test_gh_40_relationships_with_joins_aliases_table_name_in_condit { $event = Event::find(1, ['joins' => ['venue']]); - $this->assert_equals($event->id, $event->venue->id); + $this->assertEquals($event->id, $event->venue->id); } - /** - * @expectedException \ActiveRecord\RecordNotFound - */ public function test_dont_attempt_eager_load_when_record_does_not_exist() { + $this->expectException(\ActiveRecord\RecordNotFound::class); Author::find(999999, ['include' => ['books']]); } } diff --git a/test/SQLBuilderTest.php b/test/SQLBuilderTest.php index 33afe447..6f7a8355 100644 --- a/test/SQLBuilderTest.php +++ b/test/SQLBuilderTest.php @@ -3,16 +3,16 @@ use ActiveRecord\SQLBuilder; use ActiveRecord\Table; -class SQLBuilderTest extends DatabaseTest +class SQLBuilderTest extends DatabaseTestCase { protected $table_name = 'authors'; protected $class_name = 'Author'; protected $table; - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up($connection_name); - $this->sql = new SQLBuilder($this->conn, $this->table_name); + parent::setUp($connection_name); + $this->sql = new SQLBuilder($this->connection, $this->table_name); $this->table = Table::load($this->class_name); } @@ -27,100 +27,98 @@ public function assert_conditions($expected_sql, $values, $underscored_string, $ $this->assert_sql_has($expected_sql, array_shift($cond)); if ($values) { - $this->assert_equals(array_values(array_filter($values, function ($s) { return null !== $s; })), array_values($cond)); + $this->assertEquals(array_values(array_filter($values, function ($s) { return null !== $s; })), array_values($cond)); } else { - $this->assert_equals([], $cond); + $this->assertEquals([], $cond); } } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_no_connection() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); new SQLBuilder(null, 'authors'); } public function test_nothing() { - $this->assert_equals('SELECT * FROM authors', (string) $this->sql); + $this->assertEquals('SELECT * FROM authors', (string) $this->sql); } public function test_where_with_array() { $this->sql->where('id=? AND name IN(?)', 1, ['Tito', 'Mexican']); $this->assert_sql_has('SELECT * FROM authors WHERE id=? AND name IN(?,?)', (string) $this->sql); - $this->assert_equals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); + $this->assertEquals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); } public function test_where_with_hash() { $this->sql->where(['id' => 1, 'name' => 'Tito']); $this->assert_sql_has('SELECT * FROM authors WHERE id=? AND name=?', (string) $this->sql); - $this->assert_equals([1, 'Tito'], $this->sql->get_where_values()); + $this->assertEquals([1, 'Tito'], $this->sql->get_where_values()); } public function test_where_with_hash_and_array() { $this->sql->where(['id' => 1, 'name' => ['Tito', 'Mexican']]); $this->assert_sql_has('SELECT * FROM authors WHERE id=? AND name IN(?,?)', (string) $this->sql); - $this->assert_equals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); + $this->assertEquals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); } public function test_gh134_where_with_hash_and_null() { $this->sql->where(['id' => 1, 'name' => null]); $this->assert_sql_has('SELECT * FROM authors WHERE id=? AND name IS ?', (string) $this->sql); - $this->assert_equals([1, null], $this->sql->get_where_values()); + $this->assertEquals([1, null], $this->sql->get_where_values()); } public function test_where_with_null() { $this->sql->where(null); - $this->assert_equals('SELECT * FROM authors', (string) $this->sql); + $this->assertEquals('SELECT * FROM authors', (string) $this->sql); } public function test_where_with_no_args() { $this->sql->where(); - $this->assert_equals('SELECT * FROM authors', (string) $this->sql); + $this->assertEquals('SELECT * FROM authors', (string) $this->sql); } public function test_order() { $this->sql->order('name'); - $this->assert_equals('SELECT * FROM authors ORDER BY name', (string) $this->sql); + $this->assertEquals('SELECT * FROM authors ORDER BY name', (string) $this->sql); } public function test_limit() { $this->sql->limit(10)->offset(1); - $this->assert_equals($this->conn->limit('SELECT * FROM authors', 1, 10), (string) $this->sql); + $this->assertEquals($this->connection->limit('SELECT * FROM authors', 1, 10), (string) $this->sql); } public function test_select() { $this->sql->select('id,name'); - $this->assert_equals('SELECT id,name FROM authors', (string) $this->sql); + $this->assertEquals('SELECT id,name FROM authors', (string) $this->sql); } public function test_joins() { $join = 'inner join books on(authors.id=books.author_id)'; $this->sql->joins($join); - $this->assert_equals("SELECT * FROM authors $join", (string) $this->sql); + $this->assertEquals("SELECT * FROM authors $join", (string) $this->sql); } public function test_group() { $this->sql->group('name'); - $this->assert_equals('SELECT * FROM authors GROUP BY name', (string) $this->sql); + $this->assertEquals('SELECT * FROM authors GROUP BY name', (string) $this->sql); } public function test_having() { $this->sql->having("created_at > '2009-01-01'"); - $this->assert_equals("SELECT * FROM authors HAVING created_at > '2009-01-01'", (string) $this->sql); + $this->assertEquals("SELECT * FROM authors HAVING created_at > '2009-01-01'", (string) $this->sql); } public function test_all_clauses_after_where_should_be_correctly_ordered() @@ -130,14 +128,12 @@ public function test_all_clauses_after_where_should_be_correctly_ordered() $this->sql->order('name'); $this->sql->group('name'); $this->sql->where(['id' => 1]); - $this->assert_sql_has($this->conn->limit("SELECT * FROM authors WHERE id=? GROUP BY name HAVING created_at > '2009-01-01' ORDER BY name", 1, 10), (string) $this->sql); + $this->assert_sql_has($this->connection->limit("SELECT * FROM authors WHERE id=? GROUP BY name HAVING created_at > '2009-01-01' ORDER BY name", 1, 10), (string) $this->sql); } - /** - * @expectedException \ActiveRecord\ActiveRecordException - */ public function test_insert_requires_hash() { + $this->expectException(\ActiveRecord\ActiveRecordException::class); $this->sql->insert([1]); } @@ -157,13 +153,13 @@ public function test_update_with_hash() { $this->sql->update(['id' => 1, 'name' => 'Tito'])->where('id=1 AND name IN(?)', ['Tito', 'Mexican']); $this->assert_sql_has('UPDATE authors SET id=?, name=? WHERE id=1 AND name IN(?,?)', (string) $this->sql); - $this->assert_equals([1, 'Tito', 'Tito', 'Mexican'], $this->sql->bind_values()); + $this->assertEquals([1, 'Tito', 'Tito', 'Mexican'], $this->sql->bind_values()); } public function test_update_with_limit_and_order() { - if (!$this->conn->accepts_limit_and_order_for_update_and_delete()) { - $this->mark_test_skipped('Only MySQL & Sqlite accept limit/order with UPDATE operation'); + if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { + $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with UPDATE operation'); } $this->sql->update(['id' => 1])->order('name asc')->limit(1); @@ -185,27 +181,27 @@ public function test_update_with_null() public function test_delete() { $this->sql->delete(); - $this->assert_equals('DELETE FROM authors', $this->sql->to_s()); + $this->assertEquals('DELETE FROM authors', $this->sql->to_s()); } public function test_delete_with_where() { $this->sql->delete('id=? or name in(?)', 1, ['Tito', 'Mexican']); - $this->assert_equals('DELETE FROM authors WHERE id=? or name in(?,?)', $this->sql->to_s()); - $this->assert_equals([1, 'Tito', 'Mexican'], $this->sql->bind_values()); + $this->assertEquals('DELETE FROM authors WHERE id=? or name in(?,?)', $this->sql->to_s()); + $this->assertEquals([1, 'Tito', 'Mexican'], $this->sql->bind_values()); } public function test_delete_with_hash() { $this->sql->delete(['id' => 1, 'name' => ['Tito', 'Mexican']]); $this->assert_sql_has('DELETE FROM authors WHERE id=? AND name IN(?,?)', $this->sql->to_s()); - $this->assert_equals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); + $this->assertEquals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); } public function test_delete_with_limit_and_order() { - if (!$this->conn->accepts_limit_and_order_for_update_and_delete()) { - $this->mark_test_skipped('Only MySQL & Sqlite accept limit/order with DELETE operation'); + if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { + $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with DELETE operation'); } $this->sql->delete(['id' => 1])->order('name asc')->limit(1); @@ -214,13 +210,13 @@ public function test_delete_with_limit_and_order() public function test_reverse_order() { - $this->assert_equals('id ASC, name DESC', SQLBuilder::reverse_order('id DESC, name ASC')); - $this->assert_equals('id ASC, name DESC , zzz ASC', SQLBuilder::reverse_order('id DESC, name ASC , zzz DESC')); - $this->assert_equals('id DESC, name DESC', SQLBuilder::reverse_order('id, name')); - $this->assert_equals('id DESC', SQLBuilder::reverse_order('id')); - $this->assert_equals('', SQLBuilder::reverse_order('')); - $this->assert_equals(' ', SQLBuilder::reverse_order(' ')); - $this->assert_equals(null, SQLBuilder::reverse_order(null)); + $this->assertEquals('id ASC, name DESC', SQLBuilder::reverse_order('id DESC, name ASC')); + $this->assertEquals('id ASC, name DESC , zzz ASC', SQLBuilder::reverse_order('id DESC, name ASC , zzz DESC')); + $this->assertEquals('id DESC, name DESC', SQLBuilder::reverse_order('id, name')); + $this->assertEquals('id DESC', SQLBuilder::reverse_order('id')); + $this->assertEquals('', SQLBuilder::reverse_order('')); + $this->assertEquals(' ', SQLBuilder::reverse_order(' ')); + $this->assertEquals(null, SQLBuilder::reverse_order(null)); } public function test_create_conditions_from_underscored_string() @@ -248,8 +244,8 @@ public function test_create_conditions_from_underscored_string_with_blank() public function test_create_conditions_from_underscored_string_invalid() { - $this->assert_equals(null, $this->cond_from_s('')); - $this->assert_equals(null, $this->cond_from_s(null)); + $this->assertEquals(null, $this->cond_from_s('')); + $this->assertEquals(null, $this->cond_from_s(null)); } public function test_create_conditions_from_underscored_string_with_mapped_columns() @@ -261,7 +257,7 @@ public function test_create_hash_from_underscored_string() { $values = [1, 'Tito']; $hash = SQLBuilder::create_hash_from_underscored_string('id_and_my_name', $values); - $this->assert_equals(['id' => 1, 'my_name' => 'Tito'], $hash); + $this->assertEquals(['id' => 1, 'my_name' => 'Tito'], $hash); } public function test_create_hash_from_underscored_string_with_mapped_columns() @@ -269,7 +265,7 @@ public function test_create_hash_from_underscored_string_with_mapped_columns() $values = [1, 'Tito']; $map = ['my_name' => 'name']; $hash = SQLBuilder::create_hash_from_underscored_string('id_and_my_name', $values, $map); - $this->assert_equals(['id' => 1, 'name' => 'Tito'], $hash); + $this->assertEquals(['id' => 1, 'name' => 'Tito'], $hash); } public function test_where_with_joins_prepends_table_name_to_fields() diff --git a/test/SerializationTest.php b/test/SerializationTest.php index a1309ee3..3cf0c09e 100644 --- a/test/SerializationTest.php +++ b/test/SerializationTest.php @@ -4,11 +4,11 @@ use ActiveRecord\DateTime; -class SerializationTest extends DatabaseTest +class SerializationTest extends DatabaseTestCase { - public function tear_down() + public function tearDown(): void { - parent::tear_down(); + parent::tearDown(); ActiveRecord\ArraySerializer::$include_root = false; ActiveRecord\JsonSerializer::$include_root = false; } @@ -26,45 +26,49 @@ public function _a($options=[], $model=null) public function test_only() { - $this->assert_has_keys('name', 'special', $this->_a(['only' => ['name', 'special']])); + $this->assertArrayHasKey('special', $this->_a(['only' => ['name', 'special']])); + $this->assertArrayHasKey('name', $this->_a(['only' => ['name', 'special']])); } public function test_only_not_array() { - $this->assert_has_keys('name', $this->_a(['only' => 'name'])); + $this->assertArrayHasKey('name', $this->_a(['only' => 'name'])); } public function test_only_should_only_apply_to_attributes() { - $this->assert_has_keys('name', 'author', $this->_a(['only' => 'name', 'include' => 'author'])); - $this->assert_has_keys('book_id', 'upper_name', $this->_a(['only' => 'book_id', 'methods' => 'upper_name'])); + $this->assertArrayHasKey('author', $this->_a(['only' => 'name', 'include' => 'author'])); + $this->assertArrayHasKey('name', $this->_a(['only' => 'name', 'include' => 'author'])); + $this->assertArrayHasKey('book_id', $this->_a(['only' => 'book_id', 'methods' => 'upper_name'])); + $this->assertArrayHasKey('upper_name', $this->_a(['only' => 'book_id', 'methods' => 'upper_name'])); } public function test_only_overrides_except() { - $this->assert_has_keys('name', $this->_a(['only' => 'name', 'except' => 'name'])); + $this->assertArrayHasKey('name', $this->_a(['only' => 'name', 'except' => 'name'])); } public function test_except() { - $this->assert_doesnt_has_keys('name', 'special', $this->_a(['except' => ['name', 'special']])); + $this->assertArrayNotHasKey('name', $this->_a(['except' => ['name', 'special']])); + $this->assertArrayNotHasKey('special', $this->_a(['except' => ['name', 'special']])); } public function test_except_takes_a_string() { - $this->assert_doesnt_has_keys('name', $this->_a(['except' => 'name'])); + $this->assertArrayNotHasKey('name', $this->_a(['except' => 'name'])); } public function test_methods() { $a = $this->_a(['methods' => ['upper_name']]); - $this->assert_equals('ANCIENT ART OF MAIN TANKING', $a['upper_name']); + $this->assertEquals('ANCIENT ART OF MAIN TANKING', $a['upper_name']); } public function test_methods_takes_a_string() { $a = $this->_a(['methods' => 'upper_name']); - $this->assert_equals('ANCIENT ART OF MAIN TANKING', $a['upper_name']); + $this->assertEquals('ANCIENT ART OF MAIN TANKING', $a['upper_name']); } // methods added last should we shuld have value of the method in our json @@ -72,13 +76,13 @@ public function test_methods_takes_a_string() public function test_methods_method_same_as_attribute() { $a = $this->_a(['methods' => 'name']); - $this->assert_equals('ancient art of main tanking', $a['name']); + $this->assertEquals('ancient art of main tanking', $a['name']); } public function test_include() { $a = $this->_a(['include' => ['author']]); - $this->assert_has_keys('parent_author_id', $a['author']); + $this->assertArrayHasKey('parent_author_id', $a['author']); } public function test_include_nested_with_nested_options() @@ -87,29 +91,29 @@ public function test_include_nested_with_nested_options() ['include' => ['events' => ['except' => 'title', 'include' => ['host' => ['only' => 'id']]]]], Host::find(4)); - $this->assert_equals(3, count($a['events'])); - $this->assert_doesnt_has_keys('title', $a['events'][0]); - $this->assert_equals(['id' => 4], $a['events'][0]['host']); + $this->assertEquals(3, count($a['events'])); + $this->assertArrayNotHasKey('title', $a['events'][0]); + $this->assertEquals(['id' => 4], $a['events'][0]['host']); } public function test_datetime_values_get_converted_to_strings() { $now = new DateTime(); $a = $this->_a(['only' => 'created_at'], new Author(['created_at' => $now])); - $this->assert_equals($now->format(ActiveRecord\Serialization::$DATETIME_FORMAT), $a['created_at']); + $this->assertEquals($now->format(ActiveRecord\Serialization::$DATETIME_FORMAT), $a['created_at']); } public function test_to_json() { $book = Book::find(1); $json = $book->to_json(); - $this->assert_equals($book->attributes(), (array) json_decode($json)); + $this->assertEquals($book->attributes(), (array) json_decode($json)); } public function test_to_json_include_root() { ActiveRecord\JsonSerializer::$include_root = true; - $this->assert_not_null(json_decode(Book::find(1)->to_json())->book); + $this->assertNotNull(json_decode(Book::find(1)->to_json())->book); } public function test_to_xml_include() @@ -117,20 +121,20 @@ public function test_to_xml_include() $xml = Host::find(4)->to_xml(['include' => 'events']); $decoded = get_object_vars(new SimpleXMLElement($xml)); - $this->assert_equals(3, count($decoded['events']->event)); + $this->assertEquals(3, count($decoded['events']->event)); } public function test_to_xml() { $book = Book::find(1); - $this->assert_equals($book->attributes(), get_object_vars(new SimpleXMLElement($book->to_xml()))); + $this->assertEquals($book->attributes(), get_object_vars(new SimpleXMLElement($book->to_xml()))); } public function test_to_array() { $book = Book::find(1); $array = $book->to_array(); - $this->assert_equals($book->attributes(), $array); + $this->assertEquals($book->attributes(), $array); } public function test_to_array_include_root() @@ -139,7 +143,7 @@ public function test_to_array_include_root() $book = Book::find(1); $array = $book->to_array(); $book_attributes = ['book' => $book->attributes()]; - $this->assert_equals($book_attributes, $array); + $this->assertEquals($book_attributes, $array); } public function test_to_array_except() @@ -148,37 +152,37 @@ public function test_to_array_except() $array = $book->to_array(['except' => ['special']]); $book_attributes = $book->attributes(); unset($book_attributes['special']); - $this->assert_equals($book_attributes, $array); + $this->assertEquals($book_attributes, $array); } public function test_works_with_datetime() { Author::find(1)->update_attribute('created_at', new DateTime()); - $this->assert_reg_exp('/[0-9]{4}-[0-9]{2}-[0-9]{2}/', Author::find(1)->to_xml()); - $this->assert_reg_exp('/"updated_at":"[0-9]{4}-[0-9]{2}-[0-9]{2}/', Author::find(1)->to_json()); + $this->assertMatchesRegularExpression('/[0-9]{4}-[0-9]{2}-[0-9]{2}/', Author::find(1)->to_xml()); + $this->assertMatchesRegularExpression('/"updated_at":"[0-9]{4}-[0-9]{2}-[0-9]{2}/', Author::find(1)->to_json()); } public function test_to_xml_skip_instruct() { - $this->assert_same(false, strpos(Book::find(1)->to_xml(['skip_instruct' => true]), 'assert_same(0, strpos(Book::find(1)->to_xml(['skip_instruct' => false]), 'assertSame(false, strpos(Book::find(1)->to_xml(['skip_instruct' => true]), 'assertSame(0, strpos(Book::find(1)->to_xml(['skip_instruct' => false]), 'assert_contains('lasers', Author::first()->to_xml(['only_method' => 'return_something'])); + $this->assertStringContainsString('lasers', Author::first()->to_xml(['only_method' => 'return_something'])); } public function test_to_csv() { $book = Book::find(1); - $this->assert_equals('1,1,2,"Ancient Art of Main Tanking",0,0', $book->to_csv()); + $this->assertEquals('1,1,2,"Ancient Art of Main Tanking",0,0', $book->to_csv()); } public function test_to_csv_only_header() { $book = Book::find(1); - $this->assert_equals('book_id,author_id,secondary_author_id,name,numeric_test,special', + $this->assertEquals('book_id,author_id,secondary_author_id,name,numeric_test,special', $book->to_csv(['only_header'=>true]) ); } @@ -186,7 +190,7 @@ public function test_to_csv_only_header() public function test_to_csv_only_method() { $book = Book::find(1); - $this->assert_equals('2,"Ancient Art of Main Tanking"', + $this->assertEquals('2,"Ancient Art of Main Tanking"', $book->to_csv(['only'=>['name', 'secondary_author_id']]) ); } @@ -194,7 +198,7 @@ public function test_to_csv_only_method() public function test_to_csv_only_method_on_header() { $book = Book::find(1); - $this->assert_equals('secondary_author_id,name', + $this->assertEquals('secondary_author_id,name', $book->to_csv(['only'=>['secondary_author_id', 'name'], 'only_header'=>true]) ); @@ -204,7 +208,7 @@ public function test_to_csv_with_custom_delimiter() { $book = Book::find(1); ActiveRecord\CsvSerializer::$delimiter=';'; - $this->assert_equals('1;1;2;"Ancient Art of Main Tanking";0;0', $book->to_csv()); + $this->assertEquals('1;1;2;"Ancient Art of Main Tanking";0;0', $book->to_csv()); } public function test_to_csv_with_custom_enclosure() @@ -212,6 +216,6 @@ public function test_to_csv_with_custom_enclosure() $book = Book::find(1); ActiveRecord\CsvSerializer::$delimiter=','; ActiveRecord\CsvSerializer::$enclosure="'"; - $this->assert_equals("1,1,2,'Ancient Art of Main Tanking',0,0", $book->to_csv()); + $this->assertEquals("1,1,2,'Ancient Art of Main Tanking',0,0", $book->to_csv()); } } diff --git a/test/SqliteAdapterTest.php b/test/SqliteAdapterTest.php index b783e5d0..fb98cac7 100644 --- a/test/SqliteAdapterTest.php +++ b/test/SqliteAdapterTest.php @@ -2,17 +2,15 @@ require_once __DIR__ . '/../lib/adapters/SqliteAdapter.php'; -class SqliteAdapterTest extends AdapterTest +class SqliteAdapterTest extends AdapterTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up('sqlite'); + parent::setUp('sqlite'); } public function tearDown(): void { - parent::tearDown(); - @unlink(self::InvalidDb); } @@ -37,44 +35,45 @@ public function test_limit_with_null_offset_does_not_contain_offset() { $ret = []; $sql = 'SELECT * FROM authors ORDER BY name ASC'; - $this->conn->query_and_fetch($this->conn->limit($sql, null, 1), function ($row) use (&$ret) { $ret[] = $row; }); + $this->connection->query_and_fetch($this->connection->limit($sql, null, 1), function ($row) use (&$ret) { $ret[] = $row; }); - $this->assert_true(false !== strpos($this->conn->last_query, 'LIMIT 1')); + $this->assertTrue(false !== strpos($this->connection->last_query, 'LIMIT 1')); } public function test_gh183_sqliteadapter_autoincrement() { // defined in lowercase: id integer not null primary key - $columns = $this->conn->columns('awesome_people'); - $this->assert_true($columns['id']->auto_increment); + $columns = $this->connection->columns('awesome_people'); + $this->assertTrue($columns['id']->auto_increment); // defined in uppercase: `amenity_id` INTEGER NOT NULL PRIMARY KEY - $columns = $this->conn->columns('amenities'); - $this->assert_true($columns['amenity_id']->auto_increment); + $columns = $this->connection->columns('amenities'); + $this->assertTrue($columns['amenity_id']->auto_increment); // defined using int: `rm-id` INT NOT NULL - $columns = $this->conn->columns('`rm-bldg`'); - $this->assert_false($columns['rm-id']->auto_increment); + $columns = $this->connection->columns('`rm-bldg`'); + $this->assertFalse($columns['rm-id']->auto_increment); // defined using int: id INT NOT NULL PRIMARY KEY - $columns = $this->conn->columns('hosts'); - $this->assert_true($columns['id']->auto_increment); + $columns = $this->connection->columns('hosts'); + $this->assertTrue($columns['id']->auto_increment); } public function test_datetime_to_string() { $datetime = '2009-01-01 01:01:01'; - $this->assert_equals($datetime, $this->conn->datetime_to_string(date_create($datetime))); + $this->assertEquals($datetime, $this->connection->datetime_to_string(date_create($datetime))); } public function test_date_to_string() { $datetime = '2009-01-01'; - $this->assert_equals($datetime, $this->conn->date_to_string(date_create($datetime))); + $this->assertEquals($datetime, $this->connection->date_to_string(date_create($datetime))); } // not supported public function test_connect_with_port() { + $this->expectNotToPerformAssertions(); } } diff --git a/test/UtilsTest.php b/test/UtilsTest.php index f151e98f..d65ba48f 100644 --- a/test/UtilsTest.php +++ b/test/UtilsTest.php @@ -1,10 +1,11 @@ object_array = [null, null]; $this->object_array[0] = new stdClass(); @@ -21,43 +22,43 @@ public function set_up() public function test_collect_with_array_of_objects_using_closure() { - $this->assert_equals(['0a', '1a'], AR\collect($this->object_array, function ($obj) { return $obj->a; })); + $this->assertEquals(['0a', '1a'], AR\collect($this->object_array, function ($obj) { return $obj->a; })); } public function test_collect_with_array_of_objects_using_string() { - $this->assert_equals(['0a', '1a'], AR\collect($this->object_array, 'a')); + $this->assertEquals(['0a', '1a'], AR\collect($this->object_array, 'a')); } public function test_collect_with_array_hash_using_closure() { - $this->assert_equals(['0a', '1a'], AR\collect($this->array_hash, function ($item) { return $item['a']; })); + $this->assertEquals(['0a', '1a'], AR\collect($this->array_hash, function ($item) { return $item['a']; })); } public function test_collect_with_array_hash_using_string() { - $this->assert_equals(['0a', '1a'], AR\collect($this->array_hash, 'a')); + $this->assertEquals(['0a', '1a'], AR\collect($this->array_hash, 'a')); } public function test_array_flatten() { - $this->assert_equals([], AR\array_flatten([])); - $this->assert_equals([1], AR\array_flatten([1])); - $this->assert_equals([1], AR\array_flatten([[1]])); - $this->assert_equals([1, 2], AR\array_flatten([[1, 2]])); - $this->assert_equals([1, 2], AR\array_flatten([[1], 2])); - $this->assert_equals([1, 2], AR\array_flatten([1, [2]])); - $this->assert_equals([1, 2, 3], AR\array_flatten([1, [2], 3])); - $this->assert_equals([1, 2, 3, 4], AR\array_flatten([1, [2, 3], 4])); - $this->assert_equals([1, 2, 3, 4, 5, 6], AR\array_flatten([1, [2, 3], 4, [5, 6]])); + $this->assertEquals([], AR\array_flatten([])); + $this->assertEquals([1], AR\array_flatten([1])); + $this->assertEquals([1], AR\array_flatten([[1]])); + $this->assertEquals([1, 2], AR\array_flatten([[1, 2]])); + $this->assertEquals([1, 2], AR\array_flatten([[1], 2])); + $this->assertEquals([1, 2], AR\array_flatten([1, [2]])); + $this->assertEquals([1, 2, 3], AR\array_flatten([1, [2], 3])); + $this->assertEquals([1, 2, 3, 4], AR\array_flatten([1, [2, 3], 4])); + $this->assertEquals([1, 2, 3, 4, 5, 6], AR\array_flatten([1, [2, 3], 4, [5, 6]])); } public function test_all() { - $this->assert_true(AR\all(null, [null, null])); - $this->assert_true(AR\all(1, [1, 1])); - $this->assert_false(AR\all(1, [1, '1'])); - $this->assert_false(AR\all(null, ['', null])); + $this->assertTrue(AR\all(null, [null, null])); + $this->assertTrue(AR\all(1, [1, 1])); + $this->assertFalse(AR\all(1, [1, '1'])); + $this->assertFalse(AR\all(null, ['', null])); } public function test_classify() @@ -70,7 +71,7 @@ public function test_classify() $class_names[] = AR\classify($s); } - $this->assert_equals($class_names, $good_class_names); + $this->assertEquals($class_names, $good_class_names); } public function test_classify_singularize() @@ -83,26 +84,26 @@ public function test_classify_singularize() $class_names[] = AR\classify($s, true); } - $this->assert_equals($class_names, $good_class_names); + $this->assertEquals($class_names, $good_class_names); } public function test_singularize() { - $this->assert_equals('order_status', AR\Utils::singularize('order_status')); - $this->assert_equals('order_status', AR\Utils::singularize('order_statuses')); - $this->assert_equals('os_type', AR\Utils::singularize('os_type')); - $this->assert_equals('os_type', AR\Utils::singularize('os_types')); - $this->assert_equals('photo', AR\Utils::singularize('photos')); - $this->assert_equals('pass', AR\Utils::singularize('pass')); - $this->assert_equals('pass', AR\Utils::singularize('passes')); + $this->assertEquals('order_status', AR\Utils::singularize('order_status')); + $this->assertEquals('order_status', AR\Utils::singularize('order_statuses')); + $this->assertEquals('os_type', AR\Utils::singularize('os_type')); + $this->assertEquals('os_type', AR\Utils::singularize('os_types')); + $this->assertEquals('photo', AR\Utils::singularize('photos')); + $this->assertEquals('pass', AR\Utils::singularize('pass')); + $this->assertEquals('pass', AR\Utils::singularize('passes')); } public function test_wrap_strings_in_arrays() { $x = ['1', ['2']]; - $this->assert_equals([['1'], ['2']], ActiveRecord\wrap_strings_in_arrays($x)); + $this->assertEquals([['1'], ['2']], ActiveRecord\wrap_strings_in_arrays($x)); $x = '1'; - $this->assert_equals([['1']], ActiveRecord\wrap_strings_in_arrays($x)); + $this->assertEquals([['1']], ActiveRecord\wrap_strings_in_arrays($x)); } } diff --git a/test/ValidatesFormatOfTest.php b/test/ValidatesFormatOfTest.php index ba7db1d5..247297d3 100644 --- a/test/ValidatesFormatOfTest.php +++ b/test/ValidatesFormatOfTest.php @@ -8,11 +8,11 @@ class BookFormat extends ActiveRecord\Model ]; } -class ValidatesFormatOfTest extends DatabaseTest +class ValidatesFormatOfTest extends DatabaseTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up($connection_name); + parent::setUp($connection_name); BookFormat::$validates_format_of[0] = ['name']; } @@ -21,12 +21,12 @@ public function test_format() BookFormat::$validates_format_of[0]['with'] = '/^[a-z\W]*$/'; $book = new BookFormat(['author_id' => 1, 'name' => 'testing reg']); $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); BookFormat::$validates_format_of[0]['with'] = '/[0-9]/'; $book = new BookFormat(['author_id' => 1, 'name' => 12]); $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_invalid_null() @@ -35,7 +35,7 @@ public function test_invalid_null() $book = new BookFormat(); $book->name = null; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); } public function test_invalid_blank() @@ -44,7 +44,7 @@ public function test_invalid_blank() $book = new BookFormat(); $book->name = ''; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); } public function test_valid_blank_andallow_blank() @@ -53,7 +53,7 @@ public function test_valid_blank_andallow_blank() BookFormat::$validates_format_of[0]['with'] = '/[^0-9]/'; $book = new BookFormat(['author_id' => 1, 'name' => '']); $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_valid_null_and_allow_null() @@ -64,24 +64,20 @@ public function test_valid_null_and_allow_null() $book->author_id = 1; $book->name = null; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } - /** - * @expectedException \ActiveRecord\ValidationsArgumentError - */ public function test_invalid_lack_of_with_key() { + $this->expectException(\ActiveRecord\ValidationsArgumentError::class); $book = new BookFormat(); $book->name = null; $book->save(); } - /** - * @expectedException \ActiveRecord\ValidationsArgumentError - */ public function test_invalid_with_expression_as_non_string() { + $this->expectException(\ActiveRecord\ValidationsArgumentError::class); BookFormat::$validates_format_of[0]['with'] = ['test']; $book = new BookFormat(); $book->name = null; @@ -94,7 +90,7 @@ public function test_invalid_with_expression_as_non_regexp() $book = new BookFormat(); $book->name = 'blah'; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); } public function test_custom_message() @@ -105,6 +101,6 @@ public function test_custom_message() $book = new BookFormat(); $book->name = null; $book->save(); - $this->assert_equals('is using a custom message.', $book->errors->on('name')); + $this->assertEquals('is using a custom message.', $book->errors->on('name')); } } diff --git a/test/ValidatesInclusionAndExclusionOfTest.php b/test/ValidatesInclusionAndExclusionOfTest.php index 9eab089a..6e66e381 100644 --- a/test/ValidatesInclusionAndExclusionOfTest.php +++ b/test/ValidatesInclusionAndExclusionOfTest.php @@ -16,11 +16,11 @@ class BookInclusion extends ActiveRecord\Model ]; } -class ValidatesInclusionAndExclusionOfTest extends DatabaseTest +class ValidatesInclusionAndExclusionOfTest extends DatabaseTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up($connection_name); + parent::setUp($connection_name); BookInclusion::$validates_inclusion_of[0] = ['name', 'in' => ['blah', 'tanker', 'shark']]; BookExclusion::$validates_exclusion_of[0] = ['name', 'in' => ['blah', 'alpha', 'bravo']]; } @@ -30,7 +30,7 @@ public function test_inclusion() $book = new BookInclusion(); $book->name = 'blah'; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_exclusion() @@ -38,7 +38,7 @@ public function test_exclusion() $book = new BookExclusion(); $book->name = 'blahh'; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_invalid_inclusion() @@ -46,10 +46,10 @@ public function test_invalid_inclusion() $book = new BookInclusion(); $book->name = 'thanker'; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); $book->name = 'alpha '; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); } public function test_invalid_exclusion() @@ -57,12 +57,12 @@ public function test_invalid_exclusion() $book = new BookExclusion(); $book->name = 'alpha'; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); $book = new BookExclusion(); $book->name = 'bravo'; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); } public function test_inclusion_with_numeric() @@ -71,7 +71,7 @@ public function test_inclusion_with_numeric() $book = new BookInclusion(); $book->name = 2; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_inclusion_with_boolean() @@ -80,7 +80,7 @@ public function test_inclusion_with_boolean() $book = new BookInclusion(); $book->name = true; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_inclusion_with_null() @@ -89,7 +89,7 @@ public function test_inclusion_with_null() $book = new BookInclusion(); $book->name = null; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_invalid_inclusion_with_numeric() @@ -98,7 +98,7 @@ public function test_invalid_inclusion_with_numeric() $book = new BookInclusion(); $book->name = 5; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); } public function tes_inclusion_within_option() @@ -107,7 +107,7 @@ public function tes_inclusion_within_option() $book = new BookInclusion(); $book->name = 'okay'; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function tes_inclusion_scalar_value() @@ -116,7 +116,7 @@ public function tes_inclusion_scalar_value() $book = new BookInclusion(); $book->name = 'okay'; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_valid_null() @@ -125,7 +125,7 @@ public function test_valid_null() $book = new BookInclusion(); $book->name = null; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_valid_blank() @@ -134,7 +134,7 @@ public function test_valid_blank() $book = new BookInclusion(); $book->name = ''; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_custom_message() @@ -146,10 +146,10 @@ public function test_custom_message() $book = new BookInclusion(); $book->name = 'not included'; $book->save(); - $this->assert_equals('is using a custom message.', $book->errors->on('name')); + $this->assertEquals('is using a custom message.', $book->errors->on('name')); $book = new BookExclusion(); $book->name = 'bravo'; $book->save(); - $this->assert_equals('is using a custom message.', $book->errors->on('name')); + $this->assertEquals('is using a custom message.', $book->errors->on('name')); } } diff --git a/test/ValidatesLengthOfTest.php b/test/ValidatesLengthOfTest.php index 60ad343a..29a456ba 100644 --- a/test/ValidatesLengthOfTest.php +++ b/test/ValidatesLengthOfTest.php @@ -12,11 +12,11 @@ class BookSize extends ActiveRecord\Model public static $validates_size_of = []; } -class ValidatesLengthOfTest extends DatabaseTest +class ValidatesLengthOfTest extends DatabaseTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up($connection_name); + parent::setUp($connection_name); BookLength::$validates_length_of[0] = ['name', 'allow_blank' => false, 'allow_null' => false]; } @@ -26,7 +26,7 @@ public function test_within() $book = new BookLength(); $book->name = '12345'; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_within_error_message() @@ -35,11 +35,11 @@ public function test_within_error_message() $book = new BookLength(); $book->name = '1'; $book->is_valid(); - $this->assert_equals(['Name is too short (minimum is 2 characters)'], $book->errors->full_messages()); + $this->assertEquals(['Name is too short (minimum is 2 characters)'], $book->errors->full_messages()); $book->name = '123456'; $book->is_valid(); - $this->assert_equals(['Name is too long (maximum is 5 characters)'], $book->errors->full_messages()); + $this->assertEquals(['Name is too long (maximum is 5 characters)'], $book->errors->full_messages()); } public function test_within_custom_error_message() @@ -50,11 +50,11 @@ public function test_within_custom_error_message() $book = new BookLength(); $book->name = '1'; $book->is_valid(); - $this->assert_equals(['Name is not between 2 and 5 characters'], $book->errors->full_messages()); + $this->assertEquals(['Name is not between 2 and 5 characters'], $book->errors->full_messages()); $book->name = '123456'; $book->is_valid(); - $this->assert_equals(['Name is not between 2 and 5 characters'], $book->errors->full_messages()); + $this->assertEquals(['Name is not between 2 and 5 characters'], $book->errors->full_messages()); } public function test_valid_in() @@ -63,7 +63,7 @@ public function test_valid_in() $book = new BookLength(); $book->name = '12345'; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_aliased_size_of() @@ -73,7 +73,7 @@ public function test_aliased_size_of() $book = new BookSize(); $book->name = '12345'; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_invalid_within_and_in() @@ -82,14 +82,14 @@ public function test_invalid_within_and_in() $book = new BookLength(); $book->name = 'four'; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); - $this->set_up(); + $this->setUp(); BookLength::$validates_length_of[0]['in'] = [1, 3]; $book = new BookLength(); $book->name = 'four'; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); + $this->assertTrue($book->errors->is_invalid('name')); } public function test_valid_null() @@ -100,7 +100,7 @@ public function test_valid_null() $book = new BookLength(); $book->name = null; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_valid_blank() @@ -111,7 +111,7 @@ public function test_valid_blank() $book = new BookLength(); $book->name = ''; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_invalid_blank() @@ -121,8 +121,8 @@ public function test_invalid_blank() $book = new BookLength(); $book->name = ''; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); - $this->assert_equals('is too short (minimum is 1 characters)', $book->errors->on('name')); + $this->assertTrue($book->errors->is_invalid('name')); + $this->assertEquals('is too short (minimum is 1 characters)', $book->errors->on('name')); } public function test_invalid_null_within() @@ -132,8 +132,8 @@ public function test_invalid_null_within() $book = new BookLength(); $book->name = null; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); - $this->assert_equals('is too short (minimum is 1 characters)', $book->errors->on('name')); + $this->assertTrue($book->errors->is_invalid('name')); + $this->assertEquals('is too short (minimum is 1 characters)', $book->errors->on('name')); } public function test_invalid_null_minimum() @@ -143,8 +143,8 @@ public function test_invalid_null_minimum() $book = new BookLength(); $book->name = null; $book->save(); - $this->assert_true($book->errors->is_invalid('name')); - $this->assert_equals('is too short (minimum is 1 characters)', $book->errors->on('name')); + $this->assertTrue($book->errors->is_invalid('name')); + $this->assertEquals('is too short (minimum is 1 characters)', $book->errors->on('name')); } public function test_valid_null_maximum() @@ -154,7 +154,7 @@ public function test_valid_null_maximum() $book = new BookLength(); $book->name = null; $book->save(); - $this->assert_false($book->errors->is_invalid('name')); + $this->assertFalse($book->errors->is_invalid('name')); } public function test_float_as_impossible_range_option() @@ -165,17 +165,17 @@ public function test_float_as_impossible_range_option() try { $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('maximum value cannot use a float for length.', $e->getMessage()); + $this->assertEquals('maximum value cannot use a float for length.', $e->getMessage()); } - $this->set_up(); + $this->setUp(); BookLength::$validates_length_of[0]['is'] = 1.8; $book = new BookLength(); $book->name = '123'; try { $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('is value cannot use a float for length.', $e->getMessage()); + $this->assertEquals('is value cannot use a float for length.', $e->getMessage()); return; } @@ -192,7 +192,7 @@ public function test_signed_integer_as_impossible_within_option() try { $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('minimum value cannot use a signed integer.', $e->getMessage()); + $this->assertEquals('minimum value cannot use a signed integer.', $e->getMessage()); return; } @@ -208,17 +208,17 @@ public function test_not_array_as_impossible_range_option() try { $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('within must be an array composing a range of numbers with key [0] being less than key [1]', $e->getMessage()); + $this->assertEquals('within must be an array composing a range of numbers with key [0] being less than key [1]', $e->getMessage()); } - $this->set_up(); + $this->setUp(); BookLength::$validates_length_of[0]['in'] = 'string'; $book = new BookLength(); $book->name = '123'; try { $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('in must be an array composing a range of numbers with key [0] being less than key [1]', $e->getMessage()); + $this->assertEquals('in must be an array composing a range of numbers with key [0] being less than key [1]', $e->getMessage()); return; } @@ -235,7 +235,7 @@ public function test_signed_integer_as_impossible_is_option() try { $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('is value cannot use a signed integer.', $e->getMessage()); + $this->assertEquals('is value cannot use a signed integer.', $e->getMessage()); return; } @@ -250,7 +250,7 @@ public function test_lack_of_option() $book->name = null; $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('Range unspecified. Specify the [within], [maximum], or [is] option.', $e->getMessage()); + $this->assertEquals('Range unspecified. Specify the [within], [maximum], or [is] option.', $e->getMessage()); return; } @@ -268,7 +268,7 @@ public function test_too_many_options() $book->name = null; $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('Too many range options specified. Choose only one.', $e->getMessage()); + $this->assertEquals('Too many range options specified. Choose only one.', $e->getMessage()); return; } @@ -286,7 +286,7 @@ public function test_too_many_options_with_different_option_types() $book->name = null; $book->save(); } catch (ActiveRecord\ValidationsArgumentError $e) { - $this->assert_equals('Too many range options specified. Choose only one.', $e->getMessage()); + $this->assertEquals('Too many range options specified. Choose only one.', $e->getMessage()); return; } @@ -294,11 +294,9 @@ public function test_too_many_options_with_different_option_types() $this->fail('An expected exception has not be raised.'); } - /** - * @expectedException \ActiveRecord\ValidationsArgumentError - */ public function test_with_option_as_non_numeric() { + $this->expectException(\ActiveRecord\ValidationsArgumentError::class); BookLength::$validates_length_of[0]['with'] = ['test']; $book = new BookLength(); @@ -306,11 +304,9 @@ public function test_with_option_as_non_numeric() $book->save(); } - /** - * @expectedException \ActiveRecord\ValidationsArgumentError - */ public function test_with_option_as_non_numeric_non_array() { + $this->expectException(\ActiveRecord\ValidationsArgumentError::class); BookLength::$validates_length_of[0]['with'] = 'test'; $book = new BookLength(); @@ -323,7 +319,7 @@ public function test_validates_length_of_maximum() BookLength::$validates_length_of[0] = ['name', 'maximum' => 10]; $book = new BookLength(['name' => '12345678901']); $book->is_valid(); - $this->assert_equals(['Name is too long (maximum is 10 characters)'], $book->errors->full_messages()); + $this->assertEquals(['Name is too long (maximum is 10 characters)'], $book->errors->full_messages()); } public function test_validates_length_of_minimum() @@ -331,7 +327,7 @@ public function test_validates_length_of_minimum() BookLength::$validates_length_of[0] = ['name', 'minimum' => 2]; $book = new BookLength(['name' => '1']); $book->is_valid(); - $this->assert_equals(['Name is too short (minimum is 2 characters)'], $book->errors->full_messages()); + $this->assertEquals(['Name is too short (minimum is 2 characters)'], $book->errors->full_messages()); } public function test_validates_length_of_min_max_custom_message() @@ -339,12 +335,12 @@ public function test_validates_length_of_min_max_custom_message() BookLength::$validates_length_of[0] = ['name', 'maximum' => 10, 'message' => 'is far too long']; $book = new BookLength(['name' => '12345678901']); $book->is_valid(); - $this->assert_equals(['Name is far too long'], $book->errors->full_messages()); + $this->assertEquals(['Name is far too long'], $book->errors->full_messages()); BookLength::$validates_length_of[0] = ['name', 'minimum' => 10, 'message' => 'is far too short']; $book = new BookLength(['name' => '123456789']); $book->is_valid(); - $this->assert_equals(['Name is far too short'], $book->errors->full_messages()); + $this->assertEquals(['Name is far too short'], $book->errors->full_messages()); } public function test_validates_length_of_min_max_custom_message_overridden() @@ -352,7 +348,7 @@ public function test_validates_length_of_min_max_custom_message_overridden() BookLength::$validates_length_of[0] = ['name', 'minimum' => 10, 'too_short' => 'is too short', 'message' => 'is custom message']; $book = new BookLength(['name' => '123456789']); $book->is_valid(); - $this->assert_equals(['Name is custom message'], $book->errors->full_messages()); + $this->assertEquals(['Name is custom message'], $book->errors->full_messages()); } public function test_validates_length_of_is() @@ -360,6 +356,6 @@ public function test_validates_length_of_is() BookLength::$validates_length_of[0] = ['name', 'is' => 2]; $book = new BookLength(['name' => '123']); $book->is_valid(); - $this->assert_equals(['Name is the wrong length (should be 2 characters)'], $book->errors->full_messages()); + $this->assertEquals(['Name is the wrong length (should be 2 characters)'], $book->errors->full_messages()); } } diff --git a/test/ValidatesNumericalityOfTest.php b/test/ValidatesNumericalityOfTest.php index 18efd009..ea514144 100644 --- a/test/ValidatesNumericalityOfTest.php +++ b/test/ValidatesNumericalityOfTest.php @@ -9,7 +9,7 @@ class BookNumericality extends ActiveRecord\Model ]; } -class ValidatesNumericalityOfTest extends DatabaseTest +class ValidatesNumericalityOfTest extends DatabaseTestCase { public static $NULL = [null]; public static $BLANK = ['', ' ', " \t \r \n"]; @@ -19,9 +19,9 @@ class ValidatesNumericalityOfTest extends DatabaseTest public static $INTEGERS = [0, 10, -10]; public static $JUNK = ['not a number', '42 not a number', '00-1', '--3', '+-3', '+3-1', '-+019.0', '12.12.13.12', "123\nnot a number"]; - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up($connection_name); + parent::setUp($connection_name); BookNumericality::$validates_numericality_of = [ ['numeric_test'] ]; @@ -33,14 +33,14 @@ private function assert_validity($value, $boolean, $msg=null) $book->numeric_test = $value; if ('valid' == $boolean) { - $this->assert_true($book->save()); - $this->assert_false($book->errors->is_invalid('numeric_test')); + $this->assertTrue($book->save()); + $this->assertFalse($book->errors->is_invalid('numeric_test')); } else { - $this->assert_false($book->save()); - $this->assert_true($book->errors->is_invalid('numeric_test')); + $this->assertFalse($book->save()); + $this->assertTrue($book->errors->is_invalid('numeric_test')); if (!is_null($msg)) { - $this->assert_same($msg, $book->errors->on('numeric_test')); + $this->assertSame($msg, $book->errors->on('numeric_test')); } } } @@ -156,7 +156,7 @@ public function test_custom_message() ]; $book = new BookNumericality(['numeric_test' => 'NaN']); $book->is_valid(); - $this->assert_equals(['Numeric test Hello'], $book->errors->full_messages()); + $this->assertEquals(['Numeric test Hello'], $book->errors->full_messages()); } } diff --git a/test/ValidatesPresenceOfTest.php b/test/ValidatesPresenceOfTest.php index ff85fa82..c31a285c 100644 --- a/test/ValidatesPresenceOfTest.php +++ b/test/ValidatesPresenceOfTest.php @@ -18,42 +18,42 @@ class AuthorPresence extends ActiveRecord\Model ]; } -class ValidatesPresenceOfTest extends DatabaseTest +class ValidatesPresenceOfTest extends DatabaseTestCase { public function test_presence() { $book = new BookPresence(['name' => 'blah']); - $this->assert_false($book->is_invalid()); + $this->assertFalse($book->is_invalid()); } public function test_presence_on_date_field_is_valid() { $author = new AuthorPresence(['some_date' => '2010-01-01']); - $this->assert_true($author->is_valid()); + $this->assertTrue($author->is_valid()); } public function test_presence_on_date_field_is_not_valid() { $author = new AuthorPresence(); - $this->assert_false($author->is_valid()); + $this->assertFalse($author->is_valid()); } public function test_invalid_null() { $book = new BookPresence(['name' => null]); - $this->assert_true($book->is_invalid()); + $this->assertTrue($book->is_invalid()); } public function test_invalid_blank() { $book = new BookPresence(['name' => '']); - $this->assert_true($book->is_invalid()); + $this->assertTrue($book->is_invalid()); } public function test_valid_white_space() { $book = new BookPresence(['name' => ' ']); - $this->assert_false($book->is_invalid()); + $this->assertFalse($book->is_invalid()); } public function test_custom_message() @@ -62,12 +62,12 @@ public function test_custom_message() $book = new BookPresence(['name' => null]); $book->is_valid(); - $this->assert_equals('is using a custom message.', $book->errors->on('name')); + $this->assertEquals('is using a custom message.', $book->errors->on('name')); } public function test_valid_zero() { $book = new BookPresence(['name' => 0]); - $this->assert_true($book->is_valid()); + $this->assertTrue($book->is_valid()); } } diff --git a/test/ValidationsTest.php b/test/ValidationsTest.php index c5b48621..b06aaa0f 100644 --- a/test/ValidationsTest.php +++ b/test/ValidationsTest.php @@ -25,11 +25,11 @@ class ValuestoreValidations extends ActiveRecord\Model public static $validates_uniqueness_of = []; } -class ValidationsTest extends DatabaseTest +class ValidationsTest extends DatabaseTestCase { - public function set_up($connection_name=null) + public function setUp($connection_name=null): void { - parent::set_up($connection_name); + parent::setUp($connection_name); BookValidations::$validates_presence_of[0] = 'name'; BookValidations::$validates_uniqueness_of[0] = 'name'; @@ -40,33 +40,33 @@ public function set_up($connection_name=null) public function test_is_valid_invokes_validations() { $book = new Book(); - $this->assert_true(empty($book->errors)); + $this->assertTrue(empty($book->errors)); $book->is_valid(); - $this->assert_false(empty($book->errors)); + $this->assertFalse(empty($book->errors)); } public function test_is_valid_returns_true_if_no_validations_exist() { $book = new Book(); - $this->assert_true($book->is_valid()); + $this->assertTrue($book->is_valid()); } public function test_is_valid_returns_false_if_failed_validations() { $book = new BookValidations(); - $this->assert_false($book->is_valid()); + $this->assertFalse($book->is_valid()); } public function test_is_invalid() { $book = new Book(); - $this->assert_false($book->is_invalid()); + $this->assertFalse($book->is_invalid()); } public function test_is_invalid_is_true() { $book = new BookValidations(); - $this->assert_true($book->is_invalid()); + $this->assertTrue($book->is_invalid()); } public function test_is_iterable() @@ -75,7 +75,7 @@ public function test_is_iterable() $book->is_valid(); foreach ($book->errors as $name => $message) { - $this->assert_equals("Name can't be blank", $message); + $this->assertEquals("Name can't be blank", $message); } } @@ -84,7 +84,7 @@ public function test_full_messages() $book = new BookValidations(); $book->is_valid(); - $this->assert_equals(["Name can't be blank"], array_values($book->errors->full_messages(['hash' => true]))); + $this->assertEquals(["Name can't be blank"], array_values($book->errors->full_messages(['hash' => true]))); } public function test_to_array() @@ -92,7 +92,7 @@ public function test_to_array() $book = new BookValidations(); $book->is_valid(); - $this->assert_equals(['name' => ["Name can't be blank"]], $book->errors->to_array()); + $this->assertEquals(['name' => ["Name can't be blank"]], $book->errors->to_array()); } public function test_toString() @@ -101,7 +101,7 @@ public function test_toString() $book->is_valid(); $book->errors->add('secondary_author_id', 'is invalid'); - $this->assert_equals("Name can't be blank\nSecondary author id is invalid", (string) $book->errors); + $this->assertEquals("Name can't be blank\nSecondary author id is invalid", (string) $book->errors); } public function test_validates_uniqueness_of() @@ -109,14 +109,14 @@ public function test_validates_uniqueness_of() BookValidations::create(['name' => 'bob']); $book = BookValidations::create(['name' => 'bob']); - $this->assert_equals(['Name must be unique'], $book->errors->full_messages()); - $this->assert_equals(1, BookValidations::count(['conditions' => "name='bob'"])); + $this->assertEquals(['Name must be unique'], $book->errors->full_messages()); + $this->assertEquals(1, BookValidations::count(['conditions' => "name='bob'"])); } public function test_validates_uniqueness_of_excludes_self() { $book = BookValidations::first(); - $this->assert_equals(true, $book->is_valid()); + $this->assertEquals(true, $book->is_valid()); } public function test_validates_uniqueness_of_with_multiple_fields() @@ -124,7 +124,7 @@ public function test_validates_uniqueness_of_with_multiple_fields() BookValidations::$validates_uniqueness_of[0] = [['name', 'special']]; $book1 = BookValidations::first(); $book2 = new BookValidations(['name' => $book1->name, 'special' => $book1->special+1]); - $this->assert_true($book2->is_valid()); + $this->assertTrue($book2->is_valid()); } public function test_validates_uniqueness_of_with_multiple_fields_is_not_unique() @@ -132,16 +132,16 @@ public function test_validates_uniqueness_of_with_multiple_fields_is_not_unique( BookValidations::$validates_uniqueness_of[0] = [['name', 'special']]; $book1 = BookValidations::first(); $book2 = new BookValidations(['name' => $book1->name, 'special' => $book1->special]); - $this->assert_false($book2->is_valid()); - $this->assert_equals(['Name and special must be unique'], $book2->errors->full_messages()); + $this->assertFalse($book2->is_valid()); + $this->assertEquals(['Name and special must be unique'], $book2->errors->full_messages()); } public function test_validates_uniqueness_of_works_with_alias_attribute() { BookValidations::$validates_uniqueness_of[0] = [['name_alias', 'x']]; $book = BookValidations::create(['name_alias' => 'Another Book', 'x' => 2]); - $this->assert_false($book->is_valid()); - $this->assert_equals(['Name alias and x must be unique'], $book->errors->full_messages()); + $this->assertFalse($book->is_valid()); + $this->assertEquals(['Name alias and x must be unique'], $book->errors->full_messages()); } public function test_validates_uniqueness_of_works_with_mysql_reserved_word_as_column_name() @@ -149,35 +149,35 @@ public function test_validates_uniqueness_of_works_with_mysql_reserved_word_as_c ValuestoreValidations::create(['key' => 'GA_KEY', 'value' => 'UA-1234567-1']); $valuestore = ValuestoreValidations::create(['key' => 'GA_KEY', 'value' => 'UA-1234567-2']); - $this->assert_equals(['Key must be unique'], $valuestore->errors->full_messages()); - $this->assert_equals(1, ValuestoreValidations::count(['conditions' => "`key`='GA_KEY'"])); + $this->assertEquals(['Key must be unique'], $valuestore->errors->full_messages()); + $this->assertEquals(1, ValuestoreValidations::count(['conditions' => "`key`='GA_KEY'"])); } public function test_get_validation_rules() { $validators = BookValidations::first()->get_validation_rules(); - $this->assert_true(in_array(['validator' => 'validates_presence_of'], $validators['name'])); + $this->assertTrue(in_array(['validator' => 'validates_presence_of'], $validators['name'])); } public function test_model_is_nulled_out_to_prevent_memory_leak() { $book = new BookValidations(); $book->is_valid(); - $this->assert_true(false !== strpos(serialize($book->errors), 'model";N;')); + $this->assertTrue(false !== strpos(serialize($book->errors), 'model";N;')); } public function test_validations_takes_strings() { BookValidations::$validates_presence_of = ['numeric_test', ['special'], 'name']; $book = new BookValidations(['numeric_test' => 1, 'special' => 1]); - $this->assert_false($book->is_valid()); + $this->assertFalse($book->is_valid()); } public function test_gh131_custom_validation() { $book = new BookValidations(['name' => 'test_custom_validation']); $book->save(); - $this->assert_true($book->errors->is_invalid('name')); - $this->assert_equals(BookValidations::$custom_validator_error_msg, $book->errors->on('name')); + $this->assertTrue($book->errors->is_invalid('name')); + $this->assertEquals(BookValidations::$custom_validator_error_msg, $book->errors->on('name')); } } diff --git a/test/helpers/AdapterTest.php b/test/helpers/AdapterTest.php deleted file mode 100644 index f7817849..00000000 --- a/test/helpers/AdapterTest.php +++ /dev/null @@ -1,416 +0,0 @@ -get_connection($connection_name)) { - $this->mark_test_skipped($connection_name . ' drivers are not present'); - } - - parent::set_up($connection_name); - } - - public function test_i_has_a_default_port_unless_im_sqlite() - { - if ($this->conn instanceof ActiveRecord\SqliteAdapter) { - return; - } - - $c = $this->conn; - $this->assert_true($c::$DEFAULT_PORT > 0); - } - - public function test_should_set_adapter_variables() - { - $this->assert_not_null($this->conn->protocol); - } - - public function test_null_connection_string_uses_default_connection() - { - $this->assert_not_null(ActiveRecord\Connection::instance(null)); - $this->assert_not_null(ActiveRecord\Connection::instance('')); - $this->assert_not_null(ActiveRecord\Connection::instance()); - } - - /** - * @expectedException \ActiveRecord\DatabaseException - */ - public function test_invalid_connection_protocol() - { - ActiveRecord\Connection::instance('terribledb://user:pass@host/db'); - } - - /** - * @expectedException \ActiveRecord\DatabaseException - */ - public function test_no_host_connection() - { - if (!$GLOBALS['slow_tests']) { - throw new ActiveRecord\DatabaseException(''); - } - ActiveRecord\Connection::instance("{$this->conn->protocol}://user:pass"); - } - - /** - * @expectedException \ActiveRecord\DatabaseException - */ - public function test_connection_failed_invalid_host() - { - if (!$GLOBALS['slow_tests']) { - throw new ActiveRecord\DatabaseException(''); - } - ActiveRecord\Connection::instance("{$this->conn->protocol}://user:pass/1.1.1.1/db"); - } - - /** - * @expectedException \ActiveRecord\DatabaseException - */ - public function test_connection_failed() - { - ActiveRecord\Connection::instance("{$this->conn->protocol}://baduser:badpass@127.0.0.1/db"); - } - - /** - * @expectedException \ActiveRecord\DatabaseException - */ - public function test_connect_failed() - { - ActiveRecord\Connection::instance("{$this->conn->protocol}://zzz:zzz@127.0.0.1/test"); - } - - public function test_connect_with_port() - { - $config = ActiveRecord\Config::instance(); - $name = $config->get_default_connection(); - $url = parse_url($config->get_connection($name)); - $conn = $this->conn; - $port = $conn::$DEFAULT_PORT; - - $connection_string = "{$url['scheme']}://{$url['user']}"; - if (isset($url['pass'])) { - $connection_string = "{$connection_string}:{$url['pass']}"; - } - $connection_string = "{$connection_string}@{$url['host']}:$port{$url['path']}"; - - if ('sqlite' != $this->conn->protocol) { - ActiveRecord\Connection::instance($connection_string); - } - } - - /** - * @expectedException \ActiveRecord\DatabaseException - */ - public function test_connect_to_invalid_database() - { - ActiveRecord\Connection::instance("{$this->conn->protocol}://test:test@127.0.0.1/" . self::InvalidDb); - } - - public function test_date_time_type() - { - $columns = $this->conn->columns('authors'); - $this->assert_equals('datetime', $columns['created_at']->raw_type); - $this->assert_equals(Column::DATETIME, $columns['created_at']->type); - $this->assert_true($columns['created_at']->length > 0); - } - - public function test_date() - { - $columns = $this->conn->columns('authors'); - $this->assert_equals('date', $columns['some_Date']->raw_type); - $this->assert_equals(Column::DATE, $columns['some_Date']->type); - $this->assert_true($columns['some_Date']->length >= 7); - } - - public function test_columns_no_inflection_on_hash_key() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_true(array_key_exists('author_id', $author_columns)); - } - - public function test_columns_nullable() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_false($author_columns['author_id']->nullable); - $this->assert_true($author_columns['parent_author_id']->nullable); - } - - public function test_columns_pk() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_true($author_columns['author_id']->pk); - $this->assert_false($author_columns['parent_author_id']->pk); - } - - public function test_columns_sequence() - { - if ($this->conn->supports_sequences()) { - $author_columns = $this->conn->columns('authors'); - $this->assert_equals('authors_author_id_seq', $author_columns['author_id']->sequence); - } - } - - public function test_columns_default() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_equals('default_name', $author_columns['name']->default); - } - - public function test_columns_type() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_equals('varchar', substr($author_columns['name']->raw_type, 0, 7)); - $this->assert_equals(Column::STRING, $author_columns['name']->type); - $this->assert_equals(25, $author_columns['name']->length); - } - - public function test_columns_text() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_equals('text', $author_columns['some_text']->raw_type); - $this->assert_equals(null, $author_columns['some_text']->length); - } - - public function test_columns_time() - { - $author_columns = $this->conn->columns('authors'); - $this->assert_equals('time', $author_columns['some_time']->raw_type); - $this->assert_equals(Column::TIME, $author_columns['some_time']->type); - } - - public function test_query() - { - $sth = $this->conn->query('SELECT * FROM authors'); - - while (($row = $sth->fetch())) { - $this->assert_not_null($row); - } - - $sth = $this->conn->query('SELECT * FROM authors WHERE author_id=1'); - $row = $sth->fetch(); - $this->assert_equals('Tito', $row['name']); - } - - /** - * @expectedException \ActiveRecord\DatabaseException - */ - public function test_invalid_query() - { - $this->conn->query('alsdkjfsdf'); - } - - public function test_fetch() - { - $sth = $this->conn->query('SELECT * FROM authors WHERE author_id IN(1,2,3)'); - $i = 0; - $ids = []; - - while (($row = $sth->fetch())) { - ++$i; - $ids[] = $row['author_id']; - } - - $this->assert_equals(3, $i); - $this->assert_equals([1, 2, 3], $ids); - } - - public function test_query_with_params() - { - $x=['Bill Clinton', 'Tito']; - $sth = $this->conn->query('SELECT * FROM authors WHERE name IN(?,?) ORDER BY name DESC', $x); - $row = $sth->fetch(); - $this->assert_equals('Tito', $row['name']); - - $row = $sth->fetch(); - $this->assert_equals('Bill Clinton', $row['name']); - - $row = $sth->fetch(); - $this->assert_equals(null, $row); - } - - public function test_insert_id_should_return_explicitly_inserted_id() - { - $this->conn->query('INSERT INTO authors(author_id,name) VALUES(99,\'name\')'); - $this->assert_true($this->conn->insert_id() > 0); - } - - public function test_insert_id() - { - $this->conn->query("INSERT INTO authors(name) VALUES('name')"); - $this->assert_true($this->conn->insert_id() > 0); - } - - public function test_insert_id_with_params() - { - $x = ['name']; - $this->conn->query('INSERT INTO authors(name) VALUES(?)', $x); - $this->assert_true($this->conn->insert_id() > 0); - } - - public function test_inflection() - { - $columns = $this->conn->columns('authors'); - $this->assert_equals('parent_author_id', $columns['parent_author_id']->inflected_name); - } - - public function test_escape() - { - $s = "Bob's"; - $this->assert_not_equals($s, $this->conn->escape($s)); - } - - public function test_columnsx() - { - $columns = $this->conn->columns('authors'); - $names = ['author_id', 'parent_author_id', 'name', 'updated_at', 'created_at', 'some_Date', 'some_time', 'some_text', 'encrypted_password', 'mixedCaseField']; - - if ($this->conn instanceof ActiveRecord\OciAdapter) { - $names = array_filter(array_map('strtolower', $names), function ($s) { return 'some_time' !== $s; }); - } - - foreach ($names as $field) { - $this->assert_true(array_key_exists($field, $columns)); - } - - $this->assert_equals(true, $columns['author_id']->pk); - $this->assert_equals('int', $columns['author_id']->raw_type); - $this->assert_equals(Column::INTEGER, $columns['author_id']->type); - $this->assert_true($columns['author_id']->length > 1); - $this->assert_false($columns['author_id']->nullable); - - $this->assert_equals(false, $columns['parent_author_id']->pk); - $this->assert_true($columns['parent_author_id']->nullable); - - $this->assert_equals('varchar', substr($columns['name']->raw_type, 0, 7)); - $this->assert_equals(Column::STRING, $columns['name']->type); - $this->assert_equals(25, $columns['name']->length); - } - - public function test_columns_decimal() - { - $columns = $this->conn->columns('books'); - $this->assert_equals(Column::DECIMAL, $columns['special']->type); - $this->assert_true($columns['special']->length >= 10); - } - - private function limit($offset, $limit) - { - $ret = []; - $sql = 'SELECT * FROM authors ORDER BY name ASC'; - $this->conn->query_and_fetch($this->conn->limit($sql, $offset, $limit), function ($row) use (&$ret) { $ret[] = $row; }); - - return ActiveRecord\collect($ret, 'author_id'); - } - - public function test_limit() - { - $this->assert_equals([2, 1], $this->limit(1, 2)); - } - - public function test_limit_to_first_record() - { - $this->assert_equals([3], $this->limit(0, 1)); - } - - public function test_limit_to_last_record() - { - $this->assert_equals([1], $this->limit(2, 1)); - } - - public function test_limit_with_null_offset() - { - $this->assert_equals([3], $this->limit(null, 1)); - } - - public function test_limit_with_nulls() - { - $this->assert_equals([], $this->limit(null, null)); - } - - public function test_fetch_no_results() - { - $sth = $this->conn->query('SELECT * FROM authors WHERE author_id=65534'); - $this->assert_equals(null, $sth->fetch()); - } - - public function test_tables() - { - $this->assert_true(count($this->conn->tables()) > 0); - } - - public function test_query_column_info() - { - $this->assert_greater_than(0, count((array) $this->conn->query_column_info('authors'))); - } - - public function test_query_table_info() - { - $this->assert_greater_than(0, count((array) $this->conn->query_for_tables())); - } - - public function test_query_table_info_must_return_one_field() - { - $sth = $this->conn->query_for_tables(); - $this->assert_equals(1, count((array) $sth->fetch())); - } - - public function test_transaction_commit() - { - $original = $this->conn->query_and_fetch_one('select count(*) from authors'); - - $this->conn->transaction(); - $this->conn->query("insert into authors(author_id,name) values(9999,'blahhhhhhhh')"); - $this->conn->commit(); - - $this->assert_equals($original+1, $this->conn->query_and_fetch_one('select count(*) from authors')); - } - - public function test_transaction_rollback() - { - $original = $this->conn->query_and_fetch_one('select count(*) from authors'); - - $this->conn->transaction(); - $this->conn->query("insert into authors(author_id,name) values(9999,'blahhhhhhhh')"); - $this->conn->rollback(); - - $this->assert_equals($original, $this->conn->query_and_fetch_one('select count(*) from authors')); - } - - public function test_show_me_a_useful_pdo_exception_message() - { - try { - $this->conn->query('select * from an_invalid_column'); - $this->fail(); - } catch (Exception $e) { - $this->assert_equals(1, preg_match('/(an_invalid_column)|(exist)/', $e->getMessage())); - } - } - - public function test_quote_name_does_not_over_quote() - { - $c = $this->conn; - $q = $c::$QUOTE_CHARACTER; - $qn = function ($s) use ($c) { return $c->quote_name($s); }; - - $this->assert_equals("{$q}string", $qn("{$q}string")); - $this->assert_equals("string{$q}", $qn("string{$q}")); - $this->assert_equals("{$q}string{$q}", $qn("{$q}string{$q}")); - } - - public function test_datetime_to_string() - { - $datetime = '2009-01-01 01:01:01 EST'; - $this->assert_equals($datetime, $this->conn->datetime_to_string(date_create($datetime))); - } - - public function test_date_to_string() - { - $datetime = '2009-01-01'; - $this->assert_equals($datetime, $this->conn->date_to_string(date_create($datetime))); - } -} diff --git a/test/helpers/AdapterTestCase.php b/test/helpers/AdapterTestCase.php new file mode 100644 index 00000000..22866dc2 --- /dev/null +++ b/test/helpers/AdapterTestCase.php @@ -0,0 +1,408 @@ +get_connection($connection_name)) { + $this->markTestSkipped($connection_name . ' drivers are not present'); + } + + parent::setUp($connection_name); + } + + public function test_i_has_a_default_port_unless_im_sqlite() + { + if ($this->connection instanceof ActiveRecord\SqliteAdapter) { + $this->expectNotToPerformAssertions(); + return; + } + + $c = $this->connection; + $this->assertTrue($c::$DEFAULT_PORT > 0); + } + + public function test_should_set_adapter_variables() + { + $this->assertNotNull($this->connection->protocol); + } + + public function test_null_connection_string_uses_default_connection() + { + $this->assertNotNull(ActiveRecord\Connection::instance(null)); + $this->assertNotNull(ActiveRecord\Connection::instance('')); + $this->assertNotNull(ActiveRecord\Connection::instance()); + } + + public function test_invalid_connection_protocol() + { + $this->expectException(\ActiveRecord\DatabaseException::class); + ActiveRecord\Connection::instance('terribledb://user:pass@host/db'); + } + + public function test_no_host_connection() + { + $this->expectException(\ActiveRecord\DatabaseException::class); + if (!$GLOBALS['slow_tests']) { + throw new ActiveRecord\DatabaseException(''); + } + ActiveRecord\Connection::instance("{$this->connection->protocol}://user:pass"); + } + + public function test_connection_failed_invalid_host() + { + $this->expectException(\ActiveRecord\DatabaseException::class); + if (!$GLOBALS['slow_tests']) { + throw new ActiveRecord\DatabaseException(''); + } + ActiveRecord\Connection::instance("{$this->connection->protocol}://user:pass/1.1.1.1/db"); + } + + public function test_connection_failed() + { + $this->expectException(\ActiveRecord\DatabaseException::class); + ActiveRecord\Connection::instance("{$this->connection->protocol}://baduser:badpass@127.0.0.1/db"); + } + + public function test_connect_failed() + { + $this->expectException(\ActiveRecord\DatabaseException::class); + ActiveRecord\Connection::instance("{$this->connection->protocol}://zzz:zzz@127.0.0.1/test"); + } + + public function test_connect_with_port() + { + $this->expectNotToPerformAssertions(); + $config = ActiveRecord\Config::instance(); + $name = $this->connection_name; + $url = parse_url($config->get_connection($name)); + $conn = $this->connection; + $port = $conn::$DEFAULT_PORT; + + $connection_string = "{$url['scheme']}://" . $url['user'] ?? ''; + if (isset($url['pass'])) { + $connection_string = "{$connection_string}:{$url['pass']}"; + } + + $connection_string = "{$connection_string}@{$url['host']}:" . $port . $url['path'] ?? ''; + + if ('sqlite' != $this->connection->protocol) { + ActiveRecord\Connection::instance($connection_string); + } + } + + public function test_connect_to_invalid_database() + { + $this->expectException(\ActiveRecord\DatabaseException::class); + ActiveRecord\Connection::instance("{$this->connection->protocol}://test:test@127.0.0.1/" . self::InvalidDb); + } + + public function test_date_time_type() + { + $columns = $this->connection->columns('authors'); + $this->assertEquals('datetime', $columns['created_at']->raw_type); + $this->assertEquals(Column::DATETIME, $columns['created_at']->type); + $this->assertTrue($columns['created_at']->length > 0); + } + + public function test_date() + { + $columns = $this->connection->columns('authors'); + $this->assertEquals('date', $columns['some_Date']->raw_type); + $this->assertEquals(Column::DATE, $columns['some_Date']->type); + $this->assertTrue($columns['some_Date']->length >= 7); + } + + public function test_columns_no_inflection_on_hash_key() + { + $author_columns = $this->connection->columns('authors'); + $this->assertTrue(array_key_exists('author_id', $author_columns)); + } + + public function test_columns_nullable() + { + $author_columns = $this->connection->columns('authors'); + $this->assertFalse($author_columns['author_id']->nullable); + $this->assertTrue($author_columns['parent_author_id']->nullable); + } + + public function test_columns_pk() + { + $author_columns = $this->connection->columns('authors'); + $this->assertTrue($author_columns['author_id']->pk); + $this->assertFalse($author_columns['parent_author_id']->pk); + } + + public function test_columns_sequence() + { + if ($this->connection->supports_sequences()) { + $author_columns = $this->connection->columns('authors'); + $this->assertEquals('authors_author_id_seq', $author_columns['author_id']->sequence); + } else { + $this->expectNotToPerformAssertions(); + } + } + + public function test_columns_default() + { + $author_columns = $this->connection->columns('authors'); + $this->assertEquals('default_name', $author_columns['name']->default); + } + + public function test_columns_type() + { + $author_columns = $this->connection->columns('authors'); + $this->assertEquals('varchar', substr($author_columns['name']->raw_type, 0, 7)); + $this->assertEquals(Column::STRING, $author_columns['name']->type); + $this->assertEquals(25, $author_columns['name']->length); + } + + public function test_columns_text() + { + $author_columns = $this->connection->columns('authors'); + $this->assertEquals('text', $author_columns['some_text']->raw_type); + $this->assertEquals(null, $author_columns['some_text']->length); + } + + public function test_columns_time() + { + $author_columns = $this->connection->columns('authors'); + $this->assertEquals('time', $author_columns['some_time']->raw_type); + $this->assertEquals(Column::TIME, $author_columns['some_time']->type); + } + + public function test_query() + { + $sth = $this->connection->query('SELECT * FROM authors'); + + while (($row = $sth->fetch())) { + $this->assertNotNull($row); + } + + $sth = $this->connection->query('SELECT * FROM authors WHERE author_id=1'); + $row = $sth->fetch(); + $this->assertEquals('Tito', $row['name']); + } + + public function test_invalid_query() + { + $this->expectException(\ActiveRecord\DatabaseException::class); + $this->connection->query('alsdkjfsdf'); + } + + public function test_fetch() + { + $sth = $this->connection->query('SELECT * FROM authors WHERE author_id IN(1,2,3)'); + $i = 0; + $ids = []; + + while (($row = $sth->fetch())) { + ++$i; + $ids[] = $row['author_id']; + } + + $this->assertEquals(3, $i); + $this->assertEquals([1, 2, 3], $ids); + } + + public function test_query_with_params() + { + $x=['Bill Clinton', 'Tito']; + $sth = $this->connection->query('SELECT * FROM authors WHERE name IN(?,?) ORDER BY name DESC', $x); + $row = $sth->fetch(); + $this->assertEquals('Tito', $row['name']); + + $row = $sth->fetch(); + $this->assertEquals('Bill Clinton', $row['name']); + + $row = $sth->fetch(); + $this->assertEquals(null, $row); + } + + public function test_insert_id_should_return_explicitly_inserted_id() + { + $this->connection->query('INSERT INTO authors(author_id,name) VALUES(99,\'name\')'); + $this->assertTrue($this->connection->insert_id() > 0); + } + + public function test_insert_id() + { + $this->connection->query("INSERT INTO authors(name) VALUES('name')"); + $this->assertTrue($this->connection->insert_id() > 0); + } + + public function test_insert_id_with_params() + { + $x = ['name']; + $this->connection->query('INSERT INTO authors(name) VALUES(?)', $x); + $this->assertTrue($this->connection->insert_id() > 0); + } + + public function test_inflection() + { + $columns = $this->connection->columns('authors'); + $this->assertEquals('parent_author_id', $columns['parent_author_id']->inflected_name); + } + + public function test_escape() + { + $s = "Bob's"; + $this->assertNotEquals($s, $this->connection->escape($s)); + } + + public function test_columnsx() + { + $columns = $this->connection->columns('authors'); + $names = ['author_id', 'parent_author_id', 'name', 'updated_at', 'created_at', 'some_Date', 'some_time', 'some_text', 'encrypted_password', 'mixedCaseField']; + + if ($this->connection instanceof ActiveRecord\OciAdapter) { + $names = array_filter(array_map('strtolower', $names), function ($s) { return 'some_time' !== $s; }); + } + + foreach ($names as $field) { + $this->assertTrue(array_key_exists($field, $columns)); + } + + $this->assertEquals(true, $columns['author_id']->pk); + $this->assertEquals('int', $columns['author_id']->raw_type); + $this->assertEquals(Column::INTEGER, $columns['author_id']->type); + $c = $columns['author_id']; + $this->assertTrue($columns['name']->length > 1); + $this->assertFalse($columns['author_id']->nullable); + + $this->assertEquals(false, $columns['parent_author_id']->pk); + $this->assertTrue($columns['parent_author_id']->nullable); + + $this->assertEquals('varchar', substr($columns['name']->raw_type, 0, 7)); + $this->assertEquals(Column::STRING, $columns['name']->type); + $this->assertEquals(25, $columns['name']->length); + } + + public function test_columns_decimal() + { + $columns = $this->connection->columns('books'); + $this->assertEquals(Column::DECIMAL, $columns['special']->type); + $this->assertTrue($columns['special']->length >= 10); + } + + private function limit($offset, $limit) + { + $ret = []; + $sql = 'SELECT * FROM authors ORDER BY name ASC'; + $this->connection->query_and_fetch($this->connection->limit($sql, $offset, $limit), function ($row) use (&$ret) { $ret[] = $row; }); + + return ActiveRecord\collect($ret, 'author_id'); + } + + public function test_limit() + { + $this->assertEquals([2, 1], $this->limit(1, 2)); + } + + public function test_limit_to_first_record() + { + $this->assertEquals([3], $this->limit(0, 1)); + } + + public function test_limit_to_last_record() + { + $this->assertEquals([1], $this->limit(2, 1)); + } + + public function test_limit_with_null_offset() + { + $this->assertEquals([3], $this->limit(null, 1)); + } + + public function test_limit_with_nulls() + { + $this->assertEquals([], $this->limit(null, null)); + } + + public function test_fetch_no_results() + { + $sth = $this->connection->query('SELECT * FROM authors WHERE author_id=65534'); + $this->assertEquals(null, $sth->fetch()); + } + + public function test_tables() + { + $this->assertTrue(count($this->connection->tables()) > 0); + } + + public function test_query_column_info() + { + $this->assertGreaterThan(0, count((array) $this->connection->query_column_info('authors'))); + } + + public function test_query_table_info() + { + $this->assertGreaterThan(0, count((array) $this->connection->query_for_tables())); + } + + public function test_query_table_info_must_return_one_field() + { + $sth = $this->connection->query_for_tables(); + $this->assertEquals(1, count((array) $sth->fetch())); + } + + public function test_transaction_commit() + { + $original = $this->connection->query_and_fetch_one('select count(*) from authors'); + + $this->connection->transaction(); + $this->connection->query("insert into authors(author_id,name) values(9999,'blahhhhhhhh')"); + $this->connection->commit(); + + $this->assertEquals($original+1, $this->connection->query_and_fetch_one('select count(*) from authors')); + } + + public function test_transaction_rollback() + { + $original = $this->connection->query_and_fetch_one('select count(*) from authors'); + + $this->connection->transaction(); + $this->connection->query("insert into authors(author_id,name) values(9999,'blahhhhhhhh')"); + $this->connection->rollback(); + + $this->assertEquals($original, $this->connection->query_and_fetch_one('select count(*) from authors')); + } + + public function test_show_me_a_useful_pdo_exception_message() + { + try { + $this->connection->query('select * from an_invalid_column'); + $this->fail(); + } catch (Exception $e) { + $this->assertEquals(1, preg_match('/(an_invalid_column)|(exist)/', $e->getMessage())); + } + } + + public function test_quote_name_does_not_over_quote() + { + $c = $this->connection; + $q = $c::$QUOTE_CHARACTER; + $qn = function ($s) use ($c) { return $c->quote_name($s); }; + + $this->assertEquals("{$q}string", $qn("{$q}string")); + $this->assertEquals("string{$q}", $qn("string{$q}")); + $this->assertEquals("{$q}string{$q}", $qn("{$q}string{$q}")); + } + + public function test_datetime_to_string() + { + $datetime = '2009-01-01 01:01:01'; + $this->assertEquals($datetime, $this->connection->datetime_to_string(date_create($datetime))); + } + + public function test_date_to_string() + { + $datetime = '2009-01-01'; + $this->assertEquals($datetime, $this->connection->date_to_string(date_create($datetime))); + } +} diff --git a/test/helpers/DatabaseTest.php b/test/helpers/DatabaseTestCase.php similarity index 64% rename from test/helpers/DatabaseTest.php rename to test/helpers/DatabaseTestCase.php index f25e194c..7ed4a5eb 100644 --- a/test/helpers/DatabaseTest.php +++ b/test/helpers/DatabaseTestCase.php @@ -1,25 +1,26 @@ original_default_connection = $config->get_default_connection(); + $connection_name ??= $config->get_default_connection(); $this->original_date_class = $config->get_date_class(); - if ($connection_name) { - $config->set_default_connection($connection_name); - } if ('sqlite' == $connection_name || 'sqlite' == $config->get_default_connection()) { // need to create the db. the adapter specifically does not create it for us. @@ -27,16 +28,16 @@ public function set_up($connection_name=null) new SQLite3(static::$db); } - $this->connection_name = $connection_name; try { - $this->conn = ActiveRecord\ConnectionManager::get_connection($connection_name); + $this->connection = ActiveRecord\ConnectionManager::get_connection($connection_name); + $this->connection_name = $connection_name; } catch (ActiveRecord\DatabaseException $e) { - $this->mark_test_skipped($connection_name . ' failed to connect. ' . $e->getMessage()); + $this->markTestSkipped($connection_name . ' failed to connect. ' . $e->getMessage()); } $GLOBALS['ACTIVERECORD_LOG'] = false; - $loader = new DatabaseLoader($this->conn); + $loader = new DatabaseLoader($this->connection); $loader->reset_table_data(); if (self::$log) { @@ -44,12 +45,9 @@ public function set_up($connection_name=null) } } - public function tear_down() + public function tearDown(): void { ActiveRecord\Config::instance()->set_date_class($this->original_date_class); - if ($this->original_default_connection) { - ActiveRecord\Config::instance()->set_default_connection($this->original_default_connection); - } } public function assert_exception_message_contains($contains, $closure) @@ -62,7 +60,7 @@ public function assert_exception_message_contains($contains, $closure) $message = $e->getMessage(); } - $this->assertContains($contains, $message); + $this->assertStringContainsString($contains, $message); } /** @@ -76,7 +74,7 @@ public function assert_sql_has($needle, $haystack) $needle = str_replace(['"', '`'], '', $needle); $haystack = str_replace(['"', '`'], '', $haystack); - return $this->assertContains($needle, $haystack); + return $this->assertStringContainsString($needle, $haystack); } public function assert_sql_doesnt_has($needle, $haystack) @@ -84,6 +82,6 @@ public function assert_sql_doesnt_has($needle, $haystack) $needle = str_replace(['"', '`'], '', $needle); $haystack = str_replace(['"', '`'], '', $haystack); - return $this->assertNotContains($needle, $haystack); + return $this->assertStringNotContainsString($needle, $haystack); } } diff --git a/test/helpers/SnakeCase_PHPUnit_Framework_TestCase.php b/test/helpers/SnakeCase_PHPUnit_Framework_TestCase.php deleted file mode 100644 index 01224123..00000000 --- a/test/helpers/SnakeCase_PHPUnit_Framework_TestCase.php +++ /dev/null @@ -1,72 +0,0 @@ -camelize($meth); - - if (method_exists($this, $camel_cased_method)) { - return call_user_func_array([$this, $camel_cased_method], $args); - } - - $class_name = get_called_class(); - $trace = debug_backtrace(); - die("PHP Fatal Error: Call to undefined method $class_name::$meth() in {$trace[1]['file']} on line {$trace[1]['line']}" . PHP_EOL); - } - - public function setUp(): void - { - if (method_exists($this, 'set_up')) { - call_user_func_array([$this, 'set_up'], func_get_args()); - } - } - - public function tearDown(): void - { - if (method_exists($this, 'tear_down')) { - call_user_func_array([$this, 'tear_down'], func_get_args()); - } - } - - private function setup_assert_keys($args) - { - $last = count($args)-1; - $keys = array_slice($args, 0, $last); - $array = $args[$last]; - - return [$keys, $array]; - } - - public function assert_has_keys(/* $keys..., $array */) - { - list($keys, $array) = $this->setup_assert_keys(func_get_args()); - - $this->assert_not_null($array, 'Array was null'); - - foreach ($keys as $name) { - $this->assert_array_has_key($name, $array); - } - } - - public function assert_doesnt_has_keys(/* $keys..., $array */) - { - list($keys, $array) = $this->setup_assert_keys(func_get_args()); - - foreach ($keys as $name) { - $this->assert_array_not_has_key($name, $array); - } - } - - public function assert_is_a($expected_class, $object) - { - $this->assert_equals($expected_class, get_class($object)); - } - - public function assert_datetime_equals($expected, $actual) - { - $this->assert_equals($expected->format(DateTime::ISO8601), $actual->format(DateTime::ISO8601)); - } -} diff --git a/test/helpers/config.php b/test/helpers/config.php index 1b87187a..ae969379 100644 --- a/test/helpers/config.php +++ b/test/helpers/config.php @@ -15,14 +15,11 @@ * * $ vendor/bin/phpunit test/InflectorTest.php **/ -require_once 'vendor/autoload.php'; +require_once __DIR__ . '/../../vendor/autoload.php'; -require_once 'vendor/phpunit/phpunit/src/Framework/TestCase.php'; -require_once 'SnakeCase_PHPUnit_Framework_TestCase.php'; - - -require_once 'DatabaseTest.php'; -require_once 'AdapterTest.php'; +require_once __DIR__ . '/../../vendor/phpunit/phpunit/src/Framework/TestCase.php'; +require_once 'DatabaseTestCase.php'; +require_once 'AdapterTestCase.php'; require_once __DIR__ . '/../../ActiveRecord.php'; @@ -33,15 +30,14 @@ $GLOBALS['show_warnings'] = true; if ('false' !== getenv('LOG')) { - DatabaseTest::$log = true; + DatabaseTestCase::$log = true; } ActiveRecord\Config::initialize(function ($cfg) { $cfg->set_model_directory(realpath(__DIR__ . '/../models')); $cfg->set_connections([ - 'mysql' => getenv('PHPAR_MYSQL') ?: 'mysql://test:test@127.0.0.1/test', - 'pgsql' => getenv('PHPAR_PGSQL') ?: 'pgsql://test:test@127.0.0.1/test', - 'oci' => getenv('PHPAR_OCI') ?: 'oci://test:test@127.0.0.1/dev', + 'mysql' => getenv('PHPAR_MYSQL') ?: 'mysql://test:test@127.0.0.1:3306/test', + 'pgsql' => getenv('PHPAR_PGSQL') ?: 'pgsql://test:test@127.0.0.1:5432/test', 'sqlite' => getenv('PHPAR_SQLITE') ?: 'sqlite://test.db']); $cfg->set_default_connection('mysql'); @@ -54,17 +50,21 @@ } } - if (class_exists('Log_file')) { // PEAR Log installed - $logger = new Log_file(dirname(__FILE__) . '/../log/query.log', 'ident', ['mode' => 0664, 'timeFormat' => '%Y-%m-%d %H:%M:%S']); + if (class_exists('Monolog\Logger')) { // Monolog installed + $log = new Monolog\Logger("arlog"); + $log->pushHandler(new \Monolog\Handler\StreamHandler( + dirname(__FILE__) . '/../log/query.log', + \Monolog\Level::Warning) + ); $cfg->set_logging(true); - $cfg->set_logger($logger); + $cfg->set_logger($log); } else { if ($GLOBALS['show_warnings'] && !isset($GLOBALS['show_warnings_done'])) { echo "(Logging SQL queries disabled, PEAR::Log not found.)\n"; } - DatabaseTest::$log = false; + DatabaseTestCase::$log = false; } if ($GLOBALS['show_warnings'] && !isset($GLOBALS['show_warnings_done'])) {