diff --git a/.gitignore b/.gitignore index e64bc25e..01b4c704 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,21 @@ -.project -.idea -.buildpath -.settings -*.log *.db +*.log *.swp -.phpunit.cache -vendor/* -output/* -composer.lock -phpunit.xml +.buildpath +.idea .php_cs.cache .php_cs -docs/api +.php-cs-fixer.cache +.phpunit.cache .phpunit.result.cache +.project +.settings .stan-cache -.php-cs-fixer.cache +/.vscode +/docs/api +/node_modules/* +/output/* +/vendor/* +composer.lock +package-lock.json +phpunit.xml \ No newline at end of file diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index 460671e2..98ce89ba 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -2,7 +2,16 @@ $finder = new PhpCsFixer\Finder(); $config = new PhpCsFixer\Config('json-schema', 'json-schema style guide'); -$finder->in(__DIR__ . '/lib'); +$finder->in(__DIR__) + ->exclude('.github') + ->exclude('.phpunit.cache') + ->exclude('.stan.cache') + ->exclude('.vscode') + ->exclude('assets') + ->exclude('docs') + ->exclude('node_modules') + ->exclude('output') + ->exclude('vendor'); $config ->setRules([ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index cf81e54c..00000000 --- a/.travis.yml +++ /dev/null @@ -1,54 +0,0 @@ -language: php -cache: - directories: - - $HOME/.composer/cache/files - - $HOME/.phpcsfixer - -before_install: - - if [[ "$TRAVIS_PHP_VERSION" = "hhvm" || "$TRAVIS_PHP_VERSION" = "nightly" ]]; then sed -i '/^.*friendsofphp\/php-cs-fixer.*$/d' composer.json; fi - - # sami requires at least PHP 7.0. Since we only run it for PHP 7, we'll remove it from composer.json for non-7 builds - - if [[ "$TRAVIS_PHP_VERSION" != 7.0 ]]; then sed -i '/^.*sami\/sami.*$/d' composer.json; fi - -install: - - travis_retry composer install --prefer-dist --no-interaction - -before_script: - - echo 'extension = "memcached.so"' >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - mysql -e 'CREATE DATABASE phpar_test;' - - psql -c 'CREATE DATABASE phpar_test;' -U postgres - -services: - - memcached - -env: - - PHPAR_MYSQL=mysql://root@127.0.0.1/phpar_test PHPAR_PGSQL=pgsql://postgres@127.0.0.1/phpar_test - -matrix: - fast_finish: true - include: - - php: 5.4 - - php: 5.5 - - php: 5.6 - - php: 7.0 - env: - - PHPAR_MYSQL=mysql://root@127.0.0.1/phpar_test PHPAR_PGSQL=pgsql://postgres@127.0.0.1/phpar_test WITH_DOCS=true - - php: 7.1 - - php: 'nightly' - allow_failures: - - php: 'nightly' - -script: - - IFS=$'\n'; COMMIT_SCA_FILES=($(git diff --name-only --diff-filter=ACMRTUXB "${TRAVIS_COMMIT_RANGE}")); unset IFS - - if [[ "$WITH_PHPCSFIXER" == "true" ]]; then vendor/bin/php-cs-fixer fix --config=.php_cs.dist -v --dry-run --stop-on-violation --using-cache=no --path-mode=intersection -- "${COMMIT_SCA_FILES[@]}"; fi - - ./vendor/bin/phpunit - - if [[ "$WITH_DOCS" == "true" ]]; then echo "*** pwd:"; pwd; ls -la; ./vendor/bin/sami.php update sami-config.php; fi - -deploy: - provider: pages - skip_cleanup: true - local_dir: ./docs - github_token: $GITHUB_TOKEN # Set in travis-ci.org dashboard - on: - branch: master - condition: $TRAVIS_PHP_VERSION = 7.0 diff --git a/lib/Model.php b/lib/Model.php index 36a64ce9..8855f43c 100644 --- a/lib/Model.php +++ b/lib/Model.php @@ -1671,7 +1671,7 @@ public static function last(/* ... */) * YourModel::find(1,2,3); * * # finding by pk accepts an options array - * YourModel::find(123,array('order' => 'name desc')); + * YourModel::find(123, ['order' => 'name desc']); * ``` * * Finding by using a conditions array: @@ -1719,19 +1719,19 @@ public static function last(/* ... */) * array static User::find(["name"=>"Philip"]); * "first" static|null User::find("first", ["name"=>"Waldo"]); * "last" static|null User::find("last", ["name"=>"William"]); - * "all" static[] User::find("all", ["name" => "Stephen"] + * "all" static[] User::find("all", ["name"=>"Stephen"] * ...int|string static[] User::find(1, 3, 5, 8); * array static[] User::find([1,3,5,8]); - * array<"conditions", array> static[] User::find(["conditions"=> ["name" => "Kurt"]]); + * array<"conditions", array> static[] User::find(["conditions"=>["name"=>"Kurt"]]); */ - public static function find(/* $type, $options */) + public static function find(/* $type, $options */): static|array|null { $class = get_called_class(); - if (func_num_args() <= 0) { + $args = func_get_args(); + if (0 === count($args)) { throw new RecordNotFound("Couldn't find $class without an ID"); } - $args = func_get_args(); $options = static::extract_and_validate_options($args); $num_args = count($args); @@ -1765,7 +1765,7 @@ public static function find(/* $type, $options */) // find by pk else { - if (1 === count($args) && 1 == $num_args) { + if (1 === $num_args) { $args = $args[0]; } diff --git a/test/ActiveRecordCacheTest.php b/test/ActiveRecordCacheTest.php index 34f0a3ca..4ff9b4e2 100644 --- a/test/ActiveRecordCacheTest.php +++ b/test/ActiveRecordCacheTest.php @@ -24,18 +24,18 @@ public function tearDown(): void Cache::initialize(); } - public function test_default_expire() + public function testDefaultExpire() { $this->assertEquals(30, Cache::$options['expire']); } - public function test_explicit_default_expire() + public function testExplicitDefaultExpire() { Config::instance()->set_cache('memcache://localhost', ['expire' => 1]); $this->assertEquals(1, Cache::$options['expire']); } - public function test_caches_column_meta_data() + public function testCachesColumnMetaData() { Author::first(); diff --git a/test/ActiveRecordFindTest.php b/test/ActiveRecordFindTest.php index bde65669..f4565410 100644 --- a/test/ActiveRecordFindTest.php +++ b/test/ActiveRecordFindTest.php @@ -12,89 +12,90 @@ class ActiveRecordFindTest extends DatabaseTestCase { - public function test_find_with_no_params() + public function testFindWithNoParams() { $this->expectException(RecordNotFound::class); Author::find(); } - public function test_find_returns_single_model() { - $author = Author::find(3); - $this->assertInstanceOf(Model::class, $author ); + public function testFindReturnsSingleModel() + { + $author = Author::find(3, ['select' => 'author_id']); + $this->assertInstanceOf(Model::class, $author); $author = Author::find('3'); - $this->assertInstanceOf(Model::class, $author ); - - $author = Author::find(["name"=>"Bill Clinton"]); - $this->assertInstanceOf(Model::class, $author ); + $this->assertInstanceOf(Model::class, $author); + $author = Author::find(['name'=>'Bill Clinton']); + $this->assertInstanceOf(Model::class, $author); - $author = Author::find_by_name("Bill Clinton"); - $this->assertInstanceOf(Model::class, $author ); + $author = Author::find_by_name('Bill Clinton'); + $this->assertInstanceOf(Model::class, $author); $author = Author::first(); - $this->assertInstanceOf(Model::class, $author ); + $this->assertInstanceOf(Model::class, $author); - $author = Author::find("first", ["name"=>"Bill Clinton"]); - $this->assertInstanceOf(Model::class, $author ); + $author = Author::find('first', ['name'=>'Bill Clinton']); + $this->assertInstanceOf(Model::class, $author); $author = Author::last(); - $this->assertInstanceOf(Model::class, $author ); + $this->assertInstanceOf(Model::class, $author); - $author = Author::find("last", ["name"=>"Bill Clinton"]); - $this->assertInstanceOf(Model::class, $author ); + $author = Author::find('last', ['name'=>'Bill Clinton']); + $this->assertInstanceOf(Model::class, $author); } - public function test_find_returns_array_of_models() + public function testFindReturnsArrayOfModels() { $authors = Author::all(); $this->assertIsArray($authors); - $authors = Author::find("all"); + $authors = Author::find('all', ['limit' => 1]); $this->assertIsArray($authors); - $authors = Author::find("all", ["name" => "Bill Clinton"]); + $authors = Author::find('all', ['name' => 'Bill Clinton']); $this->assertIsArray($authors); - $authors = Author::find_all_by_name("Bill Clinton"); + $authors = Author::find_all_by_name('Bill Clinton'); $this->assertIsArray($authors); - $authors = Author::find(1,2,3); + $authors = Author::find(1, 2, 3); $this->assertIsArray($authors); - $authors = Author::find([1,2,3]); + $authors = Author::find([1, 2, 3]); $this->assertIsArray($authors); - $authors = Author::find(["conditions"=> ["name" => "Bill Clinton"]]); + $authors = Author::find(['conditions'=> ['name' => 'Bill Clinton']]); $this->assertIsArray($authors); - $authors = Author::find(['conditions'=>["author_id = ?", 3]]); + $authors = Author::find(['conditions'=>['author_id = ?', 3]]); $this->assertIsArray($authors); } - public function test_find_returns_null() { + public function testFindReturnsNull() + { $lawyer = HonestLawyer::first(); $this->assertNull($lawyer); $lawyer = HonestLawyer::last(); $this->assertNull($lawyer); - $lawyer = HonestLawyer::find("first", ["name"=>"Abe"]); + $lawyer = HonestLawyer::find('first', ['name'=>'Abe']); $this->assertNull($lawyer); - $lawyer = HonestLawyer::find("last", ["name"=>"Abe"]); + $lawyer = HonestLawyer::find('last', ['name'=>'Abe']); $this->assertNull($lawyer); } - static public function noReturnValues(): array + public static function noReturnValues(): array { return [ [ -1, null, - ["first", ["name"=>"Abe"]], - ["last", ["name"=>"Abe"]], - ["conditions"=> ["name" => "Bill Clinton"]] + ['first', ['name'=>'Abe']], + ['last', ['name'=>'Abe']], + ['conditions'=> ['name' => 'Bill Clinton']] ] ]; } @@ -102,24 +103,25 @@ static public function noReturnValues(): array /** * @dataProvider noReturnValues */ - public function test_find_doesnt_return($badValue) { + public function testFindDoesntReturn($badValue) + { $this->expectException(RecordNotFound::class); Author::find($badValue); } - public function test_find_by_pk() + public function testFindByPk() { $author = Author::find(3); $this->assertEquals(3, $author->id); } - public function test_find_by_pkno_results() + public function testFindByPknoResults() { $this->expectException(RecordNotFound::class); Author::find(99999999); } - public function test_find_by_multiple_pk_with_partial_match() + public function testFindByMultiplePkWithPartialMatch() { try { Author::find(1, 999999999); @@ -129,14 +131,14 @@ public function test_find_by_multiple_pk_with_partial_match() } } - public function test_find_by_pk_with_options() + public function testFindByPkWithOptions() { $author = Author::find(3, ['order' => 'name']); $this->assertEquals(3, $author->id); $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name')); } - public function test_find_by_pk_array() + public function testFindByPkArray() { $authors = Author::find(1, '2'); $this->assertEquals(2, count($authors)); @@ -144,150 +146,150 @@ public function test_find_by_pk_array() $this->assertEquals(2, $authors[1]->id); } - public function test_find_by_pk_array_with_options() + public function testFindByPkArrayWithOptions() { $authors = Author::find(1, '2', ['order' => 'name']); $this->assertEquals(2, count($authors)); $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name')); } - public function test_find_nothing_with_sql_in_string() + public function testFindNothingWithSqlInString() { $this->expectException(RecordNotFound::class); Author::first('name = 123123123'); } - public function test_find_all() + public function testFindAll() { $authors = Author::find('all', ['conditions' => ['author_id IN(?)', [1, 2, 3]]]); $this->assertTrue(count($authors) >= 3); } - public function test_find_all_with_no_bind_values() + public function testFindAllWithNoBindValues() { $authors = Author::find('all', ['conditions' => ['author_id IN(1,2,3)']]); $this->assertEquals(1, $authors[0]->author_id); } - public function test_find_all_with_empty_array_bind_value_throws_exception() + public function testFindAllWithEmptyArrayBindValueThrowsException() { $this->expectException(DatabaseException::class); $authors = Author::find('all', ['conditions' => ['author_id IN(?)', []]]); $this->assertCount(0, $authors); } - public function test_find_hash_using_alias() + public function testFindHashUsingAlias() { $venues = Venue::all(['conditions' => ['marquee' => 'Warner Theatre', 'city' => ['Washington', 'New York']]]); $this->assertTrue(count($venues) >= 1); } - public function test_find_hash_using_alias_with_null() + public function testFindHashUsingAliasWithNull() { $venues = Venue::all(['conditions' => ['marquee' => null]]); $this->assertEquals(0, count($venues)); } - public function test_dynamic_finder_using_alias() + public function testDynamicFinderUsingAlias() { $this->assertNotNull(Venue::find_by_marquee('Warner Theatre')); } - public function test_find_all_hash() + public function testFindAllHash() { $books = \test\models\Book::find('all', ['conditions' => ['author_id' => 1]]); $this->assertTrue(count($books) > 0); } - public function test_find_all_hash_with_order() + public function testFindAllHashWithOrder() { $books = \test\models\Book::find('all', ['conditions' => ['author_id' => 1], 'order' => 'name DESC']); $this->assertTrue(count($books) > 0); } - public function test_find_all_no_args() + public function testFindAllNoArgs() { $author = Author::all(); $this->assertTrue(count($author) > 1); } - public function test_find_all_no_results() + public function testFindAllNoResults() { $authors = Author::find('all', ['conditions' => ['author_id IN(11111111111,22222222222,333333333333)']]); $this->assertEquals([], $authors); } - public function test_find_first() + public function testFindFirst() { $author = Author::find('first', ['conditions' => ['author_id IN(?)', [1, 2, 3]]]); $this->assertEquals(1, $author->author_id); $this->assertEquals('Tito', $author->name); } - public function test_find_first_no_results() + public function testFindFirstNoResults() { $this->assertNull(Author::find('first', ['conditions' => 'author_id=1111111'])); } - public function test_find_first_using_pk() + public function testFindFirstUsingPk() { $author = Author::find('first', 3); $this->assertEquals(3, $author->author_id); } - public function test_find_first_with_conditions_as_string() + public function testFindFirstWithConditionsAsString() { $author = Author::find('first', ['conditions' => 'author_id=3']); $this->assertEquals(3, $author->author_id); } - public function test_find_all_with_conditions_as_string() + public function testFindAllWithConditionsAsString() { $author = Author::find('all', ['conditions' => 'author_id in(2,3)']); $this->assertEquals(2, count($author)); } - public function test_find_by_sql() + public function testFindBySql() { $author = Author::find_by_sql('SELECT * FROM authors WHERE author_id in(1,2)'); $this->assertEquals(1, $author[0]->author_id); $this->assertEquals(2, count($author)); } - public function test_find_by_sqltakes_values_array() + public function testFindBySqltakesValuesArray() { $author = Author::find_by_sql('SELECT * FROM authors WHERE author_id=?', [1]); $this->assertNotNull($author); } - public function test_find_with_conditions() + public function testFindWithConditions() { $author = Author::find('first', ['conditions' => ['author_id=? and name=?', 1, 'Tito']]); $this->assertEquals(1, $author->author_id); } - public function test_find_last() + public function testFindLast() { $author = Author::last(); $this->assertEquals(4, $author->author_id); $this->assertEquals('Uncle Bob', $author->name); } - public function test_find_last_using_string_condition() + public function testFindLastUsingStringCondition() { $author = Author::find('last', ['conditions' => 'author_id IN(1,2,3,4)']); $this->assertEquals(4, $author->author_id); $this->assertEquals('Uncle Bob', $author->name); } - public function test_limit_before_order() + public function testLimitBeforeOrder() { $authors = Author::all(['limit' => 2, 'order' => 'author_id desc', 'conditions' => 'author_id in(1,2)']); $this->assertEquals(2, $authors[0]->author_id); $this->assertEquals(1, $authors[1]->author_id); } - public function test_for_each() + public function testForEach() { $i = 0; $res = Author::all(); @@ -299,7 +301,7 @@ public function test_for_each() $this->assertTrue($i > 0); } - public function test_fetch_all() + public function testFetchAll() { $i = 0; @@ -310,7 +312,7 @@ public function test_fetch_all() $this->assertTrue($i > 0); } - public function test_count() + public function testCount() { $this->assertEquals(1, Author::count(1)); $this->assertEquals(2, Author::count([1, 2])); @@ -320,14 +322,14 @@ public function test_count() $this->assertEquals(1, Author::count(['name' => 'Tito', 'author_id' => 1])); } - public function test_gh149_empty_count() + public function testGh149EmptyCount() { $total = Author::count(); $this->assertEquals($total, Author::count(null)); $this->assertEquals($total, Author::count([])); } - public function test_exists() + public function testExists() { $this->assertTrue(Author::exists(1)); $this->assertTrue(Author::exists(['conditions' => 'author_id=1'])); @@ -336,7 +338,7 @@ public function test_exists() $this->assertFalse(Author::exists(['conditions' => 'author_id=999999'])); } - public function test_find_by_call_static() + public function testFindByCallStatic() { $this->assertEquals('Tito', Author::find_by_name('Tito')->name); $this->assertEquals('Tito', Author::find_by_author_id_and_name(1, 'Tito')->name); @@ -344,19 +346,19 @@ public function test_find_by_call_static() $this->assertEquals('Tito', Author::find_by_name(['Tito', 'George W. Bush'], ['order' => 'name desc'])->name); } - public function test_find_by_call_static_no_results() + public function testFindByCallStaticNoResults() { $this->assertNull(Author::find_by_name('SHARKS WIT LASERZ')); $this->assertNull(Author::find_by_name_or_author_id()); } - public function test_find_by_call_static_invalid_column_name() + public function testFindByCallStaticInvalidColumnName() { $this->expectException(DatabaseException::class); Author::find_by_sharks(); } - public function test_find_all_by_call_static() + public function testFindAllByCallStatic() { $x = Author::find_all_by_name('Tito'); $this->assertEquals('Tito', $x[0]->name); @@ -367,45 +369,45 @@ public function test_find_all_by_call_static() $this->assertEquals('George W. Bush', $x[0]->name); } - public function test_find_all_by_call_static_no_results() + public function testFindAllByCallStaticNoResults() { $x = Author::find_all_by_name('SHARKSSSSSSS'); $this->assertEquals(0, count($x)); } - public function test_find_all_by_call_static_with_array_values_and_options() + public function testFindAllByCallStaticWithArrayValuesAndOptions() { $author = Author::find_all_by_name(['Tito', 'Bill Clinton'], ['order' => 'name desc']); $this->assertEquals('Tito', $author[0]->name); $this->assertEquals('Bill Clinton', $author[1]->name); } - public function test_find_all_by_call_static_undefined_method() + public function testFindAllByCallStaticUndefinedMethod() { $this->expectException(ActiveRecordException::class); Author::find_sharks('Tito'); } - public function test_find_all_takes_limit_options() + public function testFindAllTakesLimitOptions() { $authors = Author::all(['limit' => 1, 'offset' => 2, 'order' => 'name desc']); $this->assertEquals('George W. Bush', $authors[0]->name); } - public function test_find_by_call_static_with_invalid_field_name() + public function testFindByCallStaticWithInvalidFieldName() { $this->expectException(ActiveRecordException::class); Author::find_by_some_invalid_field_name('Tito'); } - public function test_find_with_select() + public function testFindWithSelect() { $author = Author::first(['select' => 'name, 123 as bubba', 'order' => 'name desc']); $this->assertEquals('Uncle Bob', $author->name); $this->assertEquals(123, $author->bubba); } - public function test_find_with_select_non_selected_fields_should_not_have_attributes() + public function testFindWithSelectNonSelectedFieldsShouldNotHaveAttributes() { $this->expectException(UndefinedPropertyException::class); $author = Author::first(['select' => 'name, 123 as bubba']); @@ -413,7 +415,7 @@ public function test_find_with_select_non_selected_fields_should_not_have_attrib $this->fail('expected ActiveRecord\UndefinedPropertyExecption'); } - public function test_joins_on_model_with_association_and_explicit_joins() + public function testJoinsOnModelWithAssociationAndExplicitJoins() { JoinBook::$belongs_to = [['author']]; JoinBook::first(['joins' => ['author', 'LEFT JOIN authors a ON(books.secondary_author_id=a.author_id)']]); @@ -421,20 +423,20 @@ public function test_joins_on_model_with_association_and_explicit_joins() $this->assert_sql_has('LEFT JOIN authors a ON(books.secondary_author_id=a.author_id)', JoinBook::table()->last_sql); } - public function test_joins_on_model_with_explicit_joins() + public function testJoinsOnModelWithExplicitJoins() { JoinBook::first(['joins' => ['LEFT JOIN authors a ON(books.secondary_author_id=a.author_id)']]); $this->assert_sql_has('LEFT JOIN authors a ON(books.secondary_author_id=a.author_id)', JoinBook::table()->last_sql); } - public function test_group() + public function testGroup() { $venues = Venue::all(['select' => 'state', 'group' => 'state']); $this->assertTrue(count($venues) > 0); $this->assert_sql_has('GROUP BY state', ActiveRecord\Table::load(Venue::class)->last_sql); } - public function test_group_with_order_and_limit_and_having() + public function testGroupWithOrderAndLimitAndHaving() { $venues = Venue::all(['select' => 'state', 'group' => 'state', 'having' => 'length(state) = 2', 'order' => 'state', 'limit' => 2]); $this->assertTrue(count($venues) > 0); @@ -442,13 +444,13 @@ public function test_group_with_order_and_limit_and_having() 'SELECT state FROM venues GROUP BY state HAVING length(state) = 2 ORDER BY state', 0, 2), Venue::table()->last_sql); } - public function test_escape_quotes() + public function testEscapeQuotes() { $author = Author::find_by_name("Tito's"); $this->assertNotEquals("Tito's", Author::table()->last_sql); } - public function test_from() + public function testFrom() { $author = Author::find('first', ['from' => 'books', 'order' => 'author_id asc']); $this->assertTrue($author instanceof Author); @@ -459,7 +461,7 @@ public function test_from() $this->assertEquals(1, $author->id); } - public function test_having() + public function testHaving() { Author::first([ 'select' => 'date(created_at) as created_at', @@ -468,13 +470,13 @@ public function test_having() $this->assert_sql_has("GROUP BY date(created_at) HAVING date(created_at) > '2009-01-01'", Author::table()->last_sql); } - public function test_from_with_invalid_table() + public function testFromWithInvalidTable() { $this->expectException(DatabaseException::class); Author::find('first', ['from' => 'wrong_authors_table']); } - public function test_find_with_hash() + public function testFindWithHash() { $this->assertNotNull(Author::find(['name' => 'Tito'])); $this->assertNotNull(Author::find('first', ['name' => 'Tito'])); @@ -482,50 +484,50 @@ public function test_find_with_hash() $this->assertEquals(1, count(Author::all(['name' => 'Tito']))); } - public function test_find_or_create_by_on_existing_record() + public function testFindOrCreateByOnExistingRecord() { $this->assertNotNull(Author::find_or_create_by_name('Tito')); } - public function test_find_or_create_by_creates_new_record() + public function testFindOrCreateByCreatesNewRecord() { $author = Author::find_or_create_by_name_and_encrypted_password('New Guy', 'pencil'); $this->assertTrue($author->author_id > 0); $this->assertEquals('pencil', $author->encrypted_password); } - public function test_find_or_create_by_throws_exception_when_using_or() + public function testFindOrCreateByThrowsExceptionWhenUsingOr() { $this->expectException(ActiveRecordException::class); Author::find_or_create_by_name_or_encrypted_password('New Guy', 'pencil'); } - public function test_find_by_zero() + public function testFindByZero() { $this->expectException(RecordNotFound::class); Author::find(0); } - public function test_find_by_null() + public function testFindByNull() { $this->expectException(RecordNotFound::class); Author::find(null); } - public function test_count_by() + public function testCountBy() { $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() + public function testFindByPkShouldNotUseLimit() { Author::find(1); $this->assert_sql_has('SELECT * FROM authors WHERE author_id=?', Author::table()->last_sql); } - public function test_find_by_datetime() + public function testFindByDatetime() { $now = new DateTime(); $arnow = new ActiveRecord\DateTime(); diff --git a/test/ActiveRecordTest.php b/test/ActiveRecordTest.php index 3922f80e..de84fdb3 100644 --- a/test/ActiveRecordTest.php +++ b/test/ActiveRecordTest.php @@ -21,7 +21,7 @@ public function setUp($connection_name=null): void $this->options = ['conditions' => 'blah', 'order' => 'blah']; } - public function test_options_is_not() + public function testOptionsIsNot() { $this->assertFalse(Author::is_options_hash(null)); $this->assertFalse(Author::is_options_hash('')); @@ -30,58 +30,58 @@ public function test_options_is_not() $this->assertFalse(Author::is_options_hash([1, 2, 3])); } - public function test_options_hash_with_unknown_keys() + public function testOptionsHashWithUnknownKeys() { $this->expectException(ActiveRecordException::class); $this->assertFalse(Author::is_options_hash(['conditions' => 'blah', 'sharks' => 'laserz', 'dubya' => 'bush'])); } - public function test_options_is_hash() + public function testOptionsIsHash() { $this->assertTrue(Author::is_options_hash($this->options)); } - public function test_extract_and_validate_options() + public function testExtractAndValidateOptions() { $args = ['first', $this->options]; $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() + public function testExtractAndValidateOptionsWithArrayInArgs() { $args = ['first', [1, 2], $this->options]; $this->assertEquals($this->options, Author::extract_and_validate_options($args)); } - public function test_extract_and_validate_options_removes_options_hash() + public function testExtractAndValidateOptionsRemovesOptionsHash() { $args = ['first', $this->options]; Author::extract_and_validate_options($args); $this->assertEquals(['first'], $args); } - public function test_extract_and_validate_options_nope() + public function testExtractAndValidateOptionsNope() { $args = ['first']; $this->assertEquals([], Author::extract_and_validate_options($args)); $this->assertEquals(['first'], $args); } - public function test_extract_and_validate_options_nope_because_wasnt_at_end() + public function testExtractAndValidateOptionsNopeBecauseWasntAtEnd() { $args = ['first', $this->options, [1, 2]]; $this->assertEquals([], Author::extract_and_validate_options($args)); } - public function test_invalid_attribute() + public function testInvalidAttribute() { $this->expectException(UndefinedPropertyException::class); $author = Author::find('first', ['conditions' => 'author_id=1']); $author->some_invalid_field_name; } - public function test_invalid_attributes() + public function testInvalidAttributes() { $book = Book::find(1); try { @@ -94,7 +94,7 @@ public function test_invalid_attributes() $this->assertEquals(1, substr_count($exceptions[1], 'another_invalid_attribute')); } - public function test_getter_undefined_property_exception_includes_model_name() + public function testGetterUndefinedPropertyExceptionIncludesModelName() { $this->assert_exception_message_contains('Author->this_better_not_exist', function () { $author = new Author(); @@ -102,14 +102,14 @@ public function test_getter_undefined_property_exception_includes_model_name() }); } - public function test_mass_assignment_undefined_property_exception_includes_model_name() + public function testMassAssignmentUndefinedPropertyExceptionIncludesModelName() { $this->assert_exception_message_contains('Author->this_better_not_exist', function () { new Author(['this_better_not_exist' => 'hi']); }); } - public function test_setter_undefined_property_exception_includes_model_name() + public function testSetterUndefinedPropertyExceptionIncludesModelName() { $this->assert_exception_message_contains('Author->this_better_not_exist', function () { $author = new Author(); @@ -117,7 +117,7 @@ public function test_setter_undefined_property_exception_includes_model_name() }); } - public function test_get_values_for() + public function testGetValuesFor() { $books = Book::find_by_name('Ancient Art of Main Tanking'); $ret = $books->get_values_for(['book_id', 'author_id']); @@ -125,25 +125,25 @@ public function test_get_values_for() $this->assertEquals([1, 1], array_values($ret)); } - public function test_hyphenated_column_names_to_underscore() + public function testHyphenatedColumnNamesToUnderscore() { $keys = array_keys(RmBldg::first()->attributes()); $this->assertTrue(in_array('rm_name', $keys)); } - public function test_column_names_with_spaces() + public function testColumnNamesWithSpaces() { $keys = array_keys(RmBldg::first()->attributes()); $this->assertTrue(in_array('space_out', $keys)); } - public function test_mixed_case_column_name() + public function testMixedCaseColumnName() { $keys = array_keys(Author::first()->attributes()); $this->assertTrue(in_array('mixedcasefield', $keys)); } - public function test_mixed_case_primary_key_save() + public function testMixedCasePrimaryKeySave() { $venue = Venue::find(1); $venue->name = 'should not throw exception'; @@ -151,7 +151,7 @@ public function test_mixed_case_primary_key_save() $this->assertEquals($venue->name, Venue::find(1)->name); } - public function test_reload() + public function testReload() { $venue = Venue::find(1); $this->assertEquals('NY', $venue->state); @@ -161,7 +161,7 @@ public function test_reload() $this->assertEquals('NY', $venue->state); } - public function test_reload_protected_attribute() + public function testReloadProtectedAttribute() { $book = BookAttrAccessible::find(1); @@ -170,13 +170,13 @@ public function test_reload_protected_attribute() $this->assertNotEquals('Should not stay', $book->name); } - public function test_namespace_gets_stripped_from_table_name() + public function testNamespaceGetsStrippedFromTableName() { $model = new \test\models\namespacetest\Book(); $this->assertEquals('books', $model->table()->table); } - public function test_namespace_gets_stripped_from_inferred_foreign_key() + public function testNamespaceGetsStrippedFromInferredForeignKey() { $model = new \test\models\namespacetest\Book(); $table = ActiveRecord\Table::load(get_class($model)); @@ -186,7 +186,7 @@ public function test_namespace_gets_stripped_from_inferred_foreign_key() $this->assertEquals($table->get_relationship('parent_book_3')->foreign_key[0], 'book_id'); } - public function test_namespaced_relationship_associates_correctly() + public function testNamespacedRelationshipAssociatesCorrectly() { $model = new \test\models\namespacetest\Book(); $table = ActiveRecord\Table::load(get_class($model)); @@ -220,26 +220,26 @@ public function test_namespaced_relationship_associates_correctly() ); } - public function test_should_have_all_column_attributes_when_initializing_with_array() + public function testShouldHaveAllColumnAttributesWhenInitializingWithArray() { $author = new Author(['name' => 'Tito']); $this->assertTrue(count(array_keys($author->attributes())) >= 9); } - public function test_defaults() + public function testDefaults() { $author = new Author(); $this->assertEquals('default_name', $author->name); } - public function test_alias_attribute_getter() + public function testAliasAttributeGetter() { $venue = Venue::find(1); $this->assertEquals($venue->marquee, $venue->name); $this->assertEquals($venue->mycity, $venue->city); } - public function test_alias_attribute_setter() + public function testAliasAttributeSetter() { $venue = Venue::find(1); $venue->marquee = 'new name'; @@ -251,19 +251,19 @@ public function test_alias_attribute_setter() $this->assertEquals($venue->marquee, $venue->name); } - public function test_alias_from_mass_attributes() + public function testAliasFromMassAttributes() { $venue = new Venue(['marquee' => 'meme', 'id' => 123]); $this->assertEquals('meme', $venue->name); $this->assertEquals($venue->marquee, $venue->name); } - public function test_gh18_isset_on_aliased_attribute() + public function testGh18IssetOnAliasedAttribute() { $this->assertTrue(isset(Venue::first()->marquee)); } - public function test_attr_accessible() + public function testAttrAccessible() { $book = new BookAttrAccessible(['name' => 'should not be set', 'author_id' => 1]); $this->assertNull($book->name); @@ -272,7 +272,7 @@ public function test_attr_accessible() $this->assertEquals('test', $book->name); } - public function test_attr_protected() + public function testAttrProtected() { $book = new BookAttrAccessible(['book_id' => 999]); $this->assertNull($book->book_id); @@ -280,7 +280,7 @@ public function test_attr_protected() $this->assertEquals(999, $book->book_id); } - public function test_isset() + public function testIsset() { $book = new Book(); $this->assertTrue(isset($book->name)); @@ -290,7 +290,7 @@ public function test_isset() $this->assertTrue(isset($author->awesome_person)); } - public function test_readonly_only_halt_on_write_method() + public function testReadonlyOnlyHaltOnWriteMethod() { $book = Book::first(['readonly' => true]); $this->assertTrue($book->is_readonly()); @@ -305,27 +305,27 @@ public function test_readonly_only_halt_on_write_method() $this->assertEquals($book->name, 'some new name'); } - public function test_cast_when_using_setter() + public function testCastWhenUsingSetter() { $book = new Book(); $book->book_id = '1'; $this->assertSame(1, $book->book_id); } - public function test_cast_when_loading() + public function testCastWhenLoading() { $book = \test\models\Book::find(1); $this->assertSame(1, $book->book_id); $this->assertSame('Ancient Art of Main Tanking', $book->name); } - public function test_cast_defaults() + public function testCastDefaults() { $book = new Book(); $this->assertSame(0.0, $book->special); } - public function test_transaction_committed() + public function testTransactionCommitted() { $original = Author::count(); $ret = Author::transaction(function () { Author::create(['name' => 'blah']); }); @@ -333,7 +333,7 @@ public function test_transaction_committed() $this->assertTrue($ret); } - public function test_transaction_committed_when_returning_true() + public function testTransactionCommittedWhenReturningTrue() { $original = Author::count(); $ret = Author::transaction(function () { @@ -345,7 +345,7 @@ public function test_transaction_committed_when_returning_true() $this->assertTrue($ret); } - public function test_transaction_rolledback_by_returning_false() + public function testTransactionRolledbackByReturningFalse() { $original = Author::count(); @@ -359,7 +359,7 @@ public function test_transaction_rolledback_by_returning_false() $this->assertFalse($ret); } - public function test_transaction_rolledback_by_throwing_exception() + public function testTransactionRolledbackByThrowingException() { $original = Author::count(); $exception = null; @@ -377,33 +377,33 @@ public function test_transaction_rolledback_by_throwing_exception() $this->assertEquals($original, Author::count()); } - public function test_delegate() + public function testDelegate() { $event = Event::first(); $this->assertEquals($event->venue->state, $event->state); $this->assertEquals($event->venue->address, $event->address); } - public function test_delegate_prefix() + public function testDelegatePrefix() { $event = Event::first(); $this->assertEquals($event->host->name, $event->woot_name); } - public function test_delegate_returns_null_if_relationship_does_not_exist() + public function testDelegateReturnsNullIfRelationshipDoesNotExist() { $event = new Event(); $this->assertNull($event->state); } - public function test_delegate_set_attribute() + public function testDelegateSetAttribute() { $event = Event::first(); $event->state = 'MEXICO'; $this->assertEquals('MEXICO', $event->venue->state); } - public function test_delegate_getter_gh_98() + public function testDelegateGetterGh98() { Venue::$use_custom_get_state_getter = true; @@ -414,7 +414,7 @@ public function test_delegate_getter_gh_98() Venue::$use_custom_get_state_getter = false; } - public function test_delegate_setter_gh_98() + public function testDelegateSetterGh98() { Venue::$use_custom_set_state_setter = true; @@ -425,25 +425,25 @@ public function test_delegate_setter_gh_98() Venue::$use_custom_set_state_setter = false; } - public function test_table_name_with_underscores() + public function testTableNameWithUnderscores() { $this->assertNotNull(AwesomePerson::first()); } - public function test_model_should_default_as_new_record() + public function testModelShouldDefaultAsNewRecord() { $author = new Author(); $this->assertTrue($author->is_new_record()); } - public function test_setter() + public function testSetter() { $author = new Author(); $author->password = 'plaintext'; $this->assertEquals(md5('plaintext'), $author->encrypted_password); } - public function test_case_insensitivity() + public function testCaseInsensitivity() { $author = new Author(); $author->mixedCaseField = 'Peter'; @@ -456,45 +456,45 @@ public function test_case_insensitivity() $this->assertEquals('Simon', $author->MIXEDCASEFIELD); } - public function test_setter_with_same_name_as_an_attribute() + public function testSetterWithSameNameAsAnAttribute() { $author = new Author(); $author->name = 'bob'; $this->assertEquals('BOB', $author->name); } - public function test_getter() + public function testGetter() { $book = Book::first(); - $this->assertEquals("ANCIENT ART OF MAIN TANKING", $book->upper_name); + $this->assertEquals('ANCIENT ART OF MAIN TANKING', $book->upper_name); } - public function test_getter_with_same_name_as_an_attribute() + public function testGetterWithSameNameAsAnAttribute() { $book = new Book(); $book->publisher = 'Random House'; $this->assertEquals('RANDOM HOUSE', $book->publisher); } - public function test_setting_invalid_date_should_set_date_to_null() + public function testSettingInvalidDateShouldSetDateToNull() { $author = new Author(); $author->created_at = 'CURRENT_TIMESTAMP'; $this->assertNull($author->created_at); } - public function test_table_name() + public function testTableName() { $this->assertEquals('authors', Author::table_name()); } - public function test_undefined_instance_method() + public function testUndefinedInstanceMethod() { $this->expectException(ActiveRecordException::class); Author::first()->find_by_name('sdf'); } - public function test_clear_cache_for_specific_class() + public function testClearCacheForSpecificClass() { $book_table1 = ActiveRecord\Table::load(Book::class); $book_table2 = ActiveRecord\Table::load(Book::class); @@ -505,7 +505,7 @@ public function test_clear_cache_for_specific_class() $this->assertTrue($book_table1 !== $book_table3); } - public function test_flag_dirty() + public function testFlagDirty() { $author = new Author(); $author->flag_dirty('some_date'); @@ -515,22 +515,22 @@ public function test_flag_dirty() $this->assertFalse($author->attribute_is_dirty('some_date')); } - public function test_flag_dirty_attribute_which_does_not_exit() + public function testFlagDirtyAttributeWhichDoesNotExit() { $author = new Author(); $author->flag_dirty('some_inexistant_property'); - $this->assertEquals([],$author->dirty_attributes()); + $this->assertEquals([], $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() + public function testGh245DirtyAttributeShouldNotRaisePhpNoticeIfNotDirty() { $event = new Event(['title' => 'Fun']); $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() + public function testAssigningPhpDatetimeGetsConvertedToDateClassWithDefaults() { $author = new Author(); $author->created_at = $now = new \DateTime(); @@ -538,7 +538,7 @@ public function test_assigning_php_datetime_gets_converted_to_date_class_with_de $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() + public function testAssigningPhpDatetimeGetsConvertedToDateClassWithCustomDateClass() { ActiveRecord\Config::instance()->set_date_class('\\DateTime'); // use PHP built-in DateTime $author = new Author(); @@ -547,13 +547,13 @@ public function test_assigning_php_datetime_gets_converted_to_date_class_with_cu $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() + public function testAssigningFromMassAssignmentPhpDatetimeGetsConvertedToArDatetime() { $author = new Author(['created_at' => new \DateTime()]); $this->assertInstanceOf('ActiveRecord\\DateTime', $author->created_at); } - public function test_get_real_attribute_name() + public function testGetRealAttributeName() { $venue = new Venue(); $this->assertEquals('name', $venue->get_real_attribute_name('name')); @@ -561,13 +561,13 @@ public function test_get_real_attribute_name() $this->assertEquals(null, $venue->get_real_attribute_name('invalid_field')); } - public function test_id_setter_works_with_table_without_pk_named_attribute() + public function testIdSetterWorksWithTableWithoutPkNamedAttribute() { $author = new Author(['id' => 123]); $this->assertEquals(123, $author->author_id); } - public function test_query() + public function testQuery() { $row = Author::query('SELECT COUNT(*) AS n FROM authors')->fetch(); $this->assertTrue($row['n'] > 1); diff --git a/test/ActiveRecordWriteTest.php b/test/ActiveRecordWriteTest.php index 28a77e32..75307983 100644 --- a/test/ActiveRecordWriteTest.php +++ b/test/ActiveRecordWriteTest.php @@ -6,8 +6,8 @@ use ActiveRecord\Exception\ReadOnlyException; use ActiveRecord\Exception\UndefinedPropertyException; use test\models\Author; -use test\models\Venue; use test\models\Book; +use test\models\Venue; class DirtyAuthor extends ActiveRecord\Model { @@ -46,21 +46,21 @@ private function make_new_book_and($save=true) return $book; } - public function test_save() + public function testSave() { $this->expectNotToPerformAssertions(); $venue = new Venue(['name' => 'Tito']); $venue->save(); } - public function test_insert() + public function testInsert() { $author = new Author(['name' => 'Blah Blah']); $author->save(); $this->assertNotNull(Author::find($author->id)); } - public function test_insert_with_no_sequence_defined() + public function testInsertWithNoSequenceDefined() { $this->expectException(DatabaseException::class); if (!$this->connection->supports_sequences()) { @@ -69,21 +69,21 @@ public function test_insert_with_no_sequence_defined() AuthorWithoutSequence::create(['name' => 'Bob!']); } - public function test_insert_should_quote_keys() + public function testInsertShouldQuoteKeys() { $author = new Author(['name' => 'Blah Blah']); $author->save(); $this->assertTrue(false !== strpos($author->connection()->last_query, $author->connection()->quote_name('updated_at'))); } - public function test_save_auto_increment_id() + public function testSaveAutoIncrementId() { $venue = new Venue(['name' => 'Bob']); $venue->save(); $this->assertTrue($venue->id > 0); } - public function test_sequence_was_set() + public function testSequenceWasSet() { if ($this->connection->supports_sequences()) { $this->assertEquals($this->connection->get_sequence_name('authors', 'author_id'), Author::table()->sequence); @@ -92,7 +92,7 @@ public function test_sequence_was_set() } } - public function test_sequence_was_explicitly_set() + public function testSequenceWasExplicitlySet() { if ($this->connection->supports_sequences()) { $this->assertEquals(AuthorExplicitSequence::$sequence, AuthorExplicitSequence::table()->sequence); @@ -101,7 +101,7 @@ public function test_sequence_was_explicitly_set() } } - public function test_delete() + public function testDelete() { $author = Author::find(1); $author->delete(); @@ -109,7 +109,7 @@ public function test_delete() $this->assertFalse(Author::exists(1)); } - public function test_delete_by_find_all() + public function testDeleteByFindAll() { $books = Book::all(); @@ -121,7 +121,7 @@ public function test_delete_by_find_all() $this->assertEquals(0, count($res)); } - public function test_update() + public function testUpdate() { $book = Book::find(1); $new_name = 'new name'; @@ -132,7 +132,7 @@ public function test_update() $this->assertSame($new_name, $book->name, Book::find(1)->name); } - public function test_update_should_quote_keys() + public function testUpdateShouldQuoteKeys() { $book = Book::find(1); $book->name = 'new name'; @@ -140,7 +140,7 @@ public function test_update_should_quote_keys() $this->assertTrue(false !== strpos($book->connection()->last_query, $book->connection()->quote_name('name'))); } - public function test_update_attributes() + public function testUpdateAttributes() { $book = Book::find(1); $new_name = 'How to lose friends and alienate people'; // jax i'm worried about you @@ -151,14 +151,14 @@ public function test_update_attributes() $this->assertSame($new_name, $book->name, Book::find(1)->name); } - public function test_update_attributes_undefined_property() + public function testUpdateAttributesUndefinedProperty() { $this->expectException(UndefinedPropertyException::class); $book = Book::find(1); $book->update_attributes(['name' => 'new name', 'invalid_attribute' => true, 'another_invalid_attribute' => 'blah']); } - public function test_update_attribute() + public function testUpdateAttribute() { $book = Book::find(1); $new_name = 'some stupid self-help book'; @@ -168,14 +168,14 @@ public function test_update_attribute() $this->assertSame($new_name, $book->name, Book::find(1)->name); } - public function test_update_attribute_undefined_property() + public function testUpdateAttributeUndefinedProperty() { $this->expectException(UndefinedPropertyException::class); $book = Book::find(1); $book->update_attribute('invalid_attribute', true); } - public function test_save_null_value() + public function testSaveNullValue() { $book = Book::first(); $book->name = null; @@ -183,7 +183,7 @@ public function test_save_null_value() $this->assertSame(null, Book::find($book->id)->name); } - public function test_save_blank_value() + public function testSaveBlankValue() { $book = Book::find(1); $book->name = ''; @@ -191,13 +191,13 @@ public function test_save_blank_value() $this->assertSame('', Book::find(1)->name); } - public function test_dirty_attributes() + public function testDirtyAttributes() { $book = $this->make_new_book_and(false); $this->assertEquals(['name', 'special'], array_keys($book->dirty_attributes())); } - public function test_id_type() + public function testIdType() { $book = new Book(); $book->save(); @@ -208,7 +208,7 @@ public function test_id_type() $this->assertSame($book->id, $bookFromFind->id); } - public function test_dirty_attributes_cleared_after_saving() + public function testDirtyAttributesClearedAfterSaving() { $book = $this->make_new_book_and(); $this->assertTrue(false !== strpos($book->table()->last_sql, 'name')); @@ -216,13 +216,13 @@ public function test_dirty_attributes_cleared_after_saving() $this->assertEquals([], $book->dirty_attributes()); } - public function test_dirty_attributes_cleared_after_inserting() + public function testDirtyAttributesClearedAfterInserting() { $book = $this->make_new_book_and(); $this->assertEquals([], $book->dirty_attributes()); } - public function test_no_dirty_attributes_but_still_insert_record() + public function testNoDirtyAttributesButStillInsertRecord() { $book = new Book(); $this->assertEquals([], $book->dirty_attributes()); @@ -231,7 +231,7 @@ public function test_no_dirty_attributes_but_still_insert_record() $this->assertNotNull($book->id); } - public function test_dirty_attributes_cleared_after_updating() + public function testDirtyAttributesClearedAfterUpdating() { $book = Book::first(); $book->name = 'rivers cuomo'; @@ -239,7 +239,7 @@ public function test_dirty_attributes_cleared_after_updating() $this->assertEquals([], $book->dirty_attributes()); } - public function test_dirty_attributes_after_reloading() + public function testDirtyAttributesAfterReloading() { $book = Book::first(); $book->name = 'rivers cuomo'; @@ -247,14 +247,14 @@ public function test_dirty_attributes_after_reloading() $this->assertEquals([], $book->dirty_attributes()); } - public function test_dirty_attributes_with_mass_assignment() + public function testDirtyAttributesWithMassAssignment() { $book = Book::first(); $book->set_attributes(['name' => 'rivers cuomo']); $this->assertEquals(['name'], array_keys($book->dirty_attributes())); } - public function test_timestamps_set_before_save() + public function testTimestampsSetBeforeSave() { $author = new Author(); $author->save(); @@ -264,7 +264,7 @@ public function test_timestamps_set_before_save() $this->assertNotNull($author->created_at, $author->updated_at); } - public function test_timestamps_updated_at_only_set_before_update() + public function testTimestampsUpdatedAtOnlySetBeforeUpdate() { $author = new Author(); $author->save(); @@ -280,19 +280,19 @@ public function test_timestamps_updated_at_only_set_before_update() $this->assertNotEquals($updated_at, $author->updated_at); } - public function test_create() + public function testCreate() { $author = Author::create(['name' => 'Blah Blah']); $this->assertNotNull(Author::find($author->id)); } - public function test_create_should_set_created_at() + public function testCreateShouldSetCreatedAt() { $author = Author::create(['name' => 'Blah Blah']); $this->assertNotNull($author->created_at); } - public function test_update_with_no_primary_key_defined() + public function testUpdateWithNoPrimaryKeyDefined() { $this->expectException(ActiveRecordException::class); Author::table()->pk = []; @@ -301,7 +301,7 @@ public function test_update_with_no_primary_key_defined() $author->save(); } - public function test_delete_with_no_primary_key_defined() + public function testDeleteWithNoPrimaryKeyDefined() { $this->expectException(ActiveRecordException::class); Author::table()->pk = []; @@ -309,20 +309,20 @@ public function test_delete_with_no_primary_key_defined() $author->delete(); } - public function test_inserting_with_explicit_pk() + public function testInsertingWithExplicitPk() { $author = Author::create(['author_id' => 9999, 'name' => 'blah']); $this->assertEquals(9999, $author->author_id); } - public function test_readonly() + public function testReadonly() { $this->expectException(ReadOnlyException::class); $author = Author::first(['readonly' => true]); $author->save(); } - public function test_modified_attributes_in_before_handlers_get_saved() + public function testModifiedAttributesInBeforeHandlersGetSaved() { $author = DirtyAuthor::first(); $author->encrypted_password = 'coco'; @@ -331,7 +331,7 @@ public function test_modified_attributes_in_before_handlers_get_saved() $this->assertEquals('coco', DirtyAuthor::find($author->id)->encrypted_password); } - public function test_is_dirty() + public function testIsDirty() { $author = Author::first(); $this->assertEquals(false, $author->is_dirty()); @@ -340,7 +340,7 @@ public function test_is_dirty() $this->assertEquals(true, $author->is_dirty()); } - public function test_set_date_flags_dirty() + public function testSetDateFlagsDirty() { $author = Author::create(['some_date' => new DateTime()]); $author = Author::find($author->id); @@ -348,7 +348,7 @@ public function test_set_date_flags_dirty() $this->assertArrayHasKey('some_date', $author->dirty_attributes()); } - public function test_set_date_flags_dirty_with_php_datetime() + public function testSetDateFlagsDirtyWithPhpDatetime() { $author = Author::create(['some_date' => new \DateTime()]); $author = Author::find($author->id); @@ -356,25 +356,25 @@ public function test_set_date_flags_dirty_with_php_datetime() $this->assertArrayHasKey('some_date', $author->dirty_attributes()); } - public function test_delete_all_with_conditions_as_string() + public function testDeleteAllWithConditionsAsString() { $num_affected = Author::delete_all(['conditions' => 'parent_author_id = 2']); $this->assertEquals(2, $num_affected); } - public function test_delete_all_with_conditions_as_hash() + public function testDeleteAllWithConditionsAsHash() { $num_affected = Author::delete_all(['conditions' => ['parent_author_id' => 2]]); $this->assertEquals(2, $num_affected); } - public function test_delete_all_with_conditions_as_array() + public function testDeleteAllWithConditionsAsArray() { $num_affected = Author::delete_all(['conditions' => ['parent_author_id = ?', 2]]); $this->assertEquals(2, $num_affected); } - public function test_delete_all_with_limit_and_order() + public function testDeleteAllWithLimitAndOrder() { if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with UPDATE clause'); @@ -385,14 +385,14 @@ public function test_delete_all_with_limit_and_order() $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name asc LIMIT 1')); } - public function test_update_all_with_set_as_string() + public function testUpdateAllWithSetAsString() { $num_affected = Author::update_all(['set' => '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() + public function testUpdateAllWithSetAsHash() { $num_affected = Author::update_all(['set' => ['parent_author_id' => 2]]); $this->assertEquals(2, $num_affected); @@ -401,25 +401,25 @@ public function test_update_all_with_set_as_hash() /** * TODO: not implemented */ - public function test_update_all_with_conditions_as_string() + public function testUpdateAllWithConditionsAsString() { $num_affected = Author::update_all(['set' => 'parent_author_id = 2', 'conditions' => 'name = "Tito"']); $this->assertEquals(1, $num_affected); } - public function test_update_all_with_conditions_as_hash() + public function testUpdateAllWithConditionsAsHash() { $num_affected = Author::update_all(['set' => 'parent_author_id = 2', 'conditions' => ['name' => 'Tito']]); $this->assertEquals(1, $num_affected); } - public function test_update_all_with_conditions_as_array() + public function testUpdateAllWithConditionsAsArray() { $num_affected = Author::update_all(['set' => 'parent_author_id = 2', 'conditions' => ['name = ?', 'Tito']]); $this->assertEquals(1, $num_affected); } - public function test_update_all_with_limit_and_order() + public function testUpdateAllWithLimitAndOrder() { if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with UPDATE clause'); @@ -430,7 +430,7 @@ public function test_update_all_with_limit_and_order() $this->assertTrue(false !== strpos(Author::table()->last_sql, 'ORDER BY name asc LIMIT 1')); } - public function test_update_native_datetime() + public function testUpdateNativeDatetime() { $author = Author::create(['name' => 'Blah Blah']); $native_datetime = new \DateTime('1983-12-05'); @@ -438,7 +438,7 @@ public function test_update_native_datetime() $this->assertFalse($native_datetime === $author->some_date); } - public function test_update_our_datetime() + public function testUpdateOurDatetime() { $author = Author::create(['name' => 'Blah Blah']); $our_datetime = new DateTime('1983-12-05'); diff --git a/test/CacheModelTest.php b/test/CacheModelTest.php index 44896655..d76db3bb 100644 --- a/test/CacheModelTest.php +++ b/test/CacheModelTest.php @@ -32,17 +32,17 @@ public function tearDown(): void Cache::initialize(); } - public function test_default_expire() + public function testDefaultExpire() { $this->assertEquals(30, Author::table()->cache_model_expire); } - public function test_explicit_expire() + public function testExplicitExpire() { $this->assertEquals(2592000, Publisher::table()->cache_model_expire); } - public function test_cache_key() + public function testCacheKey() { $method = $this->set_method_public(Author::class, 'cache_key'); $author = Author::first(); @@ -50,7 +50,7 @@ public function test_cache_key() $this->assertEquals('test\models\Author-1', $method->invokeArgs($author, [])); } - public function test_model_cache_find_by_pk() + public function testModelCacheFindByPk() { $publisher = Publisher::find(1); $method = $this->set_method_public(Publisher::class, 'cache_key'); @@ -60,7 +60,7 @@ public function test_model_cache_find_by_pk() $this->assertEquals($publisher->name, $publisherDirectlyFromCache->name); } - public function test_model_cache_new() + public function testModelCacheNew() { $publisher = new Publisher([ 'name'=>'HarperCollins' @@ -76,7 +76,7 @@ public function test_model_cache_new() $this->assertEquals($publisher->name, $publisherDirectlyFromCache->name); } - public function test_model_cache_find() + public function testModelCacheFind() { $method = $this->set_method_public(Publisher::class, 'cache_key'); $publishers = Publisher::all(); @@ -89,7 +89,7 @@ public function test_model_cache_find() } } - public function test_regular_models_not_cached() + public function testRegularModelsNotCached() { $method = $this->set_method_public(Author::class, 'cache_key'); $author = Author::first(); @@ -97,7 +97,7 @@ public function test_regular_models_not_cached() $this->assertFalse(Cache::$adapter->read($cache_key)); } - public function test_model_delete_from_cache() + public function testModelDeleteFromCache() { $method = $this->set_method_public(Publisher::class, 'cache_key'); $publisher = Publisher::find(1); @@ -109,7 +109,7 @@ public function test_model_delete_from_cache() $this->assertFalse(Cache::$adapter->read($cache_key)); } - public function test_model_update_cache() + public function testModelUpdateCache() { $method = $this->set_method_public(Publisher::class, 'cache_key'); diff --git a/test/CacheTest.php b/test/CacheTest.php index 48bec5eb..84395d2b 100644 --- a/test/CacheTest.php +++ b/test/CacheTest.php @@ -27,47 +27,47 @@ private function cache_get() return Cache::get('1337', function () { return 'abcd'; }); } - public function test_initialize() + public function testInitialize() { $this->assertNotNull(Cache::$adapter); } - public function test_initialize_with_null() + public function testInitializeWithNull() { Cache::initialize(); $this->assertNull(Cache::$adapter); } - public function test_get_returns_the_value() + public function testGetReturnsTheValue() { $this->assertEquals('abcd', $this->cache_get()); } - public function test_get_writes_to_the_cache() + public function testGetWritesToTheCache() { $this->cache_get(); $this->assertEquals('abcd', Cache::$adapter->read('1337')); } - public function test_get_does_not_execute_closure_on_cache_hit() + public function testGetDoesNotExecuteClosureOnCacheHit() { $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() + public function testCacheAdapterReturnsFalseOnCacheMiss() { $this->assertSame(false, Cache::$adapter->read('some-key')); } - public function test_get_works_without_caching_enabled() + public function testGetWorksWithoutCachingEnabled() { Cache::$adapter = null; $this->assertEquals('abcd', $this->cache_get()); } - public function test_cache_expire() + public function testCacheExpire() { Cache::$options['expire'] = 1; $this->cache_get(); @@ -76,14 +76,14 @@ public function test_cache_expire() $this->assertSame(false, Cache::$adapter->read('1337')); } - public function test_namespace_is_set_properly() + public function testNamespaceIsSetProperly() { Cache::$options['namespace'] = 'myapp'; $this->cache_get(); $this->assertSame('abcd', Cache::$adapter->read('myapp::1337')); } - public function test_exception_when_connect_fails() + public function testExceptionWhenConnectFails() { $this->expectException(CacheException::class); Cache::initialize('memcache://127.0.0.1:1234'); diff --git a/test/CallbackTest.php b/test/CallbackTest.php index af778692..be549909 100644 --- a/test/CallbackTest.php +++ b/test/CallbackTest.php @@ -36,7 +36,7 @@ public function assert_implicit_save($first_method, $second_method) $this->assertEquals([$first_method, $second_method], $i_ran); } - public function test_gh_266_calling_save_in_after_save_callback_uses_update_instead_of_insert() + public function testGh266CallingSaveInAfterSaveCallbackUsesUpdateInsteadOfInsert() { $venue = new VenueAfterCreate(); $venue->name = 'change me'; @@ -47,85 +47,85 @@ public function test_gh_266_calling_save_in_after_save_callback_uses_update_inst $this->assertFalse(VenueAfterCreate::exists(['conditions'=> ['name'=>'change me']])); } - public function test_generic_callback_was_auto_registered() + public function testGenericCallbackWasAutoRegistered() { $this->assert_has_callback('after_construct'); } - public function test_register() + public function testRegister() { $this->callback->register('after_construct'); $this->assert_has_callback('after_construct'); } - public function test_register_non_generic() + public function testRegisterNonGeneric() { $this->callback->register('after_construct', 'non_generic_after_construct'); $this->assert_has_callback('after_construct', 'non_generic_after_construct'); } - public function test_register_invalid_callback() + public function testRegisterInvalidCallback() { $this->expectException(ActiveRecordException::class); $this->callback->register('invalid_callback'); } - public function test_register_callback_with_undefined_method() + public function testRegisterCallbackWithUndefinedMethod() { $this->expectException(ActiveRecordException::class); $this->callback->register('after_construct', 'do_not_define_me'); } - public function test_register_with_string_definition() + public function testRegisterWithStringDefinition() { $this->callback->register('after_construct', 'after_construct'); $this->assert_has_callback('after_construct'); } - public function test_register_with_closure() + public function testRegisterWithClosure() { $this->expectNotToPerformAssertions(); $this->callback->register('after_construct', function ($mode) { }); } - public function test_register_with_null_definition() + public function testRegisterWithNullDefinition() { $this->callback->register('after_construct', null); $this->assert_has_callback('after_construct'); } - public function test_register_with_no_definition() + public function testRegisterWithNoDefinition() { $this->callback->register('after_construct'); $this->assert_has_callback('after_construct'); } - public function test_register_appends_to_registry() + public function testRegisterAppendsToRegistry() { $this->callback->register('after_construct'); $this->callback->register('after_construct', 'non_generic_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() + public function testRegisterPrependsToRegistry() { $this->callback->register('after_construct'); $this->callback->register('after_construct', 'non_generic_after_construct', ['prepend' => true]); $this->assertEquals(['non_generic_after_construct', 'after_construct', 'after_construct'], $this->callback->get_callbacks('after_construct')); } - public function test_registers_via_static_array_definition() + public function testRegistersViaStaticArrayDefinition() { $this->assert_has_callback('after_destroy', 'after_destroy_one'); $this->assert_has_callback('after_destroy', 'after_destroy_two'); } - public function test_registers_via_static_string_definition() + public function testRegistersViaStaticStringDefinition() { $this->assert_has_callback('before_destroy', 'before_destroy_using_string'); } - public function test_register_via_static_with_invalid_definition() + public function testRegisterViaStaticWithInvalidDefinition() { $this->expectException(ActiveRecordException::class); $class_name = 'Venues_' . md5(uniqid()); @@ -134,32 +134,32 @@ public function test_register_via_static_with_invalid_definition() new ActiveRecord\CallBack($class_name); } - public function test_can_register_same_multiple_times() + public function testCanRegisterSameMultipleTimes() { $this->callback->register('after_construct'); $this->callback->register('after_construct'); $this->assertEquals(['after_construct', 'after_construct', 'after_construct'], $this->callback->get_callbacks('after_construct')); } - public function test_register_closure_callback() + public function testRegisterClosureCallback() { $closure = function ($model) {}; $this->callback->register('after_save', $closure); $this->assertEquals([$closure], $this->callback->get_callbacks('after_save')); } - public function test_get_callbacks_returns_array() + public function testGetCallbacksReturnsArray() { $this->callback->register('after_construct'); $this->assertTrue(is_array($this->callback->get_callbacks('after_construct'))); } - public function test_get_callbacks_returns_empty() + public function testGetCallbacksReturnsEmpty() { $this->assertEquals([], $this->callback->get_callbacks('this_callback_name_should_never_exist')); } - public function test_invoke_runs_all_callbacks() + public function testInvokeRunsAllCallbacks() { if (method_exists($this, 'createMock')) { $mock = $this->createMock(VenueCB::class, ['after_destroy_one', 'after_destroy_two']); @@ -171,7 +171,7 @@ public function test_invoke_runs_all_callbacks() $this->callback->invoke($mock, 'after_destroy'); } - public function test_invoke_closure() + public function testInvokeClosure() { $i_ran = false; $this->callback->register('after_validation', function ($model) use (&$i_ran) { $i_ran = true; }); @@ -179,7 +179,7 @@ public function test_invoke_closure() $this->assertTrue($i_ran); } - public function test_invoke_implicitly_calls_save_first() + public function testInvokeImplicitlyCallsSaveFirst() { $this->assert_implicit_save('before_save', 'before_create'); $this->assert_implicit_save('before_save', 'before_update'); @@ -187,26 +187,26 @@ public function test_invoke_implicitly_calls_save_first() $this->assert_implicit_save('after_save', 'after_update'); } - public function test_invoke_unregistered_callback() + public function testInvokeUnregisteredCallback() { $this->expectException(ActiveRecordException::class); $mock = $this->createMock(VenueCB::class, ['columns']); $this->callback->invoke($mock, 'before_validation_on_create'); } - public function test_before_callbacks_pass_on_false_return_callback_returned_false() + public function testBeforeCallbacksPassOnFalseReturnCallbackReturnedFalse() { $this->callback->register('before_validation', function ($model) { return false; }); $this->assertFalse($this->callback->invoke(null, 'before_validation')); } - public function test_before_callbacks_does_not_pass_on_false_for_after_callbacks() + public function testBeforeCallbacksDoesNotPassOnFalseForAfterCallbacks() { $this->callback->register('after_validation', function ($model) { return false; }); $this->assertTrue($this->callback->invoke(null, 'after_validation')); } - public function test_gh_28_after_create_should_be_invoked_after_auto_incrementing_pk_is_set() + public function testGh28AfterCreateShouldBeInvokedAfterAutoIncrementingPkIsSet() { $that = $this; VenueCB::$after_create = function ($model) use ($that) { $that->assertNotNull($model->id); }; @@ -218,7 +218,7 @@ public function test_gh_28_after_create_should_be_invoked_after_auto_incrementin $venue->save(); } - public function test_before_create_returned_false_halts_execution() + public function testBeforeCreateReturnedFalseHaltsExecution() { VenueCB::$before_create = ['before_create_halt_execution']; ActiveRecord\Table::clear_cache(VenueCB::class); @@ -239,7 +239,7 @@ public function test_before_create_returned_false_halts_execution() $this->assertTrue(false === strpos(ActiveRecord\Table::load(VenueCB::class)->last_sql, 'INSERT')); } - public function test_before_save_returned_false_halts_execution() + public function testBeforeSaveReturnedFalseHaltsExecution() { VenueCB::$before_update = ['before_update_halt_execution']; ActiveRecord\Table::clear_cache(VenueCB::class); @@ -261,7 +261,7 @@ public function test_before_save_returned_false_halts_execution() $this->assertTrue(false === strpos(ActiveRecord\Table::load(VenueCB::class)->last_sql, 'UPDATE')); } - public function test_before_destroy_returned_false_halts_execution() + public function testBeforeDestroyReturnedFalseHaltsExecution() { VenueCB::$before_destroy = ['before_destroy_halt_execution']; ActiveRecord\Table::clear_cache(VenueCB::class); @@ -279,7 +279,7 @@ public function test_before_destroy_returned_false_halts_execution() $this->assertTrue(false === strpos(ActiveRecord\Table::load(VenueCB::class)->last_sql, 'DELETE')); } - public function test_before_validation_returned_false_halts_execution() + public function testBeforeValidationReturnedFalseHaltsExecution() { VenueCB::$before_validation = ['before_validation_halt_execution']; ActiveRecord\Table::clear_cache(VenueCB::class); diff --git a/test/ColumnTest.php b/test/ColumnTest.php index a6ff9474..2b55031c 100644 --- a/test/ColumnTest.php +++ b/test/ColumnTest.php @@ -9,7 +9,7 @@ class ColumnTest extends TestCase { private $column; private $conn; - + public function setUp($connection_name = null): void { $this->column = new Column(); @@ -38,13 +38,13 @@ public function assert_cast($type, $casted_value, $original_value) } } - public function test_map_raw_type_dates() + public function testMapRawTypeDates() { $this->assert_mapped_type(Column::DATETIME, 'datetime'); $this->assert_mapped_type(Column::DATE, 'date'); } - public function test_map_raw_type_integers() + public function testMapRawTypeIntegers() { $this->assert_mapped_type(Column::INTEGER, 'integer'); $this->assert_mapped_type(Column::INTEGER, 'int'); @@ -54,7 +54,7 @@ public function test_map_raw_type_integers() $this->assert_mapped_type(Column::INTEGER, 'bigint'); } - public function test_map_raw_type_decimals() + public function testMapRawTypeDecimals() { $this->assert_mapped_type(Column::DECIMAL, 'float'); $this->assert_mapped_type(Column::DECIMAL, 'double'); @@ -62,26 +62,26 @@ public function test_map_raw_type_decimals() $this->assert_mapped_type(Column::DECIMAL, 'dec'); } - public function test_map_raw_type_strings() + public function testMapRawTypeStrings() { $this->assert_mapped_type(Column::STRING, 'string'); $this->assert_mapped_type(Column::STRING, 'varchar'); $this->assert_mapped_type(Column::STRING, 'text'); } - public function test_map_raw_type_default_to_string() + public function testMapRawTypeDefaultToString() { $this->assert_mapped_type(Column::STRING, 'bajdslfjasklfjlksfd'); } - public function test_map_raw_type_changes_integer_to_int() + public function testMapRawTypeChangesIntegerToInt() { $this->column->raw_type = 'integer'; $this->column->map_raw_type(); $this->assertEquals('int', $this->column->raw_type); } - public function test_cast() + public function testCast() { $datetime = new DateTime('2001-01-01'); $this->assert_cast(Column::INTEGER, 1, '1'); @@ -96,15 +96,15 @@ public function test_cast() // 32 bit if (PHP_INT_SIZE === 4) { - $this->assert_cast(Column::INTEGER, '2147483648', (((float) PHP_INT_MAX) + 1)); + $this->assert_cast(Column::INTEGER, '2147483648', ((float) PHP_INT_MAX) + 1); } // 64 bit elseif (PHP_INT_SIZE === 8) { - $this->assert_cast(Column::INTEGER, '9223372036854775808', (((float) PHP_INT_MAX) + 1)); + $this->assert_cast(Column::INTEGER, '9223372036854775808', ((float) PHP_INT_MAX) + 1); } } - public function test_cast_leave_null_alone() + public function testCastLeaveNullAlone() { $types = [ Column::STRING, @@ -118,7 +118,7 @@ public function test_cast_leave_null_alone() } } - public function test_empty_and_null_date_strings_should_return_null() + public function testEmptyAndNullDateStringsShouldReturnNull() { $column = new Column(); $column->type = Column::DATE; @@ -126,7 +126,7 @@ public function test_empty_and_null_date_strings_should_return_null() $this->assertEquals(null, $column->cast('', $this->conn)); } - public function test_empty_and_null_datetime_strings_should_return_null() + public function testEmptyAndNullDatetimeStringsShouldReturnNull() { $column = new Column(); $column->type = Column::DATETIME; @@ -134,7 +134,7 @@ public function test_empty_and_null_datetime_strings_should_return_null() $this->assertEquals(null, $column->cast('', $this->conn)); } - public function test_native_date_time_attribute_copies_exact_tz() + public function testNativeDateTimeAttributeCopiesExactTz() { $dt = new \DateTime('', new \DateTimeZone('America/New_York')); @@ -148,7 +148,7 @@ public function test_native_date_time_attribute_copies_exact_tz() $this->assertEquals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); } - public function test_ar_date_time_attribute_copies_exact_tz() + public function testArDateTimeAttributeCopiesExactTz() { $dt = new DateTime('', new \DateTimeZone('America/New_York')); diff --git a/test/ConfigTest.php b/test/ConfigTest.php index a10b848c..79877ce1 100644 --- a/test/ConfigTest.php +++ b/test/ConfigTest.php @@ -7,8 +7,8 @@ class TestLogger implements LoggerInterface { - public function emergency(string|\Stringable $message, array $context = []): void { - + public function emergency(string|\Stringable $message, array $context = []): void + { } /** @@ -17,13 +17,10 @@ public function emergency(string|\Stringable $message, array $context = []): voi * 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 { - + public function alert(string|\Stringable $message, array $context = []): void + { } /** @@ -31,26 +28,20 @@ public function alert(string|\Stringable $message, array $context = []): void { * * Example: Application component unavailable, unexpected exception. * - * @param string|\Stringable $message * @param mixed[] $context - * - * @return void */ - public function critical(string|\Stringable $message, array $context = []): 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 { - + public function error(string|\Stringable $message, array $context = []): void + { } /** @@ -59,26 +50,19 @@ public function error(string|\Stringable $message, array $context = []): void { * 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 { - + public function notice(string|\Stringable $message, array $context = []): void + { } /** @@ -86,40 +70,30 @@ public function notice(string|\Stringable $message, array $context = []):void { * * Example: User logs in, SQL logs. * - * @param string|\Stringable $message * @param mixed[] $context - * - * @return void */ - public function info(string|\Stringable $message, array $context = []):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 { - + 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 { - + public function log($level, string|\Stringable $message, array $context = []): void + { } } @@ -153,82 +127,82 @@ public function setUp(): void $this->config->set_connections($this->connections); } - public function test_get_connections() + public function testGetConnections() { $this->assertEquals($this->connections, $this->config->get_connections()); } - public function test_get_connection() + public function testGetConnection() { $this->assertEquals($this->connections['development'], $this->config->get_connection('development')); } - public function test_get_invalid_connection() + public function testGetInvalidConnection() { $this->assertNull($this->config->get_connection('whiskey tango foxtrot')); } - public function test_get_default_connection_and_connection() + public function testGetDefaultConnectionAndConnection() { $this->config->set_default_connection('development'); $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() + public function testGetDefaultConnectionAndConnectionStringDefaultsToDevelopment() { $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() + public function testGetDefaultConnectionStringWhenConnectionNameIsNotValid() { $this->config->set_default_connection('little mac'); $this->assertNull($this->config->get_default_connection_string()); } - public function test_default_connection_is_set_when_only_one_connection_is_present() + public function testDefaultConnectionIsSetWhenOnlyOneConnectionIsPresent() { $this->config->set_connections(['development' => $this->connections['development']]); $this->assertEquals('development', $this->config->get_default_connection()); } - public function test_set_connections_with_default() + public function testSetConnectionsWithDefault() { $this->config->set_connections($this->connections, 'test'); $this->assertEquals('test', $this->config->get_default_connection()); } - public function test_get_date_class_with_default() + public function testGetDateClassWithDefault() { $this->assertEquals('ActiveRecord\\DateTime', $this->config->get_date_class()); } - public function test_set_date_class_when_class_doesnt_exist() + public function testSetDateClassWhenClassDoesntExist() { $this->expectException(ConfigException::class); $this->config->set_date_class('doesntexist'); } - public function test_set_date_class_when_class_doesnt_have_format_or_createfromformat() + public function testSetDateClassWhenClassDoesntHaveFormatOrCreatefromformat() { $this->expectException(ConfigException::class); $this->config->set_date_class('TestLogger'); } - public function test_set_date_class_when_class_doesnt_have_createfromformat() + public function testSetDateClassWhenClassDoesntHaveCreatefromformat() { $this->expectException(ConfigException::class); $this->config->set_date_class('TestDateTimeWithoutCreateFromFormat'); } - public function test_set_date_class_with_valid_class() + public function testSetDateClassWithValidClass() { $this->config->set_date_class('TestDateTime'); $this->assertEquals('TestDateTime', $this->config->get_date_class()); } - public function test_initialize_closure() + public function testInitializeClosure() { $test = $this; diff --git a/test/ConnectionManagerTest.php b/test/ConnectionManagerTest.php index ecc023dc..a75b331c 100644 --- a/test/ConnectionManagerTest.php +++ b/test/ConnectionManagerTest.php @@ -1,28 +1,27 @@ assertNotNull(ConnectionManager::get_connection(null)); $this->assertNotNull(ConnectionManager::get_connection()); } - public function test_get_connection() + public function testGetConnection() { $this->assertNotNull(ConnectionManager::get_connection('mysql')); } - public function test_get_connection_uses_existing_object() + public function testGetConnectionUsesExistingObject() { $a = ConnectionManager::get_connection('mysql'); $this->assertSame($a === ConnectionManager::get_connection('mysql'), true); } - public function test_gh_91_get_connection_with_null_connection_is_always_default() + public function testGh91GetConnectionWithNullConnectionIsAlwaysDefault() { $conn_one = ConnectionManager::get_connection('mysql'); $conn_two = ConnectionManager::get_connection(); diff --git a/test/ConnectionTest.php b/test/ConnectionTest.php index 2f794b0b..159202bc 100644 --- a/test/ConnectionTest.php +++ b/test/ConnectionTest.php @@ -9,13 +9,13 @@ class ConnectionTest extends TestCase { - public function test_connection_info_from_should_throw_exception_when_no_host() + public function testConnectionInfoFromShouldThrowExceptionWhenNoHost() { $this->expectException(DatabaseException::class); ActiveRecord\Connection::parse_connection_url('mysql://user:pass@'); } - public function test_connection_info() + public function testConnectionInfo() { $info = ActiveRecord\Connection::parse_connection_url('mysql://user:pass@127.0.0.1:3306/dbname'); $this->assertEquals('mysql', $info->protocol); @@ -26,19 +26,19 @@ public function test_connection_info() $this->assertEquals('dbname', $info->db); } - public function test_gh_103_sqlite_connection_string_relative() + public function testGh103SqliteConnectionStringRelative() { $info = ActiveRecord\Connection::parse_connection_url('sqlite://../some/path/to/file.db'); $this->assertEquals('../some/path/to/file.db', $info->host); } - public function test_gh_103_sqlite_connection_string_absolute() + public function testGh103SqliteConnectionStringAbsolute() { $this->expectException(DatabaseException::class); ActiveRecord\Connection::parse_connection_url('sqlite:///some/path/to/file.db'); } - public function test_gh_103_sqlite_connection_string_unix() + public function testGh103SqliteConnectionStringUnix() { $info = ActiveRecord\Connection::parse_connection_url('sqlite://unix(/some/path/to/file.db)'); $this->assertEquals('/some/path/to/file.db', $info->host); @@ -50,26 +50,26 @@ public function test_gh_103_sqlite_connection_string_unix() $this->assertEquals('/some/path/to/file.db', $info->host); } - public function test_gh_103_sqlite_connection_string_windows() + public function testGh103SqliteConnectionStringWindows() { $info = ActiveRecord\Connection::parse_connection_url('sqlite://windows(c%3A/some/path/to/file.db)'); $this->assertEquals('c:/some/path/to/file.db', $info->host); } - public function test_parse_connection_url_with_unix_sockets() + public function testParseConnectionUrlWithUnixSockets() { $info = ActiveRecord\Connection::parse_connection_url('mysql://user:password@unix(/tmp/mysql.sock)/database'); $this->assertEquals('/tmp/mysql.sock', $info->host); } - public function test_parse_connection_url_with_decode_option() + public function testParseConnectionUrlWithDecodeOption() { $info = ActiveRecord\Connection::parse_connection_url('mysql://h%20az:h%40i@127.0.0.1/test?decode=true'); $this->assertEquals('h az', $info->user); $this->assertEquals('h@i', $info->pass); } - public function test_encoding() + public function testEncoding() { $info = ActiveRecord\Connection::parse_connection_url('mysql://test:test@127.0.0.1/test?charset=utf8'); $this->assertEquals('utf8', $info->charset); diff --git a/test/DateFormatTest.php b/test/DateFormatTest.php index 6af5b39a..4d29f8f6 100644 --- a/test/DateFormatTest.php +++ b/test/DateFormatTest.php @@ -4,9 +4,9 @@ class DateFormatTest extends DatabaseTestCase { - public function test_datefield_gets_converted_to_ar_datetime() + public function testDatefieldGetsConvertedToArDatetime() { - //make sure first author has a date + // make sure first author has a date $author = Author::first(); $author->some_date = new DateTime(); $author->save(); diff --git a/test/DateTimeTest.php b/test/DateTimeTest.php index d10fb91f..fac7527a 100644 --- a/test/DateTimeTest.php +++ b/test/DateTimeTest.php @@ -1,7 +1,7 @@ get_model(); $datetime = new DateTime(); @@ -45,7 +45,7 @@ private function assert_dirtifies($method /*, method params, ...*/) $this->assertArrayHasKey('some_date', $model->dirty_attributes()); } - public function test_should_flag_the_attribute_dirty() + public function testShouldFlagTheAttributeDirty() { $interval = new DateInterval('PT1S'); $timezone = new DateTimeZone('America/New_York'); @@ -59,7 +59,7 @@ public function test_should_flag_the_attribute_dirty() $this->assert_dirtifies('sub', $interval); } - public function test_set_iso_date() + public function testSetIsoDate() { $a = new \DateTime(); $a->setISODate(2001, 1); @@ -70,7 +70,7 @@ public function test_set_iso_date() $this->assertEquals($a->format(DateTime::ATOM), $b->format(DateTime::ATOM)); } - public function test_set_time() + public function testSetTime() { $a = new \DateTime(); $a->setTime(1, 1); @@ -81,82 +81,82 @@ public function test_set_time() $this->assertEquals($a->format(DateTime::ATOM), $b->format(DateTime::ATOM)); } - public function test_get_format_with_friendly() + public function testGetFormatWithFriendly() { $this->assertEquals('Y-m-d H:i:s', DateTime::get_format('db')); } - public function test_get_format_with_format() + public function testGetFormatWithFormat() { $this->assertEquals('Y-m-d', DateTime::get_format('Y-m-d')); } - public function test_get_format_with_null() + public function testGetFormatWithNull() { $this->assertEquals(\DateTime::RFC2822, DateTime::get_format()); } - public function test_format() + public function testFormat() { $this->assertTrue(is_string($this->date->format())); $this->assertTrue(is_string($this->date->format('Y-m-d'))); } - public function test_format_by_friendly_name() + public function testFormatByFriendlyName() { $d = date(DateTime::get_format('db')); $this->assertEquals($d, $this->date->format('db')); } - public function test_format_by_custom_format() + public function testFormatByCustomFormat() { $format = 'Y/m/d'; $this->assertEquals(date($format), $this->date->format($format)); } - public function test_format_uses_default() + public function testFormatUsesDefault() { $d = date(DateTime::$FORMATS[DateTime::$DEFAULT_FORMAT]); $this->assertEquals($d, $this->date->format()); } - public function test_all_formats() + public function testAllFormats() { foreach (DateTime::$FORMATS as $name => $format) { $this->assertEquals(date($format), $this->date->format($name)); } } - public function test_change_default_format_to_format_string() + public function testChangeDefaultFormatToFormatString() { DateTime::$DEFAULT_FORMAT = 'H:i:s'; $this->assertEquals(date(DateTime::$DEFAULT_FORMAT), $this->date->format()); } - public function test_change_default_format_to_friently() + public function testChangeDefaultFormatToFriently() { DateTime::$DEFAULT_FORMAT = 'short'; $this->assertEquals(date(DateTime::$FORMATS['short']), $this->date->format()); } - public function test_to_string() + public function testToString() { $this->assertEquals(date(DateTime::get_format()), '' . $this->date); } - public function test_create_from_format_error_handling() + public function testCreateFromFormatErrorHandling() { $this->expectException(AssertionError::class); DateTime::createFromFormat('H:i:s Y-d-m', '!!!'); } - public function test_create_from_format_without_tz() + public function testCreateFromFormatWithoutTz() { $d = DateTime::createFromFormat('H:i:s Y-d-m', '03:04:05 2000-02-01'); $this->assertEquals(new DateTime('2000-01-02 03:04:05'), $d); } - public function test_create_from_format_with_tz() + public function testCreateFromFormatWithTz() { $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'); @@ -164,7 +164,7 @@ public function test_create_from_format_with_tz() $this->assertEquals($d2->getTimestamp(), $d->getTimestamp()); } - public function test_native_date_time_attribute_copies_exact_tz() + public function testNativeDateTimeAttributeCopiesExactTz() { $dt = new \DateTime('', new \DateTimeZone('America/New_York')); $model = $this->get_model(); @@ -178,7 +178,7 @@ public function test_native_date_time_attribute_copies_exact_tz() $this->assertEquals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); } - public function test_ar_date_time_attribute_copies_exact_tz() + public function testArDateTimeAttributeCopiesExactTz() { $dt = new DateTime('', new \DateTimeZone('America/New_York')); $model = $this->get_model(); @@ -192,7 +192,7 @@ public function test_ar_date_time_attribute_copies_exact_tz() $this->assertEquals($dt->getTimeZone()->getName(), $dt2->getTimeZone()->getName()); } - public function test_clone() + public function testClone() { $model = $this->get_model(); $model_attribute = 'some_date'; diff --git a/test/ExpressionsTest.php b/test/ExpressionsTest.php index a2c8b54a..4245d1fc 100644 --- a/test/ExpressionsTest.php +++ b/test/ExpressionsTest.php @@ -8,135 +8,135 @@ class ExpressionsTest extends TestCase { - public function test_values() + public function testValues() { $c = new Expressions(null, 'a=? and b=?', 1, 2); $this->assertEquals([1, 2], $c->values()); } - public function test_one_variable() + public function testOneVariable() { $c = new Expressions(null, 'name=?', 'Tito'); $this->assertEquals('name=?', $c->to_s()); $this->assertEquals(['Tito'], $c->values()); } - public function test_array_variable() + public function testArrayVariable() { $c = new Expressions(null, 'name IN(?) and id=?', ['Tito', 'George'], 1); $this->assertEquals([['Tito', 'George'], 1], $c->values()); } - public function test_multiple_variables() + public function testMultipleVariables() { $c = new Expressions(null, 'name=? and book=?', 'Tito', 'Sharks'); $this->assertEquals('name=? and book=?', $c->to_s()); $this->assertEquals(['Tito', 'Sharks'], $c->values()); } - public function test_to_string() + public function testToString() { $c = new Expressions(null, 'name=? and book=?', 'Tito', 'Sharks'); $this->assertEquals('name=? and book=?', $c->to_s()); } - public function test_to_string_with_array_variable() + public function testToStringWithArrayVariable() { $c = new Expressions(null, 'name IN(?) and id=?', ['Tito', 'George'], 1); $this->assertEquals('name IN(?,?) and id=?', $c->to_s()); } - public function test_to_string_with_empty_options() + public function testToStringWithEmptyOptions() { $c = new Expressions(null, 'name=? and book=?', 'Tito', 'Sharks'); $x = []; $this->assertEquals('name=? and book=?', $c->to_s(false, $x)); } - public function test_insufficient_variables() + public function testInsufficientVariables() { $this->expectException(ExpressionsException::class); $c = new Expressions(null, 'name=? and id=?', 'Tito'); $c->to_s(); } - public function test_no_values() + public function testNoValues() { $c = new Expressions(null, "name='Tito'"); $this->assertEquals("name='Tito'", $c->to_s()); $this->assertEquals(0, count($c->values())); } - public function test_null_variable() + public function testNullVariable() { $a = new Expressions(null, 'name=?', null); $this->assertEquals('name=?', $a->to_s()); $this->assertEquals([null], $a->values()); } - public function test_zero_variable() + public function testZeroVariable() { $a = new Expressions(null, 'name=?', 0); $this->assertEquals('name=?', $a->to_s()); $this->assertEquals([0], $a->values()); } - public function test_empty_array_variable() + public function testEmptyArrayVariable() { $a = new Expressions(null, 'id IN(?)', []); $this->assertEquals('id IN(?)', $a->to_s()); $this->assertEquals([[]], $a->values()); } - public function test_ignore_invalid_parameter_marker() + public function testIgnoreInvalidParameterMarker() { $a = new Expressions(null, "question='Do you love backslashes?' and id in(?)", [1, 2]); $this->assertEquals("question='Do you love backslashes?' and id in(?,?)", $a->to_s()); } - public function test_ignore_parameter_marker_with_escaped_quote() + public function testIgnoreParameterMarkerWithEscapedQuote() { $a = new Expressions(null, "question='Do you love''s backslashes?' and id in(?)", [1, 2]); $this->assertEquals("question='Do you love''s backslashes?' and id in(?,?)", $a->to_s()); } - public function test_ignore_parameter_marker_with_backspace_escaped_quote() + public function testIgnoreParameterMarkerWithBackspaceEscapedQuote() { $a = new Expressions(null, "question='Do you love\\'s backslashes?' and id in(?)", [1, 2]); $this->assertEquals("question='Do you love\\'s backslashes?' and id in(?,?)", $a->to_s()); } - public function test_substitute() + public function testSubstitute() { $a = new Expressions(null, 'name=? and id=?', 'Tito', 1); $this->assertEquals("name='Tito' and id=1", $a->to_s(true)); } - public function test_substitute_quotes_scalars_but_not_others() + public function testSubstituteQuotesScalarsButNotOthers() { $a = new Expressions(null, 'id in(?)', [1, '2', 3.5]); $this->assertEquals("id in(1,'2',3.5)", $a->to_s(true)); } - public function test_substitute_where_value_has_question_mark() + public function testSubstituteWhereValueHasQuestionMark() { $a = new Expressions(null, 'name=? and id=?', '??????', 1); $this->assertEquals("name='??????' and id=1", $a->to_s(true)); } - public function test_substitute_array_value() + public function testSubstituteArrayValue() { $a = new Expressions(null, 'id in(?)', [1, 2]); $this->assertEquals('id in(1,2)', $a->to_s(true)); } - public function test_substitute_escapes_quotes() + public function testSubstituteEscapesQuotes() { $a = new Expressions(null, 'name=? or name in(?)', "Tito's Guild", [1, "Tito's Guild"]); $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() + public function testSubstituteEscapeQuotesWithConnectionsEscapeMethod() { try { $conn = ConnectionManager::get_connection(); @@ -149,28 +149,28 @@ public function test_substitute_escape_quotes_with_connections_escape_method() $this->assertEquals("name=$escaped", $a->to_s(true)); } - public function test_bind() + public function testBind() { $a = new Expressions(null, 'name=? and id=?', 'Tito'); $a->bind(2, 1); $this->assertEquals(['Tito', 1], $a->values()); } - public function test_bind_overwrite_existing() + public function testBindOverwriteExisting() { $a = new Expressions(null, 'name=? and id=?', 'Tito', 1); $a->bind(2, 99); $this->assertEquals(['Tito', 99], $a->values()); } - public function test_bind_invalid_parameter_number() + public function testBindInvalidParameterNumber() { $this->expectException(ExpressionsException::class); $a = new Expressions(null, 'name=?'); $a->bind(0, 99); } - public function test_substitute_using_alternate_values() + public function testSubstituteUsingAlternateValues() { $a = new Expressions(null, 'name=?', 'Tito'); $this->assertEquals("name='Tito'", $a->to_s(true)); @@ -178,25 +178,25 @@ public function test_substitute_using_alternate_values() $this->assertEquals("name='Hocus'", $a->to_s(true, $x)); } - public function test_null_value() + public function testNullValue() { $a = new Expressions(null, 'name=?', null); $this->assertEquals('name=NULL', $a->to_s(true)); } - public function test_hash_with_default_glue() + public function testHashWithDefaultGlue() { $a = new Expressions(null, ['id' => 1, 'name' => 'Tito']); $this->assertEquals('id=? AND name=?', $a->to_s()); } - public function test_hash_with_glue() + public function testHashWithGlue() { $a = new Expressions(null, ['id' => 1, 'name' => 'Tito'], ', '); $this->assertEquals('id=?, name=?', $a->to_s()); } - public function test_hash_with_array() + public function testHashWithArray() { $a = new Expressions(null, ['id' => 1, 'name' => ['Tito', 'Mexican']]); $this->assertEquals('id=? AND name IN(?,?)', $a->to_s()); diff --git a/test/HasManyThroughTest.php b/test/HasManyThroughTest.php index a55deb79..ca1cb2e3 100644 --- a/test/HasManyThroughTest.php +++ b/test/HasManyThroughTest.php @@ -8,7 +8,7 @@ class HasManyThroughTest extends DatabaseTestCase { - public function test_gh101_has_many_through() + public function testGh101HasManyThrough() { $user = User::find(1); $newsletter = Newsletter::find(1); @@ -25,7 +25,7 @@ public function test_gh101_has_many_through() ); } - public function test_gh101_has_many_through_include() + public function testGh101HasManyThroughInclude() { $user = User::find(1, [ 'include' => [ @@ -37,7 +37,7 @@ public function test_gh101_has_many_through_include() $this->assertEquals(1, $user->user_newsletters[0]->id); } - public function test_gh107_has_many_through_include_eager() + public function testGh107HasManyThroughIncludeEager() { $venue = Venue::find(1, ['include' => ['events']]); $this->assertEquals(1, $venue->events[0]->id); @@ -46,7 +46,7 @@ public function test_gh107_has_many_through_include_eager() $this->assertEquals(1, $venue->hosts[0]->id); } - public function test_gh107_has_many_though_include_eager_with_namespace() + public function testGh107HasManyThoughIncludeEagerWithNamespace() { $user = User::find(1, [ 'include' => [ diff --git a/test/InflectorTest.php b/test/InflectorTest.php index 6762b93c..e8e09a2a 100644 --- a/test/InflectorTest.php +++ b/test/InflectorTest.php @@ -13,19 +13,19 @@ public function setUp(): void $this->inflector = ActiveRecord\Inflector::instance(); } - public function test_underscorify() + public function testUnderscorify() { $this->assertEquals('rm__name__bob', $this->inflector->variablize('rm--name bob')); $this->assertEquals('One_Two_Three', $this->inflector->underscorify('OneTwoThree')); } - public function test_tableize() + public function testTableize() { $this->assertEquals('angry_people', $this->inflector->tableize('AngryPerson')); $this->assertEquals('my_sqls', $this->inflector->tableize('MySQL')); } - public function test_keyify() + public function testKeyify() { $this->assertEquals('building_type_id', $this->inflector->keyify('BuildingType')); } diff --git a/test/ModelCallbackTest.php b/test/ModelCallbackTest.php index 17eba483..7ace10fe 100644 --- a/test/ModelCallbackTest.php +++ b/test/ModelCallbackTest.php @@ -61,47 +61,60 @@ public function assert_fires_returns_false($callbacks, $only_fire, $closure) $this->assertEquals($only_fire, $intersect); } - public function test_after_construct_fires_by_default() + public function testAfterConstructFiresByDefault() { $this->assert_fires('after_construct', function ($model) { new Venue(); }); } - public function test_fire_validation_callbacks_on_insert() + public function testFireValidationCallbacksOnInsert() { $this->assert_fires(['before_validation', 'after_validation', 'before_validation_on_create', 'after_validation_on_create'], - function ($model) { $model = new Venue(); $model->save(); }); + function ($model) { + $model = new Venue(); + $model->save(); + }); } - public function test_fire_validation_callbacks_on_update() + public function testFireValidationCallbacksOnUpdate() { $this->assert_fires(['before_validation', 'after_validation', 'before_validation_on_update', 'after_validation_on_update'], - function ($model) { $model = Venue::first(); $model->save(); }); + function ($model) { + $model = Venue::first(); + $model->save(); + }); } - public function test_validation_call_backs_not_fired_due_to_bypassing_validations() + public function testValidationCallBacksNotFiredDueToBypassingValidations() { $this->assert_does_not_fire('before_validation', function ($model) { $model->save(false); }); } - public function test_before_validation_returning_false_cancels_callbacks() + public function testBeforeValidationReturningFalseCancelsCallbacks() { $this->assert_fires_returns_false(['before_validation', 'after_validation'], 'before_validation', function ($model) { $model->save(); }); } - public function test_fires_before_save_and_before_update_when_updating() + public function testFiresBeforeSaveAndBeforeUpdateWhenUpdating() { $this->assert_fires(['before_save', 'before_update'], - function ($model) { $model = Venue::first(); $model->name = 'something new'; $model->save(); }); + function ($model) { + $model = Venue::first(); + $model->name = 'something new'; + $model->save(); + }); } - public function test_before_save_returning_false_cancels_callbacks() + public function testBeforeSaveReturningFalseCancelsCallbacks() { $this->assert_fires_returns_false(['before_save', 'before_create'], 'before_save', - function ($model) { $model = new Venue(); $model->save(); }); + function ($model) { + $model = new Venue(); + $model->save(); + }); } - public function test_destroy() + public function testDestroy() { $this->assert_fires(['before_destroy', 'after_destroy'], function ($model) { $model->delete(); }); diff --git a/test/MysqlAdapterTest.php b/test/MysqlAdapterTest.php index 9000f08e..e4314363 100644 --- a/test/MysqlAdapterTest.php +++ b/test/MysqlAdapterTest.php @@ -9,7 +9,7 @@ public function setUp($connection_name=null): void parent::setUp('mysql'); } - public function test_enum() + public function testEnum() { $author_columns = $this->connection->columns('authors'); $this->assertEquals('enum', $author_columns['some_enum']->raw_type); @@ -17,14 +17,14 @@ public function test_enum() $this->assertSame(null, $author_columns['some_enum']->length); } - public function test_set_charset() + public function testSetCharset() { $connection_string = ActiveRecord\Config::instance()->get_connection($this->connection_name); $conn = ActiveRecord\Connection::instance($connection_string . '?charset=utf8'); $this->assertEquals('SET NAMES ?', $conn->last_query); } - public function test_limit_with_null_offset_does_not_contain_offset() + public function testLimitWithNullOffsetDoesNotContainOffset() { $ret = []; $sql = 'SELECT * FROM authors ORDER BY name ASC'; diff --git a/test/PgsqlAdapterTest.php b/test/PgsqlAdapterTest.php index 0df95f18..d9b460b5 100644 --- a/test/PgsqlAdapterTest.php +++ b/test/PgsqlAdapterTest.php @@ -7,33 +7,33 @@ public function setUp($connection_name=null): void parent::setUp('pgsql'); } - public function test_insert_id() + public function testInsertId() { $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() + public function testInsertIdWithParams() { $x = ['name']; $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() + public function testInsertIdShouldReturnExplicitlyInsertedId() { $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() + public function testSetCharset() { $connection_string = ActiveRecord\Config::instance()->get_connection($this->connection_name); $conn = ActiveRecord\Connection::instance($connection_string . '?charset=utf8'); $this->assertEquals("SET NAMES 'utf8'", $conn->last_query); } - public function test_gh96_columns_not_duplicated_by_index() + public function testGh96ColumnsNotDuplicatedByIndex() { $this->assertEquals(3, $this->connection->query_column_info('user_newsletters')->rowCount()); } diff --git a/test/RelationshipTest.php b/test/RelationshipTest.php index 4b92b0fa..16481834 100644 --- a/test/RelationshipTest.php +++ b/test/RelationshipTest.php @@ -8,14 +8,14 @@ use test\models\Author; use test\models\AuthorAttrAccessible; use test\models\AwesomePerson; +use test\models\Book; use test\models\Employee; use test\models\Event; use test\models\Host; use test\models\JoinBook; use test\models\Position; -use test\models\Venue; -use test\models\Book; use test\models\Property; +use test\models\Venue; class NotModel { @@ -31,7 +31,7 @@ class AuthorWithNonModelRelationship extends ActiveRecord\Model class RelationshipTest extends DatabaseTestCase { protected $relationship_name; - protected $relationship_names = ['has_many', 'belongs_to', 'has_one']; + protected $relationship_names = ['HasMany', 'BelongsTo', 'HasOne']; public function setUp($connection_name=null): void { @@ -57,15 +57,15 @@ protected function get_relationship($type=null) } switch ($type) { - case 'belongs_to': + case 'BelongsTo': $ret = Event::find(5); break; - case 'has_one': + case 'HasOne': $ret = Employee::find(1); break; - case 'has_many': + case 'HasMany': $ret = Venue::find(2); break; } @@ -95,12 +95,12 @@ protected function assert_default_has_one($employee, $association_name='position $this->assertNotNull($employee->id, $employee->$association_name->title); } - public function test_has_many_basic() + public function testHasManyBasic() { $this->assert_default_has_many($this->get_relationship()); } - public function test_gh_256_eager_loading_three_levels_deep() + public function testGh256EagerLoadingThreeLevelsDeep() { /* Before fix Undefined offset: 0 */ $conditions['include'] = ['events'=>['host'=>['events']]]; @@ -119,50 +119,50 @@ public function test_gh_256_eager_loading_three_levels_deep() $this->assertEquals('Yeah Yeah Yeahs', $bill_events[0]->title); } - public function test_joins_on_model_via_undeclared_association() + public function testJoinsOnModelViaUndeclaredAssociation() { $this->expectException(RelationshipException::class); JoinBook::first(['joins' => ['undeclared']]); } - public function test_joins_only_loads_given_model_attributes() + public function testJoinsOnlyLoadsGivenModelAttributes() { $x = Event::first(['joins' => ['venue']]); $this->assert_sql_has('SELECT events.*', Event::table()->last_sql); $this->assertFalse(array_key_exists('city', $x->attributes())); } - public function test_joins_combined_with_select_loads_all_attributes() + public function testJoinsCombinedWithSelectLoadsAllAttributes() { $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->assertTrue(array_key_exists('venue_city', $x->attributes())); } - public function test_belongs_to_basic() + public function testBelongsToBasic() { $this->assert_default_belongs_to($this->get_relationship()); } - public function test_belongs_to_returns_null_when_no_record() + public function testBelongsToReturnsNullWhenNoRecord() { $event = Event::find(6); $this->assertNull($event->venue); } - public function test_belongs_to_returns_null_when_foreign_key_is_null() + public function testBelongsToReturnsNullWhenForeignKeyIsNull() { $event = Event::create(['title' => 'venueless event', 'host_id'=>1]); $this->assertNull($event->venue); } - public function test_belongs_to_with_explicit_class_name() + public function testBelongsToWithExplicitClassName() { Event::$belongs_to = [['explicit_class_name', 'class_name' => 'Venue']]; $this->assert_default_belongs_to($this->get_relationship(), 'explicit_class_name'); } - public function test_belongs_to_with_explicit_foreign_key() + public function testBelongsToWithExplicitForeignKey() { $old = Book::$belongs_to; Book::$belongs_to = [['explicit_author', 'class_name' => 'Author', 'foreign_key' => 'secondary_author_id']]; @@ -174,7 +174,7 @@ public function test_belongs_to_with_explicit_foreign_key() Book::$belongs_to = $old; } - public function test_belongs_to_with_select() + public function testBelongsToWithSelect() { Event::$belongs_to[0]['select'] = 'id, city'; $event = $this->get_relationship(); @@ -188,7 +188,7 @@ public function test_belongs_to_with_select() } } - public function test_belongs_to_with_readonly() + public function testBelongsToWithReadonly() { Event::$belongs_to[0]['readonly'] = true; $event = $this->get_relationship(); @@ -204,13 +204,13 @@ public function test_belongs_to_with_readonly() $this->assertEquals($event->venue->name, 'new name'); } - public function test_belongs_to_with_plural_attribute_name() + public function testBelongsToWithPluralAttributeName() { Event::$belongs_to = [['venues', 'class_name' => 'Venue']]; $this->assert_default_belongs_to($this->get_relationship(), 'venues'); } - public function test_belongs_to_with_conditions_and_non_qualifying_record() + public function testBelongsToWithConditionsAndNonQualifyingRecord() { Event::$belongs_to[0]['conditions'] = "state = 'NY'"; $event = $this->get_relationship(); @@ -218,13 +218,13 @@ public function test_belongs_to_with_conditions_and_non_qualifying_record() $this->assertNull($event->venue); } - public function test_belongs_to_with_conditions_and_qualifying_record() + public function testBelongsToWithConditionsAndQualifyingRecord() { Event::$belongs_to[0]['conditions'] = "state = 'PA'"; $this->assert_default_belongs_to($this->get_relationship()); } - public function test_belongs_to_build_association() + public function testBelongsToBuildAssociation() { $event = $this->get_relationship(); $values = ['city' => 'Richmond', 'state' => 'VA']; @@ -232,14 +232,14 @@ public function test_belongs_to_build_association() $this->assertEquals($values, array_intersect_key($values, $venue->attributes())); } - public function test_has_many_build_association() + public function testHasManyBuildAssociation() { $author = Author::first(); $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() + public function testBelongsToCreateAssociation() { $event = $this->get_relationship(); $values = ['city' => 'Richmond', 'state' => 'VA', 'name' => 'Club 54', 'address' => '123 street']; @@ -247,7 +247,7 @@ public function test_belongs_to_create_association() $this->assertNotNull($venue->id); } - public function test_build_association_overwrites_guarded_foreign_keys() + public function testBuildAssociationOverwritesGuardedForeignKeys() { $author = new AuthorAttrAccessible(); $author->save(); @@ -257,7 +257,7 @@ public function test_build_association_overwrites_guarded_foreign_keys() $this->assertNotNull($book->author_id); } - public function test_belongs_to_can_be_self_referential() + public function testBelongsToCanBeSelfReferential() { Author::$belongs_to = [['parent_author', 'class_name' => 'Author', 'foreign_key' => 'parent_author_id']]; $author = Author::find(1); @@ -265,20 +265,20 @@ public function test_belongs_to_can_be_self_referential() $this->assertEquals(3, $author->parent_author->id); } - public function test_belongs_to_with_an_invalid_option() + public function testBelongsToWithAnInvalidOption() { Event::$belongs_to[0]['joins'] = 'venue'; $event = Event::first()->venue; $this->assert_sql_doesnt_has('INNER JOIN venues ON(events.venue_id = venues.id)', Event::table()->last_sql); } - public function test_has_many_with_explicit_class_name() + public function testHasManyWithExplicitClassName() { Venue::$has_many = [['explicit_class_name', 'class_name' => 'Event', 'order' => 'id asc']]; $this->assert_default_has_many($this->get_relationship(), 'explicit_class_name'); } - public function test_has_many_with_select() + public function testHasManyWithSelect() { Venue::$has_many[0]['select'] = 'title, type'; $venue = $this->get_relationship(); @@ -292,7 +292,7 @@ public function test_has_many_with_select() } } - public function test_has_many_with_readonly() + public function testHasManyWithReadonly() { Venue::$has_many[0]['readonly'] = true; $venue = $this->get_relationship(); @@ -308,13 +308,13 @@ public function test_has_many_with_readonly() $this->assertEquals($venue->events[0]->description, 'new desc'); } - public function test_has_many_with_singular_attribute_name() + public function testHasManyWithSingularAttributeName() { Venue::$has_many = [['event', 'class_name' => 'Event', 'order' => 'id asc']]; $this->assert_default_has_many($this->get_relationship(), 'event'); } - public function test_has_many_with_conditions_and_non_qualifying_record() + public function testHasManyWithConditionsAndNonQualifyingRecord() { Venue::$has_many[0]['conditions'] = "title = 'pr0n @ railsconf'"; $venue = $this->get_relationship(); @@ -322,7 +322,7 @@ public function test_has_many_with_conditions_and_non_qualifying_record() $this->assertTrue(empty($venue->events), is_array($venue->events)); } - public function test_has_many_with_conditions_and_qualifying_record() + public function testHasManyWithConditionsAndQualifyingRecord() { Venue::$has_many[0]['conditions'] = "title = 'Yeah Yeah Yeahs'"; $venue = $this->get_relationship(); @@ -330,7 +330,7 @@ public function test_has_many_with_conditions_and_qualifying_record() $this->assertEquals($venue->events[0]->title, 'Yeah Yeah Yeahs'); } - public function test_has_many_with_sql_clause_options() + public function testHasManyWithSqlClauseOptions() { Venue::$has_many[0] = ['events', 'select' => 'type', @@ -341,14 +341,14 @@ public function test_has_many_with_sql_clause_options() $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() + public function testHasManyThrough() { $hosts = Venue::find(2)->hosts; $this->assertEquals(2, $hosts[0]->id); $this->assertEquals(3, $hosts[1]->id); } - public function test_gh27_has_many_through_with_explicit_keys() + public function testGh27HasManyThroughWithExplicitKeys() { $property = Property::first(); @@ -356,7 +356,7 @@ public function test_gh27_has_many_through_with_explicit_keys() $this->assertEquals(2, $property->amenities[1]->amenity_id); } - public function test_gh16_has_many_through_inside_a_loop_should_not_cause_an_exception() + public function testGh16HasManyThroughInsideALoopShouldNotCauseAnException() { $count = 0; @@ -367,7 +367,7 @@ public function test_gh16_has_many_through_inside_a_loop_should_not_cause_an_exc $this->assertTrue($count >= 5); } - public function test_has_many_through_no_association() + public function testHasManyThroughNoAssociation() { $this->expectException(HasManyThroughAssociationException::class); Event::$belongs_to = [['host']]; @@ -378,7 +378,7 @@ public function test_has_many_through_no_association() $this->assertTrue(count($n) > 0); } - public function test_has_many_through_with_select() + public function testHasManyThroughWithSelect() { Event::$belongs_to = [['host']]; Venue::$has_many[1] = ['hosts', 'through' => 'events', 'select' => 'hosts.*, events.*']; @@ -388,7 +388,7 @@ public function test_has_many_through_with_select() $this->assertNotNull($venue->hosts[0]->title); } - public function test_has_many_through_with_conditions() + public function testHasManyThroughWithConditions() { Event::$belongs_to = [['host']]; Venue::$has_many[1] = ['hosts', 'through' => 'events', 'conditions' => ['events.title != ?', 'Love Overboard']]; @@ -398,7 +398,7 @@ public function test_has_many_through_with_conditions() $this->assert_sql_has('events.title !=', ActiveRecord\Table::load(Host::class)->last_sql); } - public function test_has_many_through_using_source() + public function testHasManyThroughUsingSource() { Event::$belongs_to = [['host']]; Venue::$has_many[1] = ['hostess', 'through' => 'events', 'source' => 'host']; @@ -407,7 +407,7 @@ public function test_has_many_through_using_source() $this->assertTrue(count($venue->hostess) > 0); } - public function test_has_many_through_with_invalid_class_name() + public function testHasManyThroughWithInvalidClassName() { $this->expectException(\ReflectionException::class); Event::$belongs_to = [['host']]; @@ -417,13 +417,13 @@ public function test_has_many_through_with_invalid_class_name() $this->get_relationship()->hosts; } - public function test_has_many_with_joins() + public function testHasManyWithJoins() { $x = Venue::first(['joins' => ['events']]); $this->assert_sql_has('INNER JOIN events ON(venues.id = events.venue_id)', Venue::table()->last_sql); } - public function test_has_many_with_explicit_keys() + public function testHasManyWithExplicitKeys() { $old = Author::$has_many; Author::$has_many = [['explicit_books', 'class_name' => 'Book', 'primary_key' => 'parent_author_id', 'foreign_key' => 'secondary_author_id']]; @@ -437,18 +437,18 @@ public function test_has_many_with_explicit_keys() Author::$has_many = $old; } - public function test_has_one_basic() + public function testHasOneBasic() { $this->assert_default_has_one($this->get_relationship()); } - public function test_has_one_with_explicit_class_name() + public function testHasOneWithExplicitClassName() { Employee::$has_one = [['explicit_class_name', 'class_name' => 'Position']]; $this->assert_default_has_one($this->get_relationship(), 'explicit_class_name'); } - public function test_has_one_with_select() + public function testHasOneWithSelect() { Employee::$has_one[0]['select'] = 'title'; $employee = $this->get_relationship(); @@ -462,7 +462,7 @@ public function test_has_one_with_select() } } - public function test_has_one_with_order() + public function testHasOneWithOrder() { Employee::$has_one[0]['order'] = 'title'; $employee = $this->get_relationship(); @@ -470,7 +470,7 @@ public function test_has_one_with_order() $this->assert_sql_has('ORDER BY title', Position::table()->last_sql); } - public function test_has_one_with_conditions_and_non_qualifying_record() + public function testHasOneWithConditionsAndNonQualifyingRecord() { Employee::$has_one[0]['conditions'] = "title = 'programmer'"; $employee = $this->get_relationship(); @@ -478,13 +478,13 @@ public function test_has_one_with_conditions_and_non_qualifying_record() $this->assertNull($employee->position); } - public function test_has_one_with_conditions_and_qualifying_record() + public function testHasOneWithConditionsAndQualifyingRecord() { Employee::$has_one[0]['conditions'] = "title = 'physicist'"; $this->assert_default_has_one($this->get_relationship()); } - public function test_has_one_with_readonly() + public function testHasOneWithReadonly() { Employee::$has_one[0]['readonly'] = true; $employee = $this->get_relationship(); @@ -500,7 +500,7 @@ public function test_has_one_with_readonly() $this->assertEquals($employee->position->title, 'new title'); } - public function test_has_one_can_be_self_referential() + public function testHasOneCanBeSelfReferential() { Author::$has_one[1] = ['parent_author', 'class_name' => 'Author', 'foreign_key' => 'parent_author_id']; $author = Author::find(1); @@ -508,13 +508,13 @@ public function test_has_one_can_be_self_referential() $this->assertEquals(3, $author->parent_author->id); } - public function test_has_one_with_joins() + public function testHasOneWithJoins() { $x = Employee::first(['joins' => ['position']]); $this->assert_sql_has('INNER JOIN positions ON(employees.id = positions.employee_id)', Employee::table()->last_sql); } - public function test_has_one_with_explicit_keys() + public function testHasOneWithExplicitKeys() { Book::$has_one = [['explicit_author', 'class_name' => 'Author', 'foreign_key' => 'parent_author_id', 'primary_key' => 'secondary_author_id']]; @@ -523,32 +523,32 @@ public function test_has_one_with_explicit_keys() $this->assertTrue(false !== strpos(ActiveRecord\Table::load(Author::class)->last_sql, 'parent_author_id')); } - public function test_dont_attempt_to_load_if_all_foreign_keys_are_null() + public function testDontAttemptToLoadIfAllForeignKeysAreNull() { $event = new Event(); $event->venue; $this->assert_sql_doesnt_has($this->connection->last_query, 'is IS NULL'); } - public function test_relationship_on_table_with_underscores() + public function testRelationshipOnTableWithUnderscores() { $this->assertEquals(1, Author::find(1)->awesome_person->is_awesome); } - public function test_has_one_through() + public function testHasOneThrough() { Venue::$has_many = [['events'], ['hosts', 'through' => 'events']]; $venue = Venue::first(); $this->assertTrue(count($venue->hosts) > 0); } - public function test_throw_error_if_relationship_is_not_a_model() + public function testThrowErrorIfRelationshipIsNotAModel() { $this->expectException(RelationshipException::class); AuthorWithNonModelRelationship::first()->books; } - public function test_gh93_and_gh100_eager_loading_respects_association_options() + public function testGh93AndGh100EagerLoadingRespectsAssociationOptions() { Venue::$has_many = [['events', 'class_name' => 'Event', 'order' => 'id asc', 'conditions' => ['length(title) = ?', 14]]]; $venues = Venue::find([2, 6], ['include' => 'events']); @@ -557,7 +557,7 @@ public function test_gh93_and_gh100_eager_loading_respects_association_options() $this->assertEquals(1, count($venues[0]->events)); } - public function test_eager_loading_has_many_x() + public function testEagerLoadingHasManyX() { $venues = Venue::find([2, 6], ['include' => 'events']); $this->assert_sql_has('WHERE venue_id IN(?,?)', ActiveRecord\Table::load(Event::class)->last_sql); @@ -569,7 +569,7 @@ public function test_eager_loading_has_many_x() $this->assertEquals(2, count($venues[0]->events)); } - public function test_eager_loading_has_many_with_no_related_rows() + public function testEagerLoadingHasManyWithNoRelatedRows() { $venues = Venue::find([7, 8], ['include' => 'events']); @@ -581,7 +581,7 @@ public function test_eager_loading_has_many_with_no_related_rows() $this->assert_sql_has('WHERE venue_id IN(?,?)', ActiveRecord\Table::load(Event::class)->last_sql); } - public function test_eager_loading_has_many_array_of_includes() + public function testEagerLoadingHasManyArrayOfIncludes() { Author::$has_many = [['books'], ['awesome_people']]; $authors = Author::find([1, 2], ['include' => ['books', 'awesome_people']]); @@ -605,7 +605,7 @@ public function test_eager_loading_has_many_array_of_includes() $this->assert_sql_has('WHERE author_id IN(?,?)', ActiveRecord\Table::load(AwesomePerson::class)->last_sql); } - public function test_eager_loading_has_many_nested() + public function testEagerLoadingHasManyNested() { $venues = Venue::find([1, 2], ['include' => ['events' => ['host']]]); @@ -625,7 +625,7 @@ public function test_eager_loading_has_many_nested() $this->assert_sql_has('WHERE id IN(?,?,?)', ActiveRecord\Table::load(Host::class)->last_sql); } - public function test_eager_loading_belongs_to() + public function testEagerLoadingBelongsTo() { $events = Event::find([1, 2, 3, 5, 7], ['include' => 'venue']); @@ -636,7 +636,7 @@ public function test_eager_loading_belongs_to() $this->assert_sql_has('WHERE id IN(?,?,?,?,?)', ActiveRecord\Table::load(Venue::class)->last_sql); } - public function test_eager_loading_belongs_to_array_of_includes() + public function testEagerLoadingBelongsToArrayOfIncludes() { $events = Event::find([1, 2, 3, 5, 7], ['include' => ['venue', 'host']]); @@ -650,7 +650,7 @@ public function test_eager_loading_belongs_to_array_of_includes() $this->assert_sql_has('WHERE id IN(?,?,?,?,?)', ActiveRecord\Table::load(Venue::class)->last_sql); } - public function test_eager_loading_belongs_to_nested() + public function testEagerLoadingBelongsToNested() { Author::$has_many = [['awesome_people']]; @@ -666,7 +666,7 @@ public function test_eager_loading_belongs_to_nested() $this->assert_sql_has('WHERE author_id IN(?,?)', ActiveRecord\Table::load(AwesomePerson::class)->last_sql); } - public function test_eager_loading_belongs_to_with_no_related_rows() + public function testEagerLoadingBelongsToWithNoRelatedRows() { $e1 = Event::create(['venue_id' => 200, 'host_id' => 200, 'title' => 'blah', 'type' => 'Music']); $e2 = Event::create(['venue_id' => 200, 'host_id' => 200, 'title' => 'blah2', 'type' => 'Music']); @@ -681,7 +681,7 @@ public function test_eager_loading_belongs_to_with_no_related_rows() $this->assert_sql_has('WHERE id IN(?,?)', ActiveRecord\Table::load(Venue::class)->last_sql); } - public function test_eager_loading_clones_related_objects() + public function testEagerLoadingClonesRelatedObjects() { $events = Event::find([2, 3], ['include' => ['venue']]); @@ -693,7 +693,7 @@ public function test_eager_loading_clones_related_objects() $this->assertNotEquals(spl_object_hash($venue), spl_object_hash($events[1]->venue)); } - public function test_eager_loading_clones_nested_related_objects() + public function testEagerLoadingClonesNestedRelatedObjects() { $venues = Venue::find([1, 2, 6, 9], ['include' => ['events' => ['host']]]); @@ -706,7 +706,7 @@ public function test_eager_loading_clones_nested_related_objects() $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() + public function testGh23RelationshipsWithJoinsToSameTableShouldAliasTableName() { $old = Book::$belongs_to; Book::$belongs_to = [ @@ -727,14 +727,14 @@ public function test_gh_23_relationships_with_joins_to_same_table_should_alias_t Book::$belongs_to = $old; } - public function test_gh_40_relationships_with_joins_aliases_table_name_in_conditions() + public function testGh40RelationshipsWithJoinsAliasesTableNameInConditions() { $event = Event::find(1, ['joins' => ['venue']]); $this->assertEquals($event->id, $event->venue->id); } - public function test_dont_attempt_eager_load_when_record_does_not_exist() + public function testDontAttemptEagerLoadWhenRecordDoesNotExist() { $this->expectException(RecordNotFound::class); Author::find(999999, ['include' => ['books']]); diff --git a/test/SQLBuilderTest.php b/test/SQLBuilderTest.php index a4429d60..5c9e7ce2 100644 --- a/test/SQLBuilderTest.php +++ b/test/SQLBuilderTest.php @@ -37,89 +37,89 @@ public function assert_conditions($expected_sql, $values, $underscored_string, $ } } - public function test_nothing() + public function testNothing() { $this->assertEquals('SELECT * FROM authors', (string) $this->sql); } - public function test_where_with_array() + public function testWhereWithArray() { $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->assertEquals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); } - public function test_where_with_hash() + public function testWhereWithHash() { $this->sql->where(['id' => 1, 'name' => 'Tito']); $this->assert_sql_has('SELECT * FROM authors WHERE id=? AND name=?', (string) $this->sql); $this->assertEquals([1, 'Tito'], $this->sql->get_where_values()); } - public function test_where_with_hash_and_array() + public function testWhereWithHashAndArray() { $this->sql->where(['id' => 1, 'name' => ['Tito', 'Mexican']]); $this->assert_sql_has('SELECT * FROM authors WHERE id=? AND name IN(?,?)', (string) $this->sql); $this->assertEquals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); } - public function test_gh134_where_with_hash_and_null() + public function testGh134WhereWithHashAndNull() { $this->sql->where(['id' => 1, 'name' => null]); $this->assert_sql_has('SELECT * FROM authors WHERE id=? AND name IS ?', (string) $this->sql); $this->assertEquals([1, null], $this->sql->get_where_values()); } - public function test_where_with_null() + public function testWhereWithNull() { $this->sql->where(null); $this->assertEquals('SELECT * FROM authors', (string) $this->sql); } - public function test_where_with_no_args() + public function testWhereWithNoArgs() { $this->sql->where(); $this->assertEquals('SELECT * FROM authors', (string) $this->sql); } - public function test_order() + public function testOrder() { $this->sql->order('name'); $this->assertEquals('SELECT * FROM authors ORDER BY name', (string) $this->sql); } - public function test_limit() + public function testLimit() { $this->sql->limit(10)->offset(1); $this->assertEquals($this->connection->limit('SELECT * FROM authors', 1, 10), (string) $this->sql); } - public function test_select() + public function testSelect() { $this->sql->select('id,name'); $this->assertEquals('SELECT id,name FROM authors', (string) $this->sql); } - public function test_joins() + public function testJoins() { $join = 'inner join books on(authors.id=books.author_id)'; $this->sql->joins($join); $this->assertEquals("SELECT * FROM authors $join", (string) $this->sql); } - public function test_group() + public function testGroup() { $this->sql->group('name'); $this->assertEquals('SELECT * FROM authors GROUP BY name', (string) $this->sql); } - public function test_having() + public function testHaving() { $this->sql->having("created_at > '2009-01-01'"); $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() + public function testAllClausesAfterWhereShouldBeCorrectlyOrdered() { $this->sql->limit(10)->offset(1); $this->sql->having("created_at > '2009-01-01'"); @@ -129,32 +129,32 @@ public function test_all_clauses_after_where_should_be_correctly_ordered() $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); } - public function test_insert_requires_hash() + public function testInsertRequiresHash() { $this->expectException(ActiveRecordException::class); $this->sql->insert([1]); } - public function test_insert() + public function testInsert() { $this->sql->insert(['id' => 1, 'name' => 'Tito']); $this->assert_sql_has('INSERT INTO authors(id,name) VALUES(?,?)', (string) $this->sql); } - public function test_insert_with_null() + public function testInsertWithNull() { $this->sql->insert(['id' => 1, 'name' => null]); $this->assert_sql_has('INSERT INTO authors(id,name) VALUES(?,?)', $this->sql->to_s()); } - public function test_update_with_hash() + public function testUpdateWithHash() { $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->assertEquals([1, 'Tito', 'Tito', 'Mexican'], $this->sql->bind_values()); } - public function test_update_with_limit_and_order() + public function testUpdateWithLimitAndOrder() { if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with UPDATE operation'); @@ -164,39 +164,39 @@ public function test_update_with_limit_and_order() $this->assert_sql_has('UPDATE authors SET id=? ORDER BY name asc LIMIT 1', $this->sql->to_s()); } - public function test_update_with_string() + public function testUpdateWithString() { $this->sql->update("name='Bob'"); $this->assert_sql_has("UPDATE authors SET name='Bob'", $this->sql->to_s()); } - public function test_update_with_null() + public function testUpdateWithNull() { $this->sql->update(['id' => 1, 'name' => null])->where('id=1'); $this->assert_sql_has('UPDATE authors SET id=?, name=? WHERE id=1', $this->sql->to_s()); } - public function test_delete() + public function testDelete() { $this->sql->delete(); $this->assertEquals('DELETE FROM authors', $this->sql->to_s()); } - public function test_delete_with_where() + public function testDeleteWithWhere() { $this->sql->delete('id=? or name in(?)', 1, ['Tito', 'Mexican']); $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() + public function testDeleteWithHash() { $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->assertEquals([1, 'Tito', 'Mexican'], $this->sql->get_where_values()); } - public function test_delete_with_limit_and_order() + public function testDeleteWithLimitAndOrder() { if (!$this->connection->accepts_limit_and_order_for_update_and_delete()) { $this->markTestSkipped('Only MySQL & Sqlite accept limit/order with DELETE operation'); @@ -206,7 +206,7 @@ public function test_delete_with_limit_and_order() $this->assert_sql_has('DELETE FROM authors WHERE id=? ORDER BY name asc LIMIT 1', $this->sql->to_s()); } - public function test_reverse_order() + public function testReverseOrder() { $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')); @@ -216,48 +216,48 @@ public function test_reverse_order() $this->assertEquals(' ', SQLBuilder::reverse_order(' ')); } - public function test_create_conditions_from_underscored_string() + public function testCreateConditionsFromUnderscoredString() { $this->assert_conditions('id=? AND name=? OR z=?', [1, 'Tito', 'X'], 'id_and_name_or_z'); $this->assert_conditions('id=?', [1], 'id'); $this->assert_conditions('id IN(?)', [[1, 2]], 'id'); } - public function test_create_conditions_from_underscored_string_with_nulls() + public function testCreateConditionsFromUnderscoredStringWithNulls() { $this->assert_conditions('id=? AND name IS NULL', [1, null], 'id_and_name'); } - public function test_create_conditions_from_underscored_string_with_missing_args() + public function testCreateConditionsFromUnderscoredStringWithMissingArgs() { $this->assert_conditions('id=? AND name IS NULL OR z IS NULL', [1, null], 'id_and_name_or_z'); $this->assert_conditions('id IS NULL', [], 'id'); } - public function test_create_conditions_from_underscored_string_with_blank() + public function testCreateConditionsFromUnderscoredStringWithBlank() { $this->assert_conditions('id=? AND name IS NULL OR z=?', [1, null, ''], 'id_and_name_or_z'); } - public function test_create_conditions_from_underscored_string_invalid() + public function testCreateConditionsFromUnderscoredStringInvalid() { $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() + public function testCreateConditionsFromUnderscoredStringWithMappedColumns() { $this->assert_conditions('id=? AND name=?', [1, 'Tito'], 'id_and_my_name', ['my_name' => 'name']); } - public function test_create_hash_from_underscored_string() + public function testCreateHashFromUnderscoredString() { $values = [1, 'Tito']; $hash = SQLBuilder::create_hash_from_underscored_string('id_and_my_name', $values); $this->assertEquals(['id' => 1, 'my_name' => 'Tito'], $hash); } - public function test_create_hash_from_underscored_string_with_mapped_columns() + public function testCreateHashFromUnderscoredStringWithMappedColumns() { $values = [1, 'Tito']; $map = ['my_name' => 'name']; @@ -265,7 +265,7 @@ public function test_create_hash_from_underscored_string_with_mapped_columns() $this->assertEquals(['id' => 1, 'name' => 'Tito'], $hash); } - public function test_where_with_joins_prepends_table_name_to_fields() + public function testWhereWithJoinsPrependsTableNameToFields() { $joins = 'INNER JOIN books ON (books.id = authors.id)'; // joins needs to be called prior to where diff --git a/test/SerializationTest.php b/test/SerializationTest.php index 1012c405..27add6c5 100644 --- a/test/SerializationTest.php +++ b/test/SerializationTest.php @@ -1,7 +1,6 @@ to_a(); } - public function test_only() + public function testOnly() { $this->assertArrayHasKey('special', $this->_a(['only' => ['name', 'special']])); $this->assertArrayHasKey('name', $this->_a(['only' => ['name', 'special']])); } - public function test_only_not_array() + public function testOnlyNotArray() { $this->assertArrayHasKey('name', $this->_a(['only' => 'name'])); } - public function test_only_should_only_apply_to_attributes() + public function testOnlyShouldOnlyApplyToAttributes() { $this->assertArrayHasKey('author', $this->_a(['only' => 'name', 'include' => 'author'])); $this->assertArrayHasKey('name', $this->_a(['only' => 'name', 'include' => 'author'])); @@ -40,29 +39,29 @@ public function test_only_should_only_apply_to_attributes() $this->assertArrayHasKey('upper_name', $this->_a(['only' => 'book_id', 'methods' => 'upper_name'])); } - public function test_only_overrides_except() + public function testOnlyOverridesExcept() { $this->assertArrayHasKey('name', $this->_a(['only' => 'name', 'except' => 'name'])); } - public function test_except() + public function testExcept() { $this->assertArrayNotHasKey('name', $this->_a(['except' => ['name', 'special']])); $this->assertArrayNotHasKey('special', $this->_a(['except' => ['name', 'special']])); } - public function test_except_takes_a_string() + public function testExceptTakesAString() { $this->assertArrayNotHasKey('name', $this->_a(['except' => 'name'])); } - public function test_methods() + public function testMethods() { $a = $this->_a(['methods' => ['upper_name']]); $this->assertEquals('ANCIENT ART OF MAIN TANKING', $a['upper_name']); } - public function test_methods_takes_a_string() + public function testMethodsTakesAString() { $a = $this->_a(['methods' => 'upper_name']); $this->assertEquals('ANCIENT ART OF MAIN TANKING', $a['upper_name']); @@ -70,19 +69,19 @@ public function test_methods_takes_a_string() // methods added last should have value of the method in our json // rather than the regular attribute value - public function test_methods_method_same_as_attribute() + public function testMethodsMethodSameAsAttribute() { $a = $this->_a(['methods' => 'name']); $this->assertEquals('ancient art of main tanking', $a['name']); } - public function test_include() + public function testInclude() { $a = $this->_a(['include' => ['author']]); $this->assertArrayHasKey('parent_author_id', $a['author']); } - public function test_include_nested_with_nested_options() + public function testIncludeNestedWithNestedOptions() { $a = $this->_a( ['include' => ['events' => ['except' => 'title', 'include' => ['host' => ['only' => 'id']]]]], @@ -93,28 +92,28 @@ public function test_include_nested_with_nested_options() $this->assertEquals(['id' => 4], $a['events'][0]['host']); } - public function test_datetime_values_get_converted_to_strings() + public function testDatetimeValuesGetConvertedToStrings() { $now = new DateTime(); $a = $this->_a(['only' => 'created_at'], new Author(['created_at' => $now])); $this->assertEquals($now->format(\ActiveRecord\Serialize\Serialization::$DATETIME_FORMAT), $a['created_at']); } - public function test_to_json() + public function testToJson() { $book = Book::find(1); $json = $book->to_json(); $this->assertEquals($book->attributes(), (array) json_decode($json)); } - public function test_to_json_include_root() + public function testToJsonIncludeRoot() { $this->assertNotNull(json_decode(Book::find(1)->to_json([ 'include_root' => true ]))->{'test\models\book'}); } - public function test_to_xml_include() + public function testToXmlInclude() { $xml = Host::find(4)->to_xml(['include' => 'events']); $decoded = get_object_vars(new SimpleXMLElement($xml)); @@ -122,20 +121,20 @@ public function test_to_xml_include() $this->assertEquals(3, count($decoded['events']->event)); } - public function test_to_xml() + public function testToXml() { $book = Book::find(1); $this->assertEquals($book->attributes(), get_object_vars(new SimpleXMLElement($book->to_xml()))); } - public function test_to_array() + public function testToArray() { $book = Book::find(1); $array = $book->to_array(); $this->assertEquals($book->attributes(), $array); } - public function test_to_array_include_root() + public function testToArrayIncludeRoot() { $book = Book::find(1); $array = $book->to_array(['include_root'=>true]); @@ -143,7 +142,7 @@ public function test_to_array_include_root() $this->assertEquals($book_attributes, $array); } - public function test_to_array_except() + public function testToArrayExcept() { $book = Book::find(1); $array = $book->to_array(['except' => ['special']]); @@ -152,63 +151,63 @@ public function test_to_array_except() $this->assertEquals($book_attributes, $array); } - public function test_works_with_datetime() + public function testWorksWithDatetime() { Author::find(1)->update_attribute('created_at', new DateTime()); $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() + public function testToXmlSkipInstruct() { $this->assertSame(false, strpos(Book::find(1)->to_xml(['skip_instruct' => true]), 'assertSame(0, strpos(Book::find(1)->to_xml(['skip_instruct' => false]), 'assertStringContainsString('lasers', Author::first()->to_xml(['only_method' => 'return_something'])); } - public function test_to_csv() + public function testToCsv() { $book = Book::find(1); $this->assertEquals('1,1,2,"Ancient Art of Main Tanking","Random House",0,0', $book->to_csv()); } - public function test_to_csv_only_header() + public function testToCsvOnlyHeader() { $book = Book::find(1); $this->assertEquals('book_id,author_id,secondary_author_id,name,publisher,numeric_test,special', - $book->to_csv(['only_header'=>true]) - ); + $book->to_csv(['only_header'=>true]) + ); } - public function test_to_csv_only_method() + public function testToCsvOnlyMethod() { $book = Book::find(1); $this->assertEquals('2,"Ancient Art of Main Tanking"', - $book->to_csv(['only'=>['name', 'secondary_author_id']]) - ); + $book->to_csv(['only'=>['name', 'secondary_author_id']]) + ); } - public function test_to_csv_only_method_on_header() + public function testToCsvOnlyMethodOnHeader() { $book = Book::find(1); $this->assertEquals('secondary_author_id,name', - $book->to_csv(['only'=>['secondary_author_id', 'name'], - 'only_header'=>true]) - ); + $book->to_csv(['only'=>['secondary_author_id', 'name'], + 'only_header'=>true]) + ); } - public function test_to_csv_with_custom_delimiter() + public function testToCsvWithCustomDelimiter() { $book = Book::find(1); CsvSerializer::$delimiter=';'; $this->assertEquals('1;1;2;"Ancient Art of Main Tanking";"Random House";0;0', $book->to_csv()); } - public function test_to_csv_with_custom_enclosure() + public function testToCsvWithCustomEnclosure() { $book = Book::find(1); CsvSerializer::$delimiter=','; diff --git a/test/SqliteAdapterTest.php b/test/SqliteAdapterTest.php index 96e6f935..f866bc7b 100644 --- a/test/SqliteAdapterTest.php +++ b/test/SqliteAdapterTest.php @@ -2,7 +2,6 @@ use ActiveRecord\Connection; use ActiveRecord\Exception\ConnectionException; -use ActiveRecord\Exception\DatabaseException; class SqliteAdapterTest extends AdapterTestCase { @@ -33,7 +32,7 @@ public function testConnectToInvalidDatabaseShouldNotCreateDbFile() } } - public function test_limit_with_0_offset_does_not_contain_offset() + public function testLimitWith0OffsetDoesNotContainOffset() { $ret = []; $sql = 'SELECT * FROM authors ORDER BY name ASC'; @@ -42,7 +41,7 @@ public function test_limit_with_0_offset_does_not_contain_offset() $this->assertTrue(false !== strpos($this->connection->last_query, 'LIMIT 1')); } - public function test_gh183_sqliteadapter_autoincrement() + public function testGh183SqliteadapterAutoincrement() { // defined in lowercase: id integer not null primary key $columns = $this->connection->columns('awesome_people'); @@ -61,20 +60,20 @@ public function test_gh183_sqliteadapter_autoincrement() $this->assertTrue($columns['id']->auto_increment); } - public function test_datetime_to_string() + public function testDatetimeToString() { $datetime = '2009-01-01 01:01:01'; $this->assertEquals($datetime, $this->connection->datetime_to_string(date_create($datetime))); } - public function test_date_to_string() + public function testDateToString() { $datetime = '2009-01-01'; $this->assertEquals($datetime, $this->connection->date_to_string(date_create($datetime))); } // not supported - public function test_connect_with_port() + public function testConnectWithPort() { $this->expectNotToPerformAssertions(); } diff --git a/test/UtilsTest.php b/test/UtilsTest.php index 5202bec9..6aaf4863 100644 --- a/test/UtilsTest.php +++ b/test/UtilsTest.php @@ -23,27 +23,27 @@ public function setUp(): void ['a' => '1a', 'b' => '1b']]; } - public function test_collect_with_array_of_objects_using_closure() + public function testCollectWithArrayOfObjectsUsingClosure() { $this->assertEquals(['0a', '1a'], AR\collect($this->object_array, function ($obj) { return $obj->a; })); } - public function test_collect_with_array_of_objects_using_string() + public function testCollectWithArrayOfObjectsUsingString() { $this->assertEquals(['0a', '1a'], AR\collect($this->object_array, 'a')); } - public function test_collect_with_array_hash_using_closure() + public function testCollectWithArrayHashUsingClosure() { $this->assertEquals(['0a', '1a'], AR\collect($this->array_hash, function ($item) { return $item['a']; })); } - public function test_collect_with_array_hash_using_string() + public function testCollectWithArrayHashUsingString() { $this->assertEquals(['0a', '1a'], AR\collect($this->array_hash, 'a')); } - public function test_array_flatten() + public function testArrayFlatten() { $this->assertEquals([], AR\array_flatten([])); $this->assertEquals([1], AR\array_flatten([1])); @@ -56,7 +56,7 @@ public function test_array_flatten() $this->assertEquals([1, 2, 3, 4, 5, 6], AR\array_flatten([1, [2, 3], 4, [5, 6]])); } - public function test_all() + public function testAll() { $this->assertTrue(AR\all(null, [null, null])); $this->assertTrue(AR\all(1, [1, 1])); @@ -64,7 +64,7 @@ public function test_all() $this->assertFalse(AR\all(null, ['', null])); } - public function test_classify() + public function testClassify() { $bad_class_names = ['ubuntu_rox', 'stop_the_Snake_Case', 'CamelCased', 'camelCased']; $good_class_names = ['UbuntuRox', 'StopTheSnakeCase', 'CamelCased', 'CamelCased']; @@ -77,7 +77,7 @@ public function test_classify() $this->assertEquals($class_names, $good_class_names); } - public function test_classify_singularize() + public function testClassifySingularize() { $bad_class_names = ['events', 'stop_the_Snake_Cases', 'angry_boxes', 'Mad_Sheep_herders', 'happy_People']; $good_class_names = ['Event', 'StopTheSnakeCase', 'AngryBox', 'MadSheepHerder', 'HappyPerson']; @@ -90,7 +90,7 @@ public function test_classify_singularize() $this->assertEquals($class_names, $good_class_names); } - public function test_singularize() + public function testSingularize() { $this->assertEquals('order_status', AR\Utils::singularize('order_status')); $this->assertEquals('order_status', AR\Utils::singularize('order_statuses')); @@ -101,7 +101,7 @@ public function test_singularize() $this->assertEquals('pass', AR\Utils::singularize('passes')); } - public function test_wrap_strings_in_arrays() + public function testWrapStringsInArrays() { $x = ['1', ['2']]; $this->assertEquals([['1'], ['2']], ActiveRecord\wrap_values_in_arrays($x)); diff --git a/test/ValidatesFormatOfTest.php b/test/ValidatesFormatOfTest.php index 65dbb006..1605f4af 100644 --- a/test/ValidatesFormatOfTest.php +++ b/test/ValidatesFormatOfTest.php @@ -1,7 +1,5 @@ ['with' => '/^[a-z\W]*$/']]; $book = new BookFormat(['author_id' => 1, 'name' => 'testing reg']); @@ -30,7 +28,7 @@ public function test_format() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_invalid_null(): void + public function testInvalidNull(): void { BookFormat::$validates_format_of = ['name' => ['with' => '/[0-9]/']]; $book = new BookFormat(); @@ -39,7 +37,7 @@ public function test_invalid_null(): void $this->assertTrue($book->errors->is_invalid('name')); } - public function test_invalid_blank(): void + public function testInvalidBlank(): void { BookFormat::$validates_format_of = ['name' => ['with' => '/[^0-9]/']]; $book = new BookFormat(); @@ -48,7 +46,7 @@ public function test_invalid_blank(): void $this->assertTrue($book->errors->is_invalid('name')); } - public function test_valid_blank_and_allow_blank() + public function testValidBlankAndAllowBlank() { BookFormat::$validates_format_of = [ 'name' => [ @@ -61,7 +59,7 @@ public function test_valid_blank_and_allow_blank() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_valid_null_and_allow_null() + public function testValidNullAndAllowNull() { BookFormat::$validates_format_of = [ 'name' => [ @@ -76,7 +74,7 @@ public function test_valid_null_and_allow_null() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_invalid_with_expression_as_non_regexp() + public function testInvalidWithExpressionAsNonRegexp() { BookFormat::$validates_format_of = [ 'name' => [ @@ -89,7 +87,7 @@ public function test_invalid_with_expression_as_non_regexp() $this->assertTrue($book->errors->is_invalid('name')); } - public function test_custom_message() + public function testCustomMessage() { BookFormat::$validates_format_of = [ 'name' => [ diff --git a/test/ValidatesInclusionAndExclusionOfTest.php b/test/ValidatesInclusionAndExclusionOfTest.php index 42137330..420bcc29 100644 --- a/test/ValidatesInclusionAndExclusionOfTest.php +++ b/test/ValidatesInclusionAndExclusionOfTest.php @@ -33,7 +33,7 @@ public function setUp($connection_name=null): void ]; } - public function test_inclusion() + public function testInclusion() { $book = new BookInclusion(); $book->name = 'blah'; @@ -41,7 +41,7 @@ public function test_inclusion() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_exclusion() + public function testExclusion() { $book = new BookExclusion(); $book->name = 'blahh'; @@ -49,7 +49,7 @@ public function test_exclusion() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_invalid_inclusion() + public function testInvalidInclusion() { $book = new BookInclusion(); $book->name = 'thanker'; @@ -60,7 +60,7 @@ public function test_invalid_inclusion() $this->assertTrue($book->errors->is_invalid('name')); } - public function test_invalid_exclusion() + public function testInvalidExclusion() { $book = new BookExclusion(); $book->name = 'alpha'; @@ -73,7 +73,7 @@ public function test_invalid_exclusion() $this->assertTrue($book->errors->is_invalid('name')); } - public function test_inclusion_with_numeric() + public function testInclusionWithNumeric() { BookInclusion::$validates_inclusion_of['name']['in'] = [0, 1, 2]; $book = new BookInclusion(); @@ -82,7 +82,7 @@ public function test_inclusion_with_numeric() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_inclusion_with_boolean() + public function testInclusionWithBoolean() { BookInclusion::$validates_inclusion_of['name']['in'] = [true]; $book = new BookInclusion(); @@ -91,7 +91,7 @@ public function test_inclusion_with_boolean() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_inclusion_with_null() + public function testInclusionWithNull() { BookInclusion::$validates_inclusion_of['name']['in']= [null]; $book = new BookInclusion(); @@ -100,7 +100,7 @@ public function test_inclusion_with_null() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_invalid_inclusion_with_numeric() + public function testInvalidInclusionWithNumeric() { BookInclusion::$validates_inclusion_of['name']['in']= [0, 1, 2]; $book = new BookInclusion(); @@ -120,7 +120,7 @@ public function tes_inclusion_within_option() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_inclusion_scalar_value(): void + public function testInclusionScalarValue(): void { BookInclusion::$validates_inclusion_of['name'] = [ 'within' => ['okay'] @@ -131,7 +131,7 @@ public function test_inclusion_scalar_value(): void $this->assertFalse($book->errors->is_invalid('name')); } - public function test_valid_null() + public function testValidNull() { BookInclusion::$validates_inclusion_of['name']['allow_null'] = true; $book = new BookInclusion(); @@ -140,7 +140,7 @@ public function test_valid_null() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_valid_blank() + public function testValidBlank() { BookInclusion::$validates_inclusion_of['name']['allow_blank'] = true; $book = new BookInclusion(); @@ -149,7 +149,7 @@ public function test_valid_blank() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_custom_message() + public function testCustomMessage() { $msg = 'is using a custom message.'; BookInclusion::$validates_inclusion_of['name']['message'] = $msg; diff --git a/test/ValidatesLengthOfTest.php b/test/ValidatesLengthOfTest.php index a2328e44..1f2f94e4 100644 --- a/test/ValidatesLengthOfTest.php +++ b/test/ValidatesLengthOfTest.php @@ -27,7 +27,7 @@ public function setUp($connection_name=null): void ]; } - public function test_within() + public function testWithin() { BookLength::$validates_length_of['name']['within'] = [1, 5]; $book = new BookLength(); @@ -36,7 +36,7 @@ public function test_within() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_within_error_message() + public function testWithinErrorMessage() { BookLength::$validates_length_of['name']['within'] = [2, 5]; $book = new BookLength(); @@ -49,7 +49,7 @@ public function test_within_error_message() $this->assertEquals(['Name is too long (maximum is 5 characters)'], $book->errors->full_messages()); } - public function test_within_custom_error_message() + public function testWithinCustomErrorMessage() { BookLength::$validates_length_of['name']['within'] = [2, 5]; BookLength::$validates_length_of['name']['too_short'] = 'is too short'; @@ -64,7 +64,7 @@ public function test_within_custom_error_message() $this->assertEquals(['Name is not between 2 and 5 characters'], $book->errors->full_messages()); } - public function test_valid_in() + public function testValidIn() { BookLength::$validates_length_of['name']['in'] = [1, 5]; $book = new BookLength(); @@ -73,7 +73,7 @@ public function test_valid_in() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_aliased_size_of() + public function testAliasedSizeOf() { BookSize::$validates_size_of = BookLength::$validates_length_of; BookSize::$validates_size_of['name']['within'] = [1, 5]; @@ -83,7 +83,7 @@ public function test_aliased_size_of() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_invalid_within_and_in() + public function testInvalidWithinAndIn() { BookLength::$validates_length_of['name']['within'] = [1, 3]; $book = new BookLength(); @@ -99,7 +99,7 @@ public function test_invalid_within_and_in() $this->assertTrue($book->errors->is_invalid('name')); } - public function test_valid_null() + public function testValidNull() { BookLength::$validates_length_of['name']['within'] = [1, 3]; BookLength::$validates_length_of['name']['allow_null'] = true; @@ -110,7 +110,7 @@ public function test_valid_null() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_valid_blank() + public function testValidBlank() { BookLength::$validates_length_of['name']['within'] = [1, 3]; BookLength::$validates_length_of['name']['allow_blank'] = true; @@ -121,7 +121,7 @@ public function test_valid_blank() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_invalid_blank() + public function testInvalidBlank() { BookLength::$validates_length_of['name']['within'] = [1, 3]; @@ -132,7 +132,7 @@ public function test_invalid_blank() $this->assertEquals('is too short (minimum is 1 characters)', $book->errors->first('name')); } - public function test_invalid_null_within() + public function testInvalidNullWithin() { BookLength::$validates_length_of['name']['within'] = [1, 3]; @@ -143,7 +143,7 @@ public function test_invalid_null_within() $this->assertEquals('is too short (minimum is 1 characters)', $book->errors->first('name')); } - public function test_invalid_null_minimum() + public function testInvalidNullMinimum() { BookLength::$validates_length_of['name']['minimum'] = 1; @@ -154,7 +154,7 @@ public function test_invalid_null_minimum() $this->assertEquals('is too short (minimum is 1 characters)', $book->errors->first('name')); } - public function test_valid_null_maximum() + public function testValidNullMaximum() { BookLength::$validates_length_of['name']['maximum'] = 1; @@ -164,7 +164,7 @@ public function test_valid_null_maximum() $this->assertFalse($book->errors->is_invalid('name')); } - public function test_float_as_impossible_range_option() + public function testFloatAsImpossibleRangeOption() { BookLength::$validates_length_of['name']['within'] = [1, 3.6]; $book = new BookLength(); @@ -176,7 +176,7 @@ public function test_float_as_impossible_range_option() } } - public function test_signed_integer_as_impossible_within_option() + public function testSignedIntegerAsImpossibleWithinOption() { BookLength::$validates_length_of['name']['within'] = [-1, 3]; @@ -193,7 +193,7 @@ public function test_signed_integer_as_impossible_within_option() $this->fail('An expected exception has not be raised.'); } - public function test_signed_integer_as_impossible_is_option() + public function testSignedIntegerAsImpossibleIsOption() { BookLength::$validates_length_of['name']['is'] = -8; @@ -210,7 +210,7 @@ public function test_signed_integer_as_impossible_is_option() $this->fail('An expected exception has not be raised.'); } - public function test_lack_of_option() + public function testLackOfOption() { try { $book = new BookLength(); @@ -225,7 +225,7 @@ public function test_lack_of_option() $this->fail('An expected exception has not be raised.'); } - public function test_too_many_options() + public function testTooManyOptions() { BookLength::$validates_length_of['name']['within'] = [1, 3]; BookLength::$validates_length_of['name']['in'] = [1, 3]; @@ -243,7 +243,7 @@ public function test_too_many_options() $this->fail('An expected exception has not be raised.'); } - public function test_too_many_options_with_different_option_types() + public function testTooManyOptionsWithDifferentOptionTypes() { BookLength::$validates_length_of['name']['within'] = [1, 3]; BookLength::$validates_length_of['name']['is'] = 3; @@ -261,7 +261,7 @@ public function test_too_many_options_with_different_option_types() $this->fail('An expected exception has not be raised.'); } - public function test_with_option_as_non_numeric() + public function testWithOptionAsNonNumeric() { $this->expectException(ValidationsArgumentError::class); BookLength::$validates_length_of = [ @@ -273,7 +273,7 @@ public function test_with_option_as_non_numeric() $book->save(); } - public function test_with_option_as_non_numeric_non_array() + public function testWithOptionAsNonNumericNonArray() { $this->expectException(ValidationsArgumentError::class); @@ -286,7 +286,7 @@ public function test_with_option_as_non_numeric_non_array() $book->save(); } - public function test_validates_length_of_maximum() + public function testValidatesLengthOfMaximum() { BookLength::$validates_length_of = [ 'name' => ['maximum' => 10] @@ -296,7 +296,7 @@ public function test_validates_length_of_maximum() $this->assertEquals(['Name is too long (maximum is 10 characters)'], $book->errors->full_messages()); } - public function test_validates_length_of_minimum() + public function testValidatesLengthOfMinimum() { BookLength::$validates_length_of['name'] = ['minimum' => 2]; $book = new BookLength(['name' => '1']); @@ -304,7 +304,7 @@ public function test_validates_length_of_minimum() $this->assertEquals(['Name is too short (minimum is 2 characters)'], $book->errors->full_messages()); } - public function test_validates_length_of_min_max_custom_message() + public function testValidatesLengthOfMinMaxCustomMessage() { BookLength::$validates_length_of['name'] = ['maximum' => 10, 'message' => 'is far too long']; $book = new BookLength([ @@ -322,7 +322,7 @@ public function test_validates_length_of_min_max_custom_message() $this->assertEquals(['Name is far too short'], $book->errors->full_messages()); } - public function test_validates_length_of_min_max_custom_message_overridden() + public function testValidatesLengthOfMinMaxCustomMessageOverridden() { BookLength::$validates_length_of['name'] = [ 'minimum' => 10, @@ -334,7 +334,7 @@ public function test_validates_length_of_min_max_custom_message_overridden() $this->assertEquals(['Name is custom message'], $book->errors->full_messages()); } - public function test_validates_length_of_is() + public function testValidatesLengthOfIs() { BookLength::$validates_length_of['name'] = ['is' => 2]; $book = new BookLength(['name' => '123']); diff --git a/test/ValidatesNumericalityOfTest.php b/test/ValidatesNumericalityOfTest.php index bf04de2b..42fbcb78 100644 --- a/test/ValidatesNumericalityOfTest.php +++ b/test/ValidatesNumericalityOfTest.php @@ -57,35 +57,35 @@ private function assert_valid($values, $msg=null) } } - public function test_numericality() + public function testNumericality() { - //$this->assert_invalid(array("0xdeadbeef")); + // $this->assert_invalid(array("0xdeadbeef")); $this->assert_valid(array_merge(self::$FLOATS, self::$INTEGERS)); $this->assert_invalid(array_merge(self::$NULL, self::$BLANK, self::$JUNK)); } - public function test_not_anumber() + public function testNotAnumber() { $this->assert_invalid(['blah'], 'is not a number'); } - public function test_invalid_null() + public function testInvalidNull() { $this->assert_invalid([null]); } - public function test_invalid_blank() + public function testInvalidBlank() { $this->assert_invalid([' ', ' '], 'is not a number'); } - public function test_invalid_whitespace() + public function testInvalidWhitespace() { $this->assert_invalid(['']); } - public function test_valid_null() + public function testValidNull() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => [ @@ -95,7 +95,7 @@ public function test_valid_null() $this->assert_valid([null]); } - public function test_only_integer() + public function testOnlyInteger() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => [ @@ -107,7 +107,7 @@ public function test_only_integer() $this->assert_invalid([1.5, '1.5']); } - public function test_greater_than() + public function testGreaterThan() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => ['greater_than' => 5] @@ -117,7 +117,7 @@ public function test_greater_than() $this->assert_invalid([5, '5'], 'must be greater than 5'); } - public function test_greater_than_or_equal_to() + public function testGreaterThanOrEqualTo() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => ['greater_than_or_equal_to' => 5] @@ -127,7 +127,7 @@ public function test_greater_than_or_equal_to() $this->assert_invalid([-50, 4.9, '4.9', '-5.1']); } - public function test_less_than() + public function testLessThan() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => ['less_than' => 5] @@ -137,7 +137,7 @@ public function test_less_than() $this->assert_invalid([5, '5'], 'must be less than 5'); } - public function test_less_than_or_equal_to() + public function testLessThanOrEqualTo() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => ['less_than_or_equal_to' => 5] @@ -147,7 +147,7 @@ public function test_less_than_or_equal_to() $this->assert_invalid(['8', 5.1], 'must be less than or equal to 5'); } - public function test_greater_than_less_than_and_even() + public function testGreaterThanLessThanAndEven() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => [ @@ -161,7 +161,7 @@ public function test_greater_than_less_than_and_even() $this->assert_invalid([1, 3, 4]); } - public function test_custom_message() + public function testCustomMessage() { BookNumericality::$validates_numericality_of = [ 'numeric_test' => ['message' => 'Hello'] diff --git a/test/ValidatesPresenceOfTest.php b/test/ValidatesPresenceOfTest.php index 2ea8d2c0..4f7a8d04 100644 --- a/test/ValidatesPresenceOfTest.php +++ b/test/ValidatesPresenceOfTest.php @@ -20,43 +20,43 @@ class AuthorPresence extends ActiveRecord\Model class ValidatesPresenceOfTest extends DatabaseTestCase { - public function test_presence() + public function testPresence() { $book = new BookPresence(['name' => 'blah']); $this->assertFalse($book->is_invalid()); } - public function test_presence_on_date_field_is_valid() + public function testPresenceOnDateFieldIsValid() { $author = new AuthorPresence(['some_date' => '2010-01-01']); $this->assertTrue($author->is_valid()); } - public function test_presence_on_date_field_is_not_valid() + public function testPresenceOnDateFieldIsNotValid() { $author = new AuthorPresence(); $this->assertFalse($author->is_valid()); } - public function test_invalid_null() + public function testInvalidNull() { $book = new BookPresence(['name' => null]); $this->assertTrue($book->is_invalid()); } - public function test_invalid_blank() + public function testInvalidBlank() { $book = new BookPresence(['name' => '']); $this->assertTrue($book->is_invalid()); } - public function test_valid_white_space() + public function testValidWhiteSpace() { $book = new BookPresence(['name' => ' ']); $this->assertFalse($book->is_invalid()); } - public function test_custom_message() + public function testCustomMessage() { BookPresence::$validates_presence_of = [ 'name' => ['message' => 'is using a custom message.'] @@ -67,7 +67,7 @@ public function test_custom_message() $this->assertEquals('is using a custom message.', $book->errors->first('name')); } - public function test_valid_zero() + public function testValidZero() { $book = new BookPresence(['name' => 0]); $this->assertTrue($book->is_valid()); diff --git a/test/ValidationsTest.php b/test/ValidationsTest.php index 0aa840eb..f4da8736 100644 --- a/test/ValidationsTest.php +++ b/test/ValidationsTest.php @@ -1,6 +1,5 @@ true ]; + BookValidations::$validates_presence_of = ['name' => true]; BookValidations::$validates_uniqueness_of = ['name' => true]; ValuestoreValidations::$validates_uniqueness_of = ['key' => true]; } - public function test_is_valid_invokes_validations() + public function testIsValidInvokesValidations() { $book = new Book(); $this->assertTrue(empty($book->errors)); @@ -45,31 +44,31 @@ public function test_is_valid_invokes_validations() $this->assertFalse(empty($book->errors)); } - public function test_is_valid_returns_true_if_no_validations_exist() + public function testIsValidReturnsTrueIfNoValidationsExist() { $book = new Book(); $this->assertTrue($book->is_valid()); } - public function test_is_valid_returns_false_if_failed_validations() + public function testIsValidReturnsFalseIfFailedValidations() { $book = new BookValidations(); $this->assertFalse($book->is_valid()); } - public function test_is_invalid() + public function testIsInvalid() { $book = new Book(); $this->assertFalse($book->is_invalid()); } - public function test_is_invalid_is_true() + public function testIsInvalidIsTrue() { $book = new BookValidations(); $this->assertTrue($book->is_invalid()); } - public function test_is_iterable() + public function testIsIterable() { $book = new BookValidations(); $book->is_valid(); @@ -79,7 +78,7 @@ public function test_is_iterable() } } - public function test_full_messages() + public function testFullMessages() { $book = new BookValidations(); $book->is_valid(); @@ -87,7 +86,7 @@ public function test_full_messages() $this->assertEquals(["Name can't be blank"], array_values($book->errors->full_messages(['hash' => true]))); } - public function test_to_array() + public function testToArray() { $book = new BookValidations(); $book->is_valid(); @@ -95,7 +94,7 @@ public function test_to_array() $this->assertEquals(['name' => ["Name can't be blank"]], $book->errors->to_array()); } - public function test_toString() + public function testToString() { $book = new BookValidations(); $book->is_valid(); @@ -104,7 +103,7 @@ public function test_toString() $this->assertEquals("Name can't be blank\nSecondary author id is invalid", (string) $book->errors); } - public function test_validates_uniqueness_of() + public function testValidatesUniquenessOf() { BookValidations::create(['name' => 'bob']); $book = BookValidations::create(['name' => 'bob']); @@ -113,13 +112,13 @@ public function test_validates_uniqueness_of() $this->assertEquals(1, BookValidations::count(['conditions' => "name='bob'"])); } - public function test_validates_uniqueness_of_excludes_self() + public function testValidatesUniquenessOfExcludesSelf() { $book = BookValidations::first(); $this->assertEquals(true, $book->is_valid()); } - public function test_validates_uniqueness_of_with_multiple_fields() + public function testValidatesUniquenessOfWithMultipleFields() { BookValidations::$validates_uniqueness_of = [ 'name' => [ @@ -131,7 +130,7 @@ public function test_validates_uniqueness_of_with_multiple_fields() $this->assertTrue($book2->is_valid()); } - public function test_validates_uniqueness_of_with_multiple_fields_is_not_unique() + public function testValidatesUniquenessOfWithMultipleFieldsIsNotUnique() { BookValidations::$validates_uniqueness_of = [ 'name' => [ @@ -144,7 +143,7 @@ public function test_validates_uniqueness_of_with_multiple_fields_is_not_unique( $this->assertEquals(['Name and special must be unique'], $book2->errors->full_messages()); } - public function test_validates_uniqueness_of_works_with_alias_attribute() + public function testValidatesUniquenessOfWorksWithAliasAttribute() { BookValidations::$validates_uniqueness_of = ['name_alias'=> ['scope'=>['x']]]; $book = BookValidations::create(['name_alias' => 'Another Book', 'x' => 2]); @@ -152,7 +151,7 @@ public function test_validates_uniqueness_of_works_with_alias_attribute() $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() + public function testValidatesUniquenessOfWorksWithMysqlReservedWordAsColumnName() { ValuestoreValidations::create(['key' => 'GA_KEY', 'value' => 'UA-1234567-1']); $valuestore = ValuestoreValidations::create(['key' => 'GA_KEY', 'value' => 'UA-1234567-2']); @@ -161,20 +160,20 @@ public function test_validates_uniqueness_of_works_with_mysql_reserved_word_as_c $this->assertEquals(1, ValuestoreValidations::count(['conditions' => "`key`='GA_KEY'"])); } - public function test_get_validation_rules() + public function testGetValidationRules() { $validators = BookValidations::first()->get_validation_rules(); $this->assertTrue(in_array(['validator' => 'validates_presence_of'], $validators['name'])); } - public function test_model_is_nulled_out_to_prevent_memory_leak() + public function testModelIsNulledOutToPreventMemoryLeak() { $book = new BookValidations(); $book->is_valid(); $this->assertTrue(false !== strpos(serialize($book->errors), 'model";N;')); } - public function test_validations_takes_strings() + public function testValidationsTakesStrings() { BookValidations::$validates_presence_of = [ 'numeric_test' => true, @@ -185,7 +184,7 @@ public function test_validations_takes_strings() $this->assertFalse($book->is_valid()); } - public function test_gh131_custom_validation() + public function testGh131CustomValidation() { $book = new BookValidations(['name' => 'test_custom_validation']); $book->save(); diff --git a/test/helpers/AdapterTestCase.php b/test/helpers/AdapterTestCase.php index b3d84153..4bdf6f41 100644 --- a/test/helpers/AdapterTestCase.php +++ b/test/helpers/AdapterTestCase.php @@ -1,28 +1,29 @@ get_connection($connection_name)) { + if (($connection_name && !in_array($connection_name, PDO::getAvailableDrivers())) + || 'skip' == ActiveRecord\Config::instance()->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() + public function testIHasADefaultPortUnlessImSqlite() { if ($this->connection instanceof SqliteAdapter) { $this->expectNotToPerformAssertions(); + return; } @@ -30,25 +31,25 @@ public function test_i_has_a_default_port_unless_im_sqlite() $this->assertTrue($c::$DEFAULT_PORT > 0); } - public function test_should_set_adapter_variables() + public function testShouldSetAdapterVariables() { $this->assertNotNull($this->connection->protocol); } - public function test_null_connection_string_uses_default_connection() + public function testNullConnectionStringUsesDefaultConnection() { $this->assertNotNull(ActiveRecord\Connection::instance(null)); $this->assertNotNull(ActiveRecord\Connection::instance('')); $this->assertNotNull(ActiveRecord\Connection::instance()); } - public function test_invalid_connection_protocol() + public function testInvalidConnectionProtocol() { $this->expectException(DatabaseException::class); ActiveRecord\Connection::instance('terribledb://user:pass@host/db'); } - public function test_no_host_connection() + public function testNoHostConnection() { $this->expectException(DatabaseException::class); if (!$GLOBALS['slow_tests']) { @@ -57,7 +58,7 @@ public function test_no_host_connection() ActiveRecord\Connection::instance("{$this->connection->protocol}://user:pass"); } - public function test_connection_failed_invalid_host() + public function testConnectionFailedInvalidHost() { $this->expectException(DatabaseException::class); if (!$GLOBALS['slow_tests']) { @@ -66,19 +67,19 @@ public function test_connection_failed_invalid_host() ActiveRecord\Connection::instance("{$this->connection->protocol}://user:pass/1.1.1.1/db"); } - public function test_connection_failed() + public function testConnectionFailed() { $this->expectException(ConnectionException::class); ActiveRecord\Connection::instance("{$this->connection->protocol}://baduser:badpass@127.0.0.1/db"); } - public function test_connect_failed() + public function testConnectFailed() { $this->expectException(ConnectionException::class); ActiveRecord\Connection::instance("{$this->connection->protocol}://zzz:zzz@127.0.0.1/test"); } - public function test_connect_with_port() + public function testConnectWithPort() { $this->expectNotToPerformAssertions(); $config = ActiveRecord\Config::instance(); @@ -99,13 +100,13 @@ public function test_connect_with_port() } } - public function test_connect_to_invalid_database() + public function testConnectToInvalidDatabase() { $this->expectException(ConnectionException::class); ActiveRecord\Connection::instance("{$this->connection->protocol}://test:test@127.0.0.1/" . self::InvalidDb); } - public function test_date_time_type() + public function testDateTimeType() { $columns = $this->connection->columns('authors'); $this->assertEquals('datetime', $columns['created_at']->raw_type); @@ -113,7 +114,7 @@ public function test_date_time_type() $this->assertTrue($columns['created_at']->length > 0); } - public function test_date() + public function testDate() { $columns = $this->connection->columns('authors'); $this->assertEquals('date', $columns['some_Date']->raw_type); @@ -121,27 +122,27 @@ public function test_date() $this->assertTrue($columns['some_Date']->length >= 7); } - public function test_columns_no_inflection_on_hash_key() + public function testColumnsNoInflectionOnHashKey() { $author_columns = $this->connection->columns('authors'); $this->assertTrue(array_key_exists('author_id', $author_columns)); } - public function test_columns_nullable() + public function testColumnsNullable() { $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() + public function testColumnsPk() { $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() + public function testColumnsSequence() { if ($this->connection->supports_sequences()) { $author_columns = $this->connection->columns('authors'); @@ -151,13 +152,13 @@ public function test_columns_sequence() } } - public function test_columns_default() + public function testColumnsDefault() { $author_columns = $this->connection->columns('authors'); $this->assertEquals('default_name', $author_columns['name']->default); } - public function test_columns_type() + public function testColumnsType() { $author_columns = $this->connection->columns('authors'); $this->assertEquals('varchar', substr($author_columns['name']->raw_type, 0, 7)); @@ -165,25 +166,25 @@ public function test_columns_type() $this->assertEquals(25, $author_columns['name']->length); } - public function test_columns_text() + public function testColumnsText() { $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() + public function testColumnsTime() { $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() + public function testQuery() { $sth = $this->connection->query('SELECT * FROM authors'); - while (($row = $sth->fetch())) { + while ($row = $sth->fetch()) { $this->assertNotNull($row); } @@ -192,19 +193,19 @@ public function test_query() $this->assertEquals('Tito', $row['name']); } - public function test_invalid_query() + public function testInvalidQuery() { $this->expectException(DatabaseException::class); $this->connection->query('alsdkjfsdf'); } - public function test_fetch() + public function testFetch() { $sth = $this->connection->query('SELECT * FROM authors WHERE author_id IN(1,2,3)'); $i = 0; $ids = []; - while (($row = $sth->fetch())) { + while ($row = $sth->fetch()) { ++$i; $ids[] = $row['author_id']; } @@ -213,7 +214,7 @@ public function test_fetch() $this->assertEquals([1, 2, 3], $ids); } - public function test_query_with_params() + public function testQueryWithParams() { $x=['Bill Clinton', 'Tito']; $sth = $this->connection->query('SELECT * FROM authors WHERE name IN(?,?) ORDER BY name DESC', $x); @@ -227,38 +228,38 @@ public function test_query_with_params() $this->assertEquals(null, $row); } - public function test_insert_id_should_return_explicitly_inserted_id() + public function testInsertIdShouldReturnExplicitlyInsertedId() { $this->connection->query('INSERT INTO authors(author_id,name) VALUES(99,\'name\')'); $this->assertTrue($this->connection->insert_id() > 0); } - public function test_insert_id() + public function testInsertId() { $this->connection->query("INSERT INTO authors(name) VALUES('name')"); $this->assertTrue($this->connection->insert_id() > 0); } - public function test_insert_id_with_params() + public function testInsertIdWithParams() { $x = ['name']; $this->connection->query('INSERT INTO authors(name) VALUES(?)', $x); $this->assertTrue($this->connection->insert_id() > 0); } - public function test_inflection() + public function testInflection() { $columns = $this->connection->columns('authors'); $this->assertEquals('parent_author_id', $columns['parent_author_id']->inflected_name); } - public function test_escape() + public function testEscape() { $s = "Bob's"; $this->assertNotEquals($s, $this->connection->escape($s)); } - public function test_columnsx() + public function testColumnsx() { $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']; @@ -282,7 +283,7 @@ public function test_columnsx() $this->assertEquals(25, $columns['name']->length); } - public function test_columns_decimal() + public function testColumnsDecimal() { $columns = $this->connection->columns('books'); $this->assertEquals(Column::DECIMAL, $columns['special']->type); @@ -298,59 +299,59 @@ private function limit(int $offset = 0, int $limit = 0) return ActiveRecord\collect($ret, 'author_id'); } - public function test_limit() + public function testLimit() { $this->assertEquals([2, 1], $this->limit(1, 2)); } - public function test_limit_to_first_record() + public function testLimitToFirstRecord() { $this->assertEquals([3], $this->limit(0, 1)); } - public function test_limit_to_last_record() + public function testLimitToLastRecord() { $this->assertEquals([1], $this->limit(2, 1)); } - public function test_limit_with_null_offset() + public function testLimitWithNullOffset() { $this->assertEquals([3], $this->limit(0, 1)); } - public function test_limit_with_defaults() + public function testLimitWithDefaults() { $this->assertEquals([], $this->limit()); } - public function test_fetch_no_results() + public function testFetchNoResults() { $sth = $this->connection->query('SELECT * FROM authors WHERE author_id=65534'); $this->assertEquals(null, $sth->fetch()); } - public function test_tables() + public function testTables() { $this->assertTrue(count($this->connection->tables()) > 0); } - public function test_query_column_info() + public function testQueryColumnInfo() { $this->assertGreaterThan(0, count((array) $this->connection->query_column_info('authors'))); } - public function test_query_table_info() + public function testQueryTableInfo() { $this->assertGreaterThan(0, count((array) $this->connection->query_for_tables())); } - public function test_query_table_info_must_return_one_field() + public function testQueryTableInfoMustReturnOneField() { $sth = $this->connection->query_for_tables(); $this->assertEquals(1, count((array) $sth->fetch())); } - public function test_transaction_commit() + public function testTransactionCommit() { $original = $this->connection->query_and_fetch_one('select count(*) from authors'); @@ -361,7 +362,7 @@ public function test_transaction_commit() $this->assertEquals($original+1, $this->connection->query_and_fetch_one('select count(*) from authors')); } - public function test_transaction_rollback() + public function testTransactionRollback() { $original = $this->connection->query_and_fetch_one('select count(*) from authors'); @@ -372,7 +373,7 @@ public function test_transaction_rollback() $this->assertEquals($original, $this->connection->query_and_fetch_one('select count(*) from authors')); } - public function test_show_me_a_useful_pdo_exception_message() + public function testShowMeAUsefulPdoExceptionMessage() { try { $this->connection->query('select * from an_invalid_column'); @@ -382,7 +383,7 @@ public function test_show_me_a_useful_pdo_exception_message() } } - public function test_quote_name_does_not_over_quote() + public function testQuoteNameDoesNotOverQuote() { $c = $this->connection; $q = $c::$QUOTE_CHARACTER; @@ -393,13 +394,13 @@ public function test_quote_name_does_not_over_quote() $this->assertEquals("{$q}string{$q}", $qn("{$q}string{$q}")); } - public function test_datetime_to_string() + public function testDatetimeToString() { $datetime = '2009-01-01 01:01:01'; $this->assertEquals($datetime, $this->connection->datetime_to_string(date_create($datetime))); } - public function test_date_to_string() + public function testDateToString() { $datetime = '2009-01-01'; $this->assertEquals($datetime, $this->connection->date_to_string(date_create($datetime))); diff --git a/test/helpers/DatabaseLoader.php b/test/helpers/DatabaseLoader.php index 459843f9..d4041114 100644 --- a/test/helpers/DatabaseLoader.php +++ b/test/helpers/DatabaseLoader.php @@ -1,7 +1,5 @@ db->query("INSERT INTO $table($fields) VALUES($markers)", $values); } } diff --git a/test/helpers/DatabaseTestCase.php b/test/helpers/DatabaseTestCase.php index 320df481..3f457b7e 100644 --- a/test/helpers/DatabaseTestCase.php +++ b/test/helpers/DatabaseTestCase.php @@ -1,7 +1,5 @@ original_date_class = $config->get_date_class(); - if ('sqlite' == $connection_name || 'sqlite' == $config->get_default_connection()) { // need to create the db. the adapter specifically does not create it for us. static::$db = substr(ActiveRecord\Config::instance()->get_connection('sqlite'), 9); diff --git a/test/helpers/config.php b/test/helpers/config.php index 5e9e90d2..b0b275ef 100644 --- a/test/helpers/config.php +++ b/test/helpers/config.php @@ -50,7 +50,7 @@ } if (class_exists('Monolog\Logger')) { // Monolog installed - $log = new Monolog\Logger("arlog"); + $log = new Monolog\Logger('arlog'); $log->pushHandler(new \Monolog\Handler\StreamHandler( dirname(__FILE__) . '/../log/query.log', \Monolog\Level::Warning) diff --git a/test/models/Amenity.php b/test/models/Amenity.php index ec9b2d5b..7abc0f3f 100644 --- a/test/models/Amenity.php +++ b/test/models/Amenity.php @@ -1,7 +1,9 @@ name); diff --git a/test/models/BookAttrAccessible.php b/test/models/BookAttrAccessible.php index fa419178..6cfc540f 100644 --- a/test/models/BookAttrAccessible.php +++ b/test/models/BookAttrAccessible.php @@ -1,7 +1,9 @@ 'AuthorAttrAccessible', 'primary_key' => 'author_id'] diff --git a/test/models/Employee.php b/test/models/Employee.php index 2bb5a1e4..90269a64 100644 --- a/test/models/Employee.php +++ b/test/models/Employee.php @@ -1,7 +1,9 @@