diff --git a/tests/data/ar/Animal.php b/tests/data/ar/Animal.php index 839e605d26..b2d842ddda 100644 --- a/tests/data/ar/Animal.php +++ b/tests/data/ar/Animal.php @@ -39,7 +39,7 @@ class Animal extends ActiveRecord /** * @param type $row - * @return \yiiunit\data\ar\Animal + * @return Animal */ public static function instantiate($row) { diff --git a/tests/data/views/widgets/ListView/item.php b/tests/data/views/widgets/ListView/item.php index 8703566571..a100d07514 100644 --- a/tests/data/views/widgets/ListView/item.php +++ b/tests/data/views/widgets/ListView/item.php @@ -1,4 +1,7 @@ className(); diff --git a/tests/framework/ar/ActiveRecordTestTrait.php b/tests/framework/ar/ActiveRecordTestTrait.php index f82db23a2e..2d92dceacf 100644 --- a/tests/framework/ar/ActiveRecordTestTrait.php +++ b/tests/framework/ar/ActiveRecordTestTrait.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\ar; +use yiiunit\extensions\redis\ActiveRecordTest; +use Exception; use yii\base\Event; use yii\db\ActiveRecordInterface; use yii\db\BaseActiveRecord; @@ -62,7 +64,7 @@ trait ActiveRecordTestTrait { } - public function testFind() + public function testFind(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -125,7 +127,7 @@ trait ActiveRecordTestTrait $this->assertEquals(2, $customerClass::find()->active()->count()); } - public function testFindAsArray() + public function testFindAsArray(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -161,7 +163,7 @@ trait ActiveRecordTestTrait $this->assertArrayHasKey('status', $customers[2]); } - public function testHasAttribute() + public function testHasAttribute(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -181,7 +183,7 @@ trait ActiveRecordTestTrait $this->assertFalse($customer->hasAttribute(42)); } - public function testFindScalar() + public function testFindScalar(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -198,7 +200,7 @@ trait ActiveRecordTestTrait $this->assertEquals(3, $customerId); } - public function testFindColumn() + public function testFindColumn(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -208,7 +210,7 @@ trait ActiveRecordTestTrait $this->assertEquals(['user3', 'user2', 'user1'], $customerClass::find()->orderBy(['name' => SORT_DESC])->column('name')); } - public function testFindIndexBy() + public function testFindIndexBy(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -230,7 +232,7 @@ trait ActiveRecordTestTrait $this->assertInstanceOf($customerClass, $customers['3-user3']); } - public function testFindIndexByAsArray() + public function testFindIndexByAsArray(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -277,7 +279,7 @@ trait ActiveRecordTestTrait $this->assertArrayHasKey('status', $customers['3-user3']); } - public function testRefresh() + public function testRefresh(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -291,7 +293,7 @@ trait ActiveRecordTestTrait $this->assertEquals('user1', $customer->name); } - public function testEquals() + public function testEquals(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -319,7 +321,7 @@ trait ActiveRecordTestTrait $this->assertFalse($customerA->equals($customerB)); } - public function testFindCount() + public function testFindCount(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -339,7 +341,7 @@ trait ActiveRecordTestTrait $this->assertEquals(3, $customerClass::find()->offset(2)->limit(2)->count()); } - public function testFindLimit() + public function testFindLimit(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -386,7 +388,7 @@ trait ActiveRecordTestTrait $this->assertNull($customer); } - public function testFindComplexCondition() + public function testFindComplexCondition(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -402,7 +404,7 @@ trait ActiveRecordTestTrait $this->assertCount(1, $customerClass::find()->where(['AND', ['name' => ['user2', 'user3']], ['BETWEEN', 'status', 2, 4]])->all()); } - public function testFindNullValues() + public function testFindNullValues(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -418,7 +420,7 @@ trait ActiveRecordTestTrait $this->assertEquals(2, reset($result)->primaryKey); } - public function testExists() + public function testExists(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -434,7 +436,7 @@ trait ActiveRecordTestTrait $this->assertFalse($customerClass::find()->where(['id' => [2, 3]])->offset(2)->exists()); } - public function testFindLazy() + public function testFindLazy(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -462,7 +464,7 @@ trait ActiveRecordTestTrait $this->assertEquals(3, $orders[0]->id); } - public function testFindEager() + public function testFindEager(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -499,7 +501,7 @@ trait ActiveRecordTestTrait $this->assertTrue($orders[0]->isRelationPopulated('items')); } - public function testFindLazyVia() + public function testFindLazyVia(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -513,7 +515,7 @@ trait ActiveRecordTestTrait $this->assertEquals(2, $order->items[1]->id); } - public function testFindLazyVia2() + public function testFindLazyVia2(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -525,7 +527,7 @@ trait ActiveRecordTestTrait $this->assertEquals([], $order->items); } - public function testFindEagerViaRelation() + public function testFindEagerViaRelation(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -541,7 +543,7 @@ trait ActiveRecordTestTrait $this->assertEquals(2, $order->items[1]->id); } - public function testFindNestedRelation() + public function testFindNestedRelation(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -578,7 +580,7 @@ trait ActiveRecordTestTrait * * @see https://github.com/yiisoft/yii2/issues/1310. */ - public function testFindEagerViaRelationPreserveOrder() + public function testFindEagerViaRelationPreserveOrder(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -641,7 +643,7 @@ trait ActiveRecordTestTrait } // different order in via table - public function testFindEagerViaRelationPreserveOrderB() + public function testFindEagerViaRelationPreserveOrderB(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -671,7 +673,7 @@ trait ActiveRecordTestTrait $this->assertEquals(2, $order->itemsInOrder2[0]->id); } - public function testLink() + public function testLink(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -724,7 +726,7 @@ trait ActiveRecordTestTrait $this->assertEquals(100, $orderItem->subtotal); } - public function testUnlink() + public function testUnlink(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -775,7 +777,7 @@ trait ActiveRecordTestTrait $this->assertCount(2, $order->orderItems); } - public function testUnlinkAll() + public function testUnlinkAll(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -841,7 +843,7 @@ trait ActiveRecordTestTrait // via table is covered in \yiiunit\framework\db\ActiveRecordTest::testUnlinkAllViaTable() } - public function testUnlinkAllAndConditionSetNull() + public function testUnlinkAllAndConditionSetNull(): void { /** @var TestCase|ActiveRecordTestTrait $this */ @@ -867,7 +869,7 @@ trait ActiveRecordTestTrait $this->assertCount(0, $customer->expensiveOrdersWithNullFK); } - public function testUnlinkAllAndConditionDelete() + public function testUnlinkAllAndConditionDelete(): void { /** @var TestCase|ActiveRecordTestTrait $this */ @@ -896,7 +898,7 @@ trait ActiveRecordTestTrait public static $afterSaveNewRecord; public static $afterSaveInsert; - public function testInsert() + public function testInsert(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -920,7 +922,7 @@ trait ActiveRecordTestTrait $this->assertFalse($customer->isNewRecord); } - public function testExplicitPkOnAutoIncrement() + public function testExplicitPkOnAutoIncrement(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -939,7 +941,7 @@ trait ActiveRecordTestTrait $this->assertFalse($customer->isNewRecord); } - public function testUpdate() + public function testUpdate(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -982,7 +984,7 @@ trait ActiveRecordTestTrait $this->assertEquals(0, $ret); } - public function testUpdateAttributes() + public function testUpdateAttributes(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -1017,7 +1019,7 @@ trait ActiveRecordTestTrait $this->assertEquals(1, $customer->status); } - public function testUpdateCounters() + public function testUpdateCounters(): void { /** @var ActiveRecordInterface $orderItemClass */ $orderItemClass = $this->getOrderItemClass(); @@ -1048,7 +1050,7 @@ trait ActiveRecordTestTrait $this->assertEquals(30, $orderItem->subtotal); } - public function testDelete() + public function testDelete(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -1080,7 +1082,7 @@ trait ActiveRecordTestTrait * Some PDO implementations(e.g. cubrid) do not support boolean values. * Make sure this does not affect AR layer. */ - public function testBooleanAttribute() + public function testBooleanAttribute(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -1107,7 +1109,7 @@ trait ActiveRecordTestTrait $this->assertCount(1, $customers); } - public function testAfterFind() + public function testAfterFind(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -1145,7 +1147,7 @@ trait ActiveRecordTestTrait ], $afterFindCalls); $afterFindCalls = []; - if ($this instanceof \yiiunit\extensions\redis\ActiveRecordTest) { // TODO redis does not support orderBy() yet + if ($this instanceof ActiveRecordTest) { // TODO redis does not support orderBy() yet $customer = $customerClass::find()->where(['id' => [1, 2]])->with('orders')->all(); } else { // orderBy is needed to avoid random test failure @@ -1164,7 +1166,7 @@ trait ActiveRecordTestTrait Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND); } - public function testAfterRefresh() + public function testAfterRefresh(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -1185,7 +1187,7 @@ trait ActiveRecordTestTrait Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_REFRESH); } - public function testFindEmptyInCondition() + public function testFindEmptyInCondition(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -1204,7 +1206,7 @@ trait ActiveRecordTestTrait $this->assertCount(0, $customers); } - public function testFindEagerIndexBy() + public function testFindEagerIndexBy(): void { /** @var TestCase|ActiveRecordTestTrait $this */ @@ -1229,7 +1231,7 @@ trait ActiveRecordTestTrait $this->assertTrue(isset($items[5])); } - public function testAttributeAccess() + public function testAttributeAccess(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -1278,7 +1280,7 @@ trait ActiveRecordTestTrait $itemClass = $this->getItemClass(); $customer->orderItems = [new $itemClass()]; $this->fail('setter call above MUST throw Exception'); - } catch (\Exception $e) { + } catch (Exception $e) { // catch exception "Setting read-only property" $this->assertInstanceOf('yii\base\InvalidCallException', $e); } @@ -1293,7 +1295,7 @@ trait ActiveRecordTestTrait /** * @see https://github.com/yiisoft/yii2/issues/17089 */ - public function testViaWithCallable() + public function testViaWithCallable(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); diff --git a/tests/framework/behaviors/SluggableBehaviorTest.php b/tests/framework/behaviors/SluggableBehaviorTest.php index 2882cae734..ee825672ff 100644 --- a/tests/framework/behaviors/SluggableBehaviorTest.php +++ b/tests/framework/behaviors/SluggableBehaviorTest.php @@ -71,7 +71,7 @@ class SluggableBehaviorTest extends TestCase // Tests : - public function testSlug() + public function testSlug(): void { $model = new ActiveRecordSluggable(); $model->name = 'test name'; @@ -83,7 +83,7 @@ class SluggableBehaviorTest extends TestCase /** * @depends testSlug */ - public function testSlugSeveralAttributes() + public function testSlugSeveralAttributes(): void { $model = new ActiveRecordSluggable(); $model->getBehavior('sluggable')->attribute = ['name', 'category_id']; @@ -98,7 +98,7 @@ class SluggableBehaviorTest extends TestCase /** * @depends testSlug */ - public function testSlugRelatedAttribute() + public function testSlugRelatedAttribute(): void { $model = new ActiveRecordSluggable(); $model->getBehavior('sluggable')->attribute = 'related.name'; @@ -117,7 +117,7 @@ class SluggableBehaviorTest extends TestCase /** * @depends testSlug */ - public function testUniqueByIncrement() + public function testUniqueByIncrement(): void { $name = 'test name'; @@ -136,7 +136,7 @@ class SluggableBehaviorTest extends TestCase /** * @depends testUniqueByIncrement */ - public function testUniqueByCallback() + public function testUniqueByCallback(): void { $name = 'test name'; @@ -157,7 +157,7 @@ class SluggableBehaviorTest extends TestCase /** * @depends testSlug */ - public function testUpdateUnique() + public function testUpdateUnique(): void { $name = 'test name'; @@ -177,7 +177,7 @@ class SluggableBehaviorTest extends TestCase $this->assertEquals('test-name', $model->slug); } - public function testSkipOnEmpty() + public function testSkipOnEmpty(): void { $model = new SkipOnEmptySluggableActiveRecord(); $model->name = 'test name'; @@ -196,7 +196,7 @@ class SluggableBehaviorTest extends TestCase /** * @depends testSlug */ - public function testImmutableByAttribute() + public function testImmutableByAttribute(): void { $model = new ActiveRecordSluggable(); $model->getSluggable()->immutable = true; @@ -213,7 +213,7 @@ class SluggableBehaviorTest extends TestCase /** * @depends testSlug */ - public function testImmutableByCallback() + public function testImmutableByCallback(): void { $model = new ActiveRecordSluggable(); $model->getSluggable()->immutable = true; diff --git a/tests/framework/behaviors/TimestampBehaviorTest.php b/tests/framework/behaviors/TimestampBehaviorTest.php index cf97023ded..1799a4c9a7 100644 --- a/tests/framework/behaviors/TimestampBehaviorTest.php +++ b/tests/framework/behaviors/TimestampBehaviorTest.php @@ -72,7 +72,7 @@ class TimestampBehaviorTest extends TestCase // Tests : - public function testNewRecord() + public function testNewRecord(): void { $currentTime = time(); @@ -89,7 +89,7 @@ class TimestampBehaviorTest extends TestCase /** * @depends testNewRecord */ - public function testUpdateRecord() + public function testUpdateRecord(): void { $currentTime = time(); @@ -112,7 +112,7 @@ class TimestampBehaviorTest extends TestCase /** * @depends testNewRecord */ - public function testUpdateCleanRecord() + public function testUpdateCleanRecord(): void { ActiveRecordTimestamp::$behaviors = [ TimestampBehavior::className(), @@ -151,7 +151,7 @@ class TimestampBehaviorTest extends TestCase * @param mixed $expression * @param mixed $expected */ - public function testNewRecordExpression($expression, $expected) + public function testNewRecordExpression($expression, $expected): void { ActiveRecordTimestamp::$tableName = 'test_auto_timestamp_string'; ActiveRecordTimestamp::$behaviors = [ @@ -179,7 +179,7 @@ class TimestampBehaviorTest extends TestCase /** * @depends testNewRecord */ - public function testUpdateRecordExpression() + public function testUpdateRecordExpression(): void { ActiveRecordTimestamp::$tableName = 'test_auto_timestamp_string'; ActiveRecordTimestamp::$behaviors = [ @@ -203,7 +203,7 @@ class TimestampBehaviorTest extends TestCase $this->assertEquals(date('Y'), $model->updated_at); } - public function testTouchingNewRecordGeneratesException() + public function testTouchingNewRecordGeneratesException(): void { ActiveRecordTimestamp::$behaviors = [ 'timestamp' => [ @@ -218,7 +218,7 @@ class TimestampBehaviorTest extends TestCase $model->touch('created_at'); } - public function testTouchingNotNewRecord() + public function testTouchingNotNewRecord(): void { ActiveRecordTimestamp::$behaviors = [ 'timestamp' => [ diff --git a/tests/framework/caching/ApcCacheTest.php b/tests/framework/caching/ApcCacheTest.php index 83d57d893a..42e06bab98 100644 --- a/tests/framework/caching/ApcCacheTest.php +++ b/tests/framework/caching/ApcCacheTest.php @@ -43,12 +43,12 @@ class ApcCacheTest extends CacheTestCase return $this->_cacheInstance; } - public function testExpire() + public function testExpire(): void { $this->markTestSkipped('APC keys are expiring only on the next request.'); } - public function testExpireAdd() + public function testExpireAdd(): void { $this->markTestSkipped('APC keys are expiring only on the next request.'); } diff --git a/tests/framework/caching/ArrayCacheTest.php b/tests/framework/caching/ArrayCacheTest.php index ba4249a049..87b23ec2a9 100644 --- a/tests/framework/caching/ArrayCacheTest.php +++ b/tests/framework/caching/ArrayCacheTest.php @@ -30,7 +30,7 @@ class ArrayCacheTest extends CacheTestCase return $this->_cacheInstance; } - public function testExpire() + public function testExpire(): void { $cache = $this->getCacheInstance(); @@ -42,7 +42,7 @@ class ArrayCacheTest extends CacheTestCase $this->assertFalse($cache->get('expire_test')); } - public function testExpireAdd() + public function testExpireAdd(): void { $cache = $this->getCacheInstance(); @@ -57,7 +57,7 @@ class ArrayCacheTest extends CacheTestCase /** * @see https://github.com/yiisoft/yii2/issues/16028 */ - public function testSerializationOfComplexKeysThatContainNonUTFSequences() + public function testSerializationOfComplexKeysThatContainNonUTFSequences(): void { $cache = $this->getCacheInstance(); diff --git a/tests/framework/caching/CacheTestCase.php b/tests/framework/caching/CacheTestCase.php index 1fce0a44fa..8147daa912 100644 --- a/tests/framework/caching/CacheTestCase.php +++ b/tests/framework/caching/CacheTestCase.php @@ -82,7 +82,7 @@ abstract class CacheTestCase extends TestCase return $cache; } - public function testSet() + public function testSet(): void { $cache = $this->getCacheInstance(); @@ -91,7 +91,7 @@ abstract class CacheTestCase extends TestCase $this->assertTrue($cache->set('array_test', ['array_test' => 'array_test'])); } - public function testGet() + public function testGet(): void { $cache = $this->prepare(); @@ -116,7 +116,7 @@ abstract class CacheTestCase extends TestCase * @dataProvider multiSetExpiry * @param int $expiry */ - public function testMultiset($expiry) + public function testMultiset($expiry): void { $cache = $this->getCacheInstance(); $cache->flush(); @@ -136,7 +136,7 @@ abstract class CacheTestCase extends TestCase $this->assertEquals('array_test', $array['array_test']); } - public function testExists() + public function testExists(): void { $cache = $this->prepare(); @@ -148,7 +148,7 @@ abstract class CacheTestCase extends TestCase $this->assertFalse($cache->exists('not_exists')); } - public function testArrayAccess() + public function testArrayAccess(): void { $cache = $this->getCacheInstance(); @@ -156,21 +156,21 @@ abstract class CacheTestCase extends TestCase $this->assertInstanceOf('stdClass', $cache['arrayaccess_test']); } - public function testGetValueNonExistent() + public function testGetValueNonExistent(): void { $cache = $this->getCacheInstance(); $this->assertFalse($this->invokeMethod($cache, 'getValue', ['non_existent_key'])); } - public function testGetNonExistent() + public function testGetNonExistent(): void { $cache = $this->getCacheInstance(); $this->assertFalse($cache->get('non_existent_key')); } - public function testStoreSpecialValues() + public function testStoreSpecialValues(): void { $cache = $this->getCacheInstance(); @@ -181,7 +181,7 @@ abstract class CacheTestCase extends TestCase $this->assertTrue($cache->get('bool_value')); } - public function testMultiGet() + public function testMultiGet(): void { $cache = $this->prepare(); @@ -191,14 +191,14 @@ abstract class CacheTestCase extends TestCase $this->assertSame(['number_test' => 42, 'non_existent_key' => false], $cache->multiGet(['number_test', 'non_existent_key'])); } - public function testDefaultTtl() + public function testDefaultTtl(): void { $cache = $this->getCacheInstance(); $this->assertSame(0, $cache->defaultDuration); } - public function testExpire() + public function testExpire(): void { $cache = $this->getCacheInstance(); @@ -209,7 +209,7 @@ abstract class CacheTestCase extends TestCase $this->assertFalse($cache->get('expire_test')); } - public function testExpireAdd() + public function testExpireAdd(): void { $cache = $this->getCacheInstance(); @@ -220,7 +220,7 @@ abstract class CacheTestCase extends TestCase $this->assertFalse($cache->get('expire_testa')); } - public function testAdd() + public function testAdd(): void { $cache = $this->prepare(); @@ -234,7 +234,7 @@ abstract class CacheTestCase extends TestCase $this->assertEquals(13, $cache->get('add_test')); } - public function testMultiAdd() + public function testMultiAdd(): void { $cache = $this->prepare(); @@ -249,7 +249,7 @@ abstract class CacheTestCase extends TestCase $this->assertEquals(13, $cache->get('add_test')); } - public function testDelete() + public function testDelete(): void { $cache = $this->prepare(); @@ -258,14 +258,14 @@ abstract class CacheTestCase extends TestCase $this->assertFalse($cache->get('number_test')); } - public function testFlush() + public function testFlush(): void { $cache = $this->prepare(); $this->assertTrue($cache->flush()); $this->assertFalse($cache->get('number_test')); } - public function testGetOrSet() + public function testGetOrSet(): void { $cache = $this->prepare(); @@ -282,7 +282,7 @@ abstract class CacheTestCase extends TestCase return get_class($cache); } - public function testGetOrSetWithDependencies() + public function testGetOrSetWithDependencies(): void { $cache = $this->prepare(); $dependency = new TagDependency(['tags' => 'test']); diff --git a/tests/framework/caching/CallbackDependencyTest.php b/tests/framework/caching/CallbackDependencyTest.php index b2a93ff954..ac284068f2 100644 --- a/tests/framework/caching/CallbackDependencyTest.php +++ b/tests/framework/caching/CallbackDependencyTest.php @@ -8,7 +8,7 @@ use yii\caching\CallbackDependency; class CallbackDependencyTest extends TestCase { - public function testDependencyChange() + public function testDependencyChange(): void { $cache = new ArrayCache(); $dependencyValue = true; @@ -25,7 +25,7 @@ class CallbackDependencyTest extends TestCase $this->assertTrue($dependency->isChanged($cache)); } - public function testDependencyNotChanged() + public function testDependencyNotChanged(): void { $cache = new ArrayCache(); diff --git a/tests/framework/caching/DbCacheTest.php b/tests/framework/caching/DbCacheTest.php index e05aa446aa..4f43db38d0 100644 --- a/tests/framework/caching/DbCacheTest.php +++ b/tests/framework/caching/DbCacheTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\caching; +use yii\db\Connection; use yii\caching\DbCache; /** @@ -41,14 +42,14 @@ class DbCacheTest extends CacheTestCase /** * @param bool $reset whether to clean up the test database - * @return \yii\db\Connection + * @return Connection */ public function getConnection($reset = true) { if ($this->_connection === null) { $databases = self::getParam('databases'); $params = $databases['mysql']; - $db = new \yii\db\Connection(); + $db = new Connection(); $db->dsn = $params['dsn']; $db->username = $params['username']; $db->password = $params['password']; @@ -79,7 +80,7 @@ class DbCacheTest extends CacheTestCase return $this->_cacheInstance; } - public function testExpire() + public function testExpire(): void { $cache = $this->getCacheInstance(); @@ -91,7 +92,7 @@ class DbCacheTest extends CacheTestCase $this->assertFalse($cache->get('expire_test')); } - public function testExpireAdd() + public function testExpireAdd(): void { $cache = $this->getCacheInstance(); @@ -103,7 +104,7 @@ class DbCacheTest extends CacheTestCase $this->assertFalse($cache->get('expire_testa')); } - public function testSynchronousSetWithTheSameKey() + public function testSynchronousSetWithTheSameKey(): void { $KEY = 'sync-test-key'; $VALUE = 'sync-test-value'; diff --git a/tests/framework/caching/DbDependencyTest.php b/tests/framework/caching/DbDependencyTest.php index be7e002cce..48a8a6a84a 100644 --- a/tests/framework/caching/DbDependencyTest.php +++ b/tests/framework/caching/DbDependencyTest.php @@ -39,7 +39,7 @@ class DbDependencyTest extends DatabaseTestCase $db->createCommand()->insert('dependency_item', ['value' => 'initial'])->execute(); } - public function testQueryOneIsExecutedWhenQueryCacheEnabled() + public function testQueryOneIsExecutedWhenQueryCacheEnabled(): void { $db = $this->getConnection(false); $cache = new ArrayCache(); @@ -60,7 +60,7 @@ class DbDependencyTest extends DatabaseTestCase $this->assertTrue($dependency->isChanged($cache)); } - public function testQueryOneIsExecutedWhenQueryCacheDisabled() + public function testQueryOneIsExecutedWhenQueryCacheDisabled(): void { $db = $this->getConnection(false); $cache = new ArrayCache(); @@ -81,7 +81,7 @@ class DbDependencyTest extends DatabaseTestCase $this->assertTrue($dependency->isChanged($cache)); } - public function testMissingSqlThrowsException() + public function testMissingSqlThrowsException(): void { $this->expectException('\yii\base\InvalidConfigException'); diff --git a/tests/framework/caching/DbQueryDependencyTest.php b/tests/framework/caching/DbQueryDependencyTest.php index e7ac7fd24a..e8e01d2850 100644 --- a/tests/framework/caching/DbQueryDependencyTest.php +++ b/tests/framework/caching/DbQueryDependencyTest.php @@ -37,7 +37,7 @@ class DbQueryDependencyTest extends DatabaseTestCase $db->createCommand()->insert('dependency_item', ['value' => 'initial'])->execute(); } - public function testIsChanged() + public function testIsChanged(): void { $db = $this->getConnection(false); $cache = new ArrayCache(); @@ -62,7 +62,7 @@ class DbQueryDependencyTest extends DatabaseTestCase /** * @depends testIsChanged */ - public function testCustomMethod() + public function testCustomMethod(): void { $db = $this->getConnection(false); $cache = new ArrayCache(); @@ -86,7 +86,7 @@ class DbQueryDependencyTest extends DatabaseTestCase /** * @depends testCustomMethod */ - public function testCustomMethodCallback() + public function testCustomMethodCallback(): void { $db = $this->getConnection(false); $cache = new ArrayCache(); @@ -112,7 +112,7 @@ class DbQueryDependencyTest extends DatabaseTestCase /** * @depends testCustomMethod */ - public function testReusableAndCustomMethodCallback() + public function testReusableAndCustomMethodCallback(): void { $db = $this->getConnection(false); $cache = new ArrayCache(); diff --git a/tests/framework/caching/DependencyTest.php b/tests/framework/caching/DependencyTest.php index 05010e1058..1eb3aeb24b 100644 --- a/tests/framework/caching/DependencyTest.php +++ b/tests/framework/caching/DependencyTest.php @@ -21,7 +21,7 @@ use yiiunit\TestCase; */ class DependencyTest extends TestCase { - public function testResetReusableData() + public function testResetReusableData(): void { $value = ['dummy']; $dependency = new MockDependency(); @@ -33,7 +33,7 @@ class DependencyTest extends TestCase $this->assertEquals([], $this->getInaccessibleProperty($dependency, '_reusableData')); } - public function testGenerateReusableHash() + public function testGenerateReusableHash(): void { $dependency = $this->getMockForAbstractClass(Dependency::className()); $dependency->data = 'dummy'; @@ -43,7 +43,7 @@ class DependencyTest extends TestCase $this->assertEquals(40, strlen($result)); } - public function testIsChanged() + public function testIsChanged(): void { $dependency = $this->getMockForAbstractClass(Dependency::className()); $cache = $this->getMockForAbstractClass(Cache::className()); diff --git a/tests/framework/caching/FileCacheTest.php b/tests/framework/caching/FileCacheTest.php index 1f6f8747a1..85f69afb36 100644 --- a/tests/framework/caching/FileCacheTest.php +++ b/tests/framework/caching/FileCacheTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\caching; +use ReflectionClass; use yii\caching\FileCache; /** @@ -30,7 +31,7 @@ class FileCacheTest extends CacheTestCase return $this->_cacheInstance; } - public function testExpire() + public function testExpire(): void { $cache = $this->getCacheInstance(); @@ -42,7 +43,7 @@ class FileCacheTest extends CacheTestCase $this->assertFalse($cache->get('expire_test')); } - public function testExpireAdd() + public function testExpireAdd(): void { $cache = $this->getCacheInstance(); @@ -54,7 +55,7 @@ class FileCacheTest extends CacheTestCase $this->assertFalse($cache->get('expire_testa')); } - public function testKeyPrefix() + public function testKeyPrefix(): void { $keyPrefix = 'foobar'; $key = uniqid('uid-cache_'); @@ -68,7 +69,7 @@ class FileCacheTest extends CacheTestCase $value = \time(); - $refClass = new \ReflectionClass($cache); + $refClass = new ReflectionClass($cache); $refMethodGetCacheFile = $refClass->getMethod('getCacheFile'); @@ -90,13 +91,13 @@ class FileCacheTest extends CacheTestCase $this->assertEquals($value, $refMethodGet->invoke($cache, $key)); } - public function testStatCache() + public function testStatCache(): void { $cache = $this->getCacheInstance(); $cache->set(__FUNCTION__, 'cache1', 2); $normalizeKey = $cache->buildKey(__FUNCTION__); - $refClass = new \ReflectionClass($cache); + $refClass = new ReflectionClass($cache); $refMethodGetCacheFile = $refClass->getMethod('getCacheFile'); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible diff --git a/tests/framework/caching/MemCacheTest.php b/tests/framework/caching/MemCacheTest.php index 61f2cac9dd..02644a08ab 100644 --- a/tests/framework/caching/MemCacheTest.php +++ b/tests/framework/caching/MemCacheTest.php @@ -40,7 +40,7 @@ class MemCacheTest extends CacheTestCase return $this->_cacheInstance; } - public function testExpire() + public function testExpire(): void { if (getenv('GITHUB_ACTIONS') == 'true') { $this->markTestSkipped('Can not reliably test memcache expiry on GitHub actions.'); @@ -48,7 +48,7 @@ class MemCacheTest extends CacheTestCase parent::testExpire(); } - public function testExpireAdd() + public function testExpireAdd(): void { if (getenv('GITHUB_ACTIONS') == 'true') { $this->markTestSkipped('Can not reliably test memcache expiry on GitHub actions.'); diff --git a/tests/framework/caching/MemCachedTest.php b/tests/framework/caching/MemCachedTest.php index 70c0668d21..d05e149d03 100644 --- a/tests/framework/caching/MemCachedTest.php +++ b/tests/framework/caching/MemCachedTest.php @@ -48,7 +48,7 @@ class MemCachedTest extends CacheTestCase return $this->_cacheInstance; } - public function testExpire() + public function testExpire(): void { if (getenv('GITHUB_ACTIONS') == 'true') { $this->markTestSkipped('Can not reliably test memcached expiry on GitHub actions.'); @@ -56,7 +56,7 @@ class MemCachedTest extends CacheTestCase parent::testExpire(); } - public function testExpireAdd() + public function testExpireAdd(): void { if (getenv('GITHUB_ACTIONS') == 'true') { $this->markTestSkipped('Can not reliably test memcached expiry on GitHub actions.'); diff --git a/tests/framework/caching/MssqlCacheTest.php b/tests/framework/caching/MssqlCacheTest.php index 42f5b105bf..fc64010715 100644 --- a/tests/framework/caching/MssqlCacheTest.php +++ b/tests/framework/caching/MssqlCacheTest.php @@ -42,7 +42,7 @@ class MssqlCacheTest extends CacheTestCase /** * @param bool $reset whether to clean up the test database - * @return \yii\db\Connection + * @return Connection */ public function getConnection($reset = true) { @@ -79,7 +79,7 @@ class MssqlCacheTest extends CacheTestCase return $this->_cacheInstance; } - public function testExpire() + public function testExpire(): void { $cache = $this->getCacheInstance(); @@ -91,7 +91,7 @@ class MssqlCacheTest extends CacheTestCase $this->assertFalse($cache->get('expire_test')); } - public function testExpireAdd() + public function testExpireAdd(): void { $cache = $this->getCacheInstance(); @@ -103,7 +103,7 @@ class MssqlCacheTest extends CacheTestCase $this->assertFalse($cache->get('expire_testa')); } - public function testSynchronousSetWithTheSameKey() + public function testSynchronousSetWithTheSameKey(): void { $KEY = 'sync-test-key'; $VALUE = 'sync-test-value'; diff --git a/tests/framework/caching/TagDependencyTest.php b/tests/framework/caching/TagDependencyTest.php index 41f9552dd0..e7fdea3469 100644 --- a/tests/framework/caching/TagDependencyTest.php +++ b/tests/framework/caching/TagDependencyTest.php @@ -17,7 +17,7 @@ use yiiunit\TestCase; */ class TagDependencyTest extends TestCase { - public function testInvalidate() + public function testInvalidate(): void { $cache = new FileCache(['cachePath' => '@yiiunit/runtime/cache']); diff --git a/tests/framework/console/ControllerTest.php b/tests/framework/console/ControllerTest.php index 6922baa9a4..9ed3a7868d 100644 --- a/tests/framework/console/ControllerTest.php +++ b/tests/framework/console/ControllerTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\console; +use yii\data\ArrayDataProvider; use RuntimeException; use yii\console\Exception; use yiiunit\framework\console\stubs\DummyService; @@ -38,7 +39,7 @@ class ControllerTest extends TestCase ]; } - public function testBindArrayToActionParams() + public function testBindArrayToActionParams(): void { $controller = new FakeController('fake', Yii::$app); @@ -47,7 +48,7 @@ class ControllerTest extends TestCase $this->assertEquals([], $controller->runAction('aksi4', $params)); } - public function testBindActionParams() + public function testBindActionParams(): void { $controller = new FakeController('fake', Yii::$app); @@ -105,7 +106,7 @@ class ControllerTest extends TestCase $result = $controller->runAction('aksi3', $params); } - public function testNullableInjectedActionParams() + public function testNullableInjectedActionParams(): void { // Use the PHP71 controller for this test $this->controller = new FakePhp71Controller('fake', new Application([ @@ -117,11 +118,11 @@ class ControllerTest extends TestCase $injectionAction = new InlineAction('injection', $this->controller, 'actionNullableInjection'); $params = []; $args = $this->controller->bindActionParams($injectionAction, $params); - $this->assertEquals(\Yii::$app->request, $args[0]); + $this->assertEquals(Yii::$app->request, $args[0]); $this->assertNull($args[1]); } - public function testInjectionContainerException() + public function testInjectionContainerException(): void { // Use the PHP71 controller for this test $this->controller = new FakePhp71Controller('fake', new Application([ @@ -132,8 +133,8 @@ class ControllerTest extends TestCase $injectionAction = new InlineAction('injection', $this->controller, 'actionInjection'); $params = ['between' => 'test', 'after' => 'another', 'before' => 'test']; - \Yii::$container->set(DummyService::className(), function () { - throw new \RuntimeException('uh oh'); + Yii::$container->set(DummyService::className(), function () { + throw new RuntimeException('uh oh'); }); $this->expectException(get_class(new RuntimeException())); @@ -141,7 +142,7 @@ class ControllerTest extends TestCase $this->controller->bindActionParams($injectionAction, $params); } - public function testUnknownInjection() + public function testUnknownInjection(): void { // Use the PHP71 controller for this test $this->controller = new FakePhp71Controller('fake', new Application([ @@ -152,13 +153,13 @@ class ControllerTest extends TestCase $injectionAction = new InlineAction('injection', $this->controller, 'actionInjection'); $params = ['between' => 'test', 'after' => 'another', 'before' => 'test']; - \Yii::$container->clear(DummyService::className()); + Yii::$container->clear(DummyService::className()); $this->expectException(get_class(new Exception())); $this->expectExceptionMessage('Could not load required service: dummyService'); $this->controller->bindActionParams($injectionAction, $params); } - public function testInjectedActionParams() + public function testInjectedActionParams(): void { // Use the PHP71 controller for this test $this->controller = new FakePhp71Controller('fake', new Application([ @@ -169,27 +170,27 @@ class ControllerTest extends TestCase $injectionAction = new InlineAction('injection', $this->controller, 'actionInjection'); $params = ['between' => 'test', 'after' => 'another', 'before' => 'test']; - \Yii::$container->set(DummyService::className(), DummyService::className()); + Yii::$container->set(DummyService::className(), DummyService::className()); $args = $this->controller->bindActionParams($injectionAction, $params); $this->assertEquals($params['before'], $args[0]); - $this->assertEquals(\Yii::$app->request, $args[1]); - $this->assertEquals('Component: yii\console\Request $request', \Yii::$app->requestedParams['request']); + $this->assertEquals(Yii::$app->request, $args[1]); + $this->assertEquals('Component: yii\console\Request $request', Yii::$app->requestedParams['request']); $this->assertEquals($params['between'], $args[2]); $this->assertInstanceOf(DummyService::className(), $args[3]); - $this->assertEquals('Container DI: yiiunit\framework\console\stubs\DummyService $dummyService', \Yii::$app->requestedParams['dummyService']); + $this->assertEquals('Container DI: yiiunit\framework\console\stubs\DummyService $dummyService', Yii::$app->requestedParams['dummyService']); $this->assertNull($args[4]); - $this->assertEquals('Unavailable service: post', \Yii::$app->requestedParams['post']); + $this->assertEquals('Unavailable service: post', Yii::$app->requestedParams['post']); $this->assertEquals($params['after'], $args[5]); } - public function testInjectedActionParamsFromModule() + public function testInjectedActionParamsFromModule(): void { - $module = new \yii\base\Module('fake', new Application([ + $module = new Module('fake', new Application([ 'id' => 'app', 'basePath' => __DIR__, ])); $module->set('yii\data\DataProviderInterface', [ - 'class' => \yii\data\ArrayDataProvider::className(), + 'class' => ArrayDataProvider::className(), ]); // Use the PHP71 controller for this test $this->controller = new FakePhp71Controller('fake', $module); @@ -197,11 +198,11 @@ class ControllerTest extends TestCase $injectionAction = new InlineAction('injection', $this->controller, 'actionModuleServiceInjection'); $args = $this->controller->bindActionParams($injectionAction, []); - $this->assertInstanceOf(\yii\data\ArrayDataProvider::className(), $args[0]); - $this->assertEquals('Module yii\base\Module DI: yii\data\DataProviderInterface $dataProvider', \Yii::$app->requestedParams['dataProvider']); + $this->assertInstanceOf(ArrayDataProvider::className(), $args[0]); + $this->assertEquals('Module yii\base\Module DI: yii\data\DataProviderInterface $dataProvider', Yii::$app->requestedParams['dataProvider']); } - public function assertResponseStatus($status, $response) + public function assertResponseStatus($status, $response): void { $this->assertInstanceOf('yii\console\Response', $response); $this->assertSame($status, $response->exitStatus); @@ -214,7 +215,7 @@ class ControllerTest extends TestCase return Yii::$app->handleRequest($request); } - public function testResponse() + public function testResponse(): void { $status = 123; @@ -234,7 +235,7 @@ class ControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/12028 */ - public function testHelpOptionNotSet() + public function testHelpOptionNotSet(): void { $controller = new FakeController('posts', Yii::$app); $controller->runAction('index'); @@ -246,7 +247,7 @@ class ControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/12028 */ - public function testHelpOption() + public function testHelpOption(): void { $controller = new FakeController('posts', Yii::$app); $controller->help = true; @@ -263,7 +264,7 @@ class ControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/13071 */ - public function testHelpOptionWithModule() + public function testHelpOptionWithModule(): void { $controller = new FakeController('posts', new Module('news')); $controller->help = true; @@ -276,7 +277,7 @@ class ControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/19028 */ - public function testGetActionArgsHelp() + public function testGetActionArgsHelp(): void { $controller = new FakeController('fake', Yii::$app); $help = $controller->getActionArgsHelp($controller->createAction('aksi2')); @@ -293,7 +294,7 @@ class ControllerTest extends TestCase $this->assertEquals('string', $help['value']['type']); } - public function testGetActionHelpSummaryOnNull() + public function testGetActionHelpSummaryOnNull(): void { $controller = new FakeController('fake', Yii::$app); diff --git a/tests/framework/console/FakeController.php b/tests/framework/console/FakeController.php index 670ab68076..540cd1a0b5 100644 --- a/tests/framework/console/FakeController.php +++ b/tests/framework/console/FakeController.php @@ -51,7 +51,7 @@ class FakeController extends Controller ]; } - public function actionIndex() + public function actionIndex(): void { self::$_wasActionIndexCalled = true; } diff --git a/tests/framework/console/FakeHelpController.php b/tests/framework/console/FakeHelpController.php index 24277688c0..af28037d93 100644 --- a/tests/framework/console/FakeHelpController.php +++ b/tests/framework/console/FakeHelpController.php @@ -14,7 +14,7 @@ class FakeHelpController extends HelpController { private static $_actionIndexLastCallParams; - public function actionIndex($command = null) + public function actionIndex($command = null): void { self::$_actionIndexLastCallParams = func_get_args(); } diff --git a/tests/framework/console/RequestTest.php b/tests/framework/console/RequestTest.php index 7704d13b62..af90715a47 100644 --- a/tests/framework/console/RequestTest.php +++ b/tests/framework/console/RequestTest.php @@ -187,7 +187,7 @@ class RequestTest extends TestCase * @param array $expected * @param array|null $expectedException */ - public function testResolve($params, $expected, $expectedException = null) + public function testResolve($params, $expected, $expectedException = null): void { if (isset($expectedException)) { $this->expectException($expectedException[0]); diff --git a/tests/framework/console/UnknownCommandExceptionTest.php b/tests/framework/console/UnknownCommandExceptionTest.php index a7502593b2..179ba23d87 100644 --- a/tests/framework/console/UnknownCommandExceptionTest.php +++ b/tests/framework/console/UnknownCommandExceptionTest.php @@ -62,13 +62,13 @@ class UnknownCommandExceptionTest extends TestCase * @param string $command * @param array $expectedSuggestion */ - public function testSuggestCommand($command, $expectedSuggestion) + public function testSuggestCommand($command, $expectedSuggestion): void { $exception = new UnknownCommandException($command, Yii::$app); $this->assertEquals($expectedSuggestion, $exception->getSuggestedAlternatives()); } - public function testNameAndConstructor() + public function testNameAndConstructor(): void { $exception = new UnknownCommandException('test', Yii::$app); $this->assertEquals('Unknown command', $exception->getName()); diff --git a/tests/framework/console/controllers/AssetControllerTest.php b/tests/framework/console/controllers/AssetControllerTest.php index 828bf7a785..86e36ba5ba 100644 --- a/tests/framework/console/controllers/AssetControllerTest.php +++ b/tests/framework/console/controllers/AssetControllerTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\console\controllers; +use Exception; use Yii; use yii\console\controllers\AssetController; use yii\helpers\ArrayHelper; @@ -134,13 +135,13 @@ class AssetControllerTest extends TestCase * @param string $fileName output file name. * @param array[] $bundles asset bundles config. * @param array $config additional config parameters. - * @throws \Exception on failure. + * @throws Exception on failure. */ protected function createCompressConfigFile($fileName, array $bundles, array $config = []) { $content = 'createCompressConfig($bundles, $config), true) . ';'; if (file_put_contents($fileName, $content) <= 0) { - throw new \Exception("Unable to create file '{$fileName}'!"); + throw new Exception("Unable to create file '{$fileName}'!"); } } @@ -149,7 +150,7 @@ class AssetControllerTest extends TestCase * @param string $fileRelativeName file name relative to [[testFilePath]] * @param string $content file content * @param string $fileBasePath base path for the created files, if not set [[testFilePath]] is used. - * @throws \Exception on failure. + * @throws Exception on failure. */ protected function createAssetSourceFile($fileRelativeName, $content, $fileBasePath = null) { @@ -159,7 +160,7 @@ class AssetControllerTest extends TestCase $fileFullName = $fileBasePath . DIRECTORY_SEPARATOR . $fileRelativeName; $this->createDir(dirname($fileFullName)); if (file_put_contents($fileFullName, $content) <= 0) { - throw new \Exception("Unable to create file '{$fileFullName}'!"); + throw new Exception("Unable to create file '{$fileFullName}'!"); } } @@ -248,7 +249,7 @@ EOL; // Tests : - public function testActionTemplate() + public function testActionTemplate(): void { $configFileName = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php'; $this->runAssetControllerAction('template', [$configFileName]); @@ -257,7 +258,7 @@ EOL; $this->assertIsArray($config, 'Invalid config created!'); } - public function testActionCompress() + public function testActionCompress(): void { // Given : $cssFiles = [ @@ -337,7 +338,7 @@ EOL; * * @see https://github.com/yiisoft/yii2/issues/5194 */ - public function testCompressExternalAsset() + public function testCompressExternalAsset(): void { // Given : $externalAssetConfig = [ @@ -408,7 +409,7 @@ EOL; * * @see https://github.com/yiisoft/yii2/issues/7539 */ - public function testDetectCircularDependency() + public function testDetectCircularDependency(): void { // Given : $namespace = __NAMESPACE__; @@ -571,7 +572,7 @@ EOL; * @param $outputFilePath * @param $expectedCssContent */ - public function testAdjustCssUrl($cssContent, $inputFilePath, $outputFilePath, $expectedCssContent) + public function testAdjustCssUrl($cssContent, $inputFilePath, $outputFilePath, $expectedCssContent): void { $adjustedCssContent = $this->invokeAssetControllerMethod('adjustCssUrl', [$cssContent, $inputFilePath, $outputFilePath]); @@ -618,7 +619,7 @@ EOL; * @param string $sourcePath * @param string $expectedRealPath */ - public function testFindRealPath($sourcePath, $expectedRealPath) + public function testFindRealPath($sourcePath, $expectedRealPath): void { $expectedRealPath = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $expectedRealPath); $realPath = $this->invokeAssetControllerMethod('findRealPath', [$sourcePath]); @@ -630,7 +631,7 @@ EOL; * * @see https://github.com/yiisoft/yii2/issues/9708 */ - public function testActionCompressDeleteSource() + public function testActionCompressDeleteSource(): void { // Given : $cssFiles = [ @@ -700,7 +701,7 @@ EOL; * * @see https://github.com/yiisoft/yii2/issues/10567 */ - public function testActionCompressOverrideAsExternal() + public function testActionCompressOverrideAsExternal(): void { // Given : $cssFiles = [ diff --git a/tests/framework/console/controllers/BaseMessageControllerTest.php b/tests/framework/console/controllers/BaseMessageControllerTest.php index bb3c5d2cde..8b1f858c22 100644 --- a/tests/framework/console/controllers/BaseMessageControllerTest.php +++ b/tests/framework/console/controllers/BaseMessageControllerTest.php @@ -146,7 +146,7 @@ abstract class BaseMessageControllerTest extends TestCase // Tests: - public function testActionConfig() + public function testActionConfig(): void { $configFileName = $this->configFileName; $out = $this->runMessageControllerAction('config', [$configFileName]); @@ -156,20 +156,20 @@ abstract class BaseMessageControllerTest extends TestCase ); } - public function testActionConfigSubDir() + public function testActionConfigSubDir(): void { $configFileName = Yii::getAlias('@yiiunit/runtime/not_existing_subdir') . DIRECTORY_SEPARATOR . 'message_controller_test_config-' . md5(uniqid()) . '.php'; $out = $this->runMessageControllerAction('config', [$configFileName]); $this->assertFileExists($configFileName, "Unable to create config file in subdirectory. Command output:\n\n" . $out); } - public function testConfigFileNotExist() + public function testConfigFileNotExist(): void { $this->expectException('yii\\console\\Exception'); $this->runMessageControllerAction('extract', ['not_existing_file.php']); } - public function testCreateTranslation() + public function testCreateTranslation(): void { $category = 'test.category1'; $message = 'test message'; @@ -188,7 +188,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @depends testCreateTranslation */ - public function testNothingToSave() + public function testNothingToSave(): void { $category = 'test_category2'; $message = 'test message'; @@ -208,7 +208,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @depends testCreateTranslation */ - public function testMerge() + public function testMerge(): void { $category = 'test_category3'; @@ -237,7 +237,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @depends testMerge */ - public function testMarkObsoleteMessages() + public function testMarkObsoleteMessages(): void { $category = 'category'; @@ -260,7 +260,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @depends testMerge */ - public function removeObsoleteMessages() + public function removeObsoleteMessages(): void { $category = 'category'; @@ -282,7 +282,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @depends testMerge */ - public function testMergeWithContentZero() + public function testMergeWithContentZero(): void { $category = 'test_category5'; @@ -320,7 +320,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @depends testCreateTranslation */ - public function testMultipleTranslators() + public function testMultipleTranslators(): void { $category = 'test_category6'; @@ -352,7 +352,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @depends testCreateTranslation */ - public function testMultipleCategories() + public function testMultipleCategories(): void { $category1 = 'category1'; $category2 = 'category2'; @@ -389,7 +389,7 @@ abstract class BaseMessageControllerTest extends TestCase $this->assertArrayNotHasKey($message2, $messages2, "message2 found in category2. Command output:\n\n" . $out); } - public function testIgnoreCategories() + public function testIgnoreCategories(): void { $category1 = 'category1'; $category2 = 'category2'; @@ -435,7 +435,7 @@ abstract class BaseMessageControllerTest extends TestCase * * @see https://github.com/yiisoft/yii2/issues/8286 */ - public function testCreateTranslationFromNested() + public function testCreateTranslationFromNested(): void { $category = 'test.category1'; $mainMessage = 'main message'; @@ -456,7 +456,7 @@ abstract class BaseMessageControllerTest extends TestCase * * @see https://github.com/yiisoft/yii2/issues/11502 */ - public function testMissingLanguage() + public function testMissingLanguage(): void { $category = 'multiLangCategory'; $mainMessage = 'multiLangMessage'; @@ -482,7 +482,7 @@ abstract class BaseMessageControllerTest extends TestCase * * @see https://github.com/yiisoft/yii2/issues/13824 */ - public function testCreateTranslationFromConcatenatedString() + public function testCreateTranslationFromConcatenatedString(): void { $category = 'test.category1'; $mainMessage = 'main message second message third message'; @@ -503,7 +503,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/14016 */ - public function testShouldNotMarkUnused() + public function testShouldNotMarkUnused(): void { $category = 'testShouldNotMarkUnused'; @@ -538,7 +538,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/13792 */ - public function testShouldNotRemoveUnused() + public function testShouldNotRemoveUnused(): void { $category = 'my'; @@ -576,7 +576,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/16828 */ - public function testPartialTranslator() + public function testPartialTranslator(): void { $category = 'category'; $negativeKey1 = 'Should not find this'; @@ -610,7 +610,7 @@ abstract class BaseMessageControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/17098 */ - public function testMessageExtractActionWhenMessageUsingParamsReturnedFromMethodCalls() + public function testMessageExtractActionWhenMessageUsingParamsReturnedFromMethodCalls(): void { $sourceFileContent = " echo PHP_EOL, Yii::t('app', '1. Simple message'); @@ -653,7 +653,7 @@ abstract class BaseMessageControllerTest extends TestCase ], $messages); } - public function testMessagesSorting() + public function testMessagesSorting(): void { $category = 'test_order_category'; $key1 = 'key1'; diff --git a/tests/framework/console/controllers/CacheControllerTest.php b/tests/framework/console/controllers/CacheControllerTest.php index a77d9d8334..d1c5d55219 100644 --- a/tests/framework/console/controllers/CacheControllerTest.php +++ b/tests/framework/console/controllers/CacheControllerTest.php @@ -85,7 +85,7 @@ class CacheControllerTest extends TestCase } } - public function testFlushOne() + public function testFlushOne(): void { Yii::$app->firstCache->set('firstKey', 'firstValue'); Yii::$app->firstCache->set('secondKey', 'secondValue'); @@ -98,7 +98,7 @@ class CacheControllerTest extends TestCase $this->assertEquals('thirdValue', Yii::$app->secondCache->get('thirdKey'), 'second cache data should not be flushed'); } - public function testClearSchema() + public function testClearSchema(): void { $schema = Yii::$app->db->schema; Yii::$app->db->createCommand()->createTable('test_schema_cache', ['id' => 'pk'])->execute(); @@ -116,7 +116,7 @@ class CacheControllerTest extends TestCase $this->assertEquals($noCacheSchemas, $cacheSchema, 'Schema cache should be flushed.'); } - public function testFlushBoth() + public function testFlushBoth(): void { Yii::$app->firstCache->set('firstKey', 'firstValue'); Yii::$app->firstCache->set('secondKey', 'secondValue'); @@ -129,7 +129,7 @@ class CacheControllerTest extends TestCase $this->assertFalse(Yii::$app->secondCache->get('thirdKey'), 'second cache data should be flushed'); } - public function testNotFoundFlush() + public function testNotFoundFlush(): void { Yii::$app->firstCache->set('firstKey', 'firstValue'); @@ -138,7 +138,7 @@ class CacheControllerTest extends TestCase $this->assertEquals('firstValue', Yii::$app->firstCache->get('firstKey'), 'first cache data should not be flushed'); } - public function testNothingToFlushException() + public function testNothingToFlushException(): void { $this->expectException('yii\console\Exception'); $this->expectExceptionMessage('You should specify cache components names'); @@ -146,7 +146,7 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlush(); } - public function testFlushAll() + public function testFlushAll(): void { Yii::$app->firstCache->set('firstKey', 'firstValue'); Yii::$app->secondCache->set('secondKey', 'secondValue'); diff --git a/tests/framework/console/controllers/DbMessageControllerTest.php b/tests/framework/console/controllers/DbMessageControllerTest.php index d685f3bad9..17d6c89c49 100644 --- a/tests/framework/console/controllers/DbMessageControllerTest.php +++ b/tests/framework/console/controllers/DbMessageControllerTest.php @@ -8,6 +8,14 @@ namespace yiiunit\framework\console\controllers; +use yii\console\Application; +use yii\console\Controller; +use yii\helpers\ArrayHelper; +use yii\db\Query; +use yii\db\Expression; +use yii\base\InvalidParamException; +use yii\db\Exception; +use yii\base\InvalidConfigException; use Yii; use yii\db\Connection; @@ -30,7 +38,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest protected static function runConsoleAction($route, $params = []) { if (Yii::$app === null) { - new \yii\console\Application([ + new Application([ 'id' => 'Migrator', 'basePath' => '@yiiunit', 'controllerMap' => [ @@ -45,7 +53,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest ob_start(); $result = Yii::$app->runAction($route, $params); echo 'Result is ' . $result; - if ($result !== \yii\console\Controller::EXIT_CODE_NORMAL) { + if ($result !== Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { ob_end_clean(); @@ -83,10 +91,10 @@ class DbMessageControllerTest extends BaseMessageControllerTest } /** - * @throws \yii\base\InvalidParamException - * @throws \yii\db\Exception - * @throws \yii\base\InvalidConfigException - * @return \yii\db\Connection + * @throws InvalidParamException + * @throws Exception + * @throws InvalidConfigException + * @return Connection */ public static function getConnection() { @@ -150,11 +158,11 @@ class DbMessageControllerTest extends BaseMessageControllerTest */ protected function loadMessages($category) { - return \yii\helpers\ArrayHelper::map((new \yii\db\Query()) + return ArrayHelper::map((new Query()) ->select(['message' => 't1.message', 'translation' => 't2.translation']) ->from(['t1' => 'source_message', 't2' => 'message']) ->where([ - 't1.id' => new \yii\db\Expression('[[t2.id]]'), + 't1.id' => new Expression('[[t2.id]]'), 't1.category' => $category, 't2.language' => $this->language, ])->all(static::$db), 'message', 'translation'); @@ -166,7 +174,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest * Source is marked instead of translation. * @depends testMerge */ - public function testMarkObsoleteMessages() + public function testMarkObsoleteMessages(): void { $category = 'category'; @@ -188,7 +196,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest $this->assertEquals($obsoleteTranslation, $messages[$obsoleteMessage], "Obsolete message was not marked properly. Command output:\n\n" . $out); } - public function testMessagesSorting() + public function testMessagesSorting(): void { $this->markTestSkipped('There\'s no need to order messages for database'); } diff --git a/tests/framework/console/controllers/EchoMigrateController.php b/tests/framework/console/controllers/EchoMigrateController.php index 2eefd60267..5320235b6a 100644 --- a/tests/framework/console/controllers/EchoMigrateController.php +++ b/tests/framework/console/controllers/EchoMigrateController.php @@ -18,7 +18,7 @@ class EchoMigrateController extends MigrateController /** * {@inheritdoc} */ - public function stdout($string) + public function stdout($string): void { echo $string; } diff --git a/tests/framework/console/controllers/FixtureControllerTest.php b/tests/framework/console/controllers/FixtureControllerTest.php index bb912efb9d..c2350c30d0 100644 --- a/tests/framework/console/controllers/FixtureControllerTest.php +++ b/tests/framework/console/controllers/FixtureControllerTest.php @@ -25,7 +25,7 @@ use yiiunit\framework\db\DatabaseTestCase; class FixtureControllerTest extends DatabaseTestCase { /** - * @var \yiiunit\framework\console\controllers\FixtureConsoledController + * @var FixtureConsoledController */ private $_fixtureController; @@ -36,7 +36,7 @@ class FixtureControllerTest extends DatabaseTestCase parent::setUp(); $db = $this->getConnection(); - \Yii::$app->set('db', $db); + Yii::$app->set('db', $db); ActiveRecord::$db = $db; $this->_fixtureController = Yii::createObject([ @@ -55,7 +55,7 @@ class FixtureControllerTest extends DatabaseTestCase parent::tearDown(); } - public function testLoadGlobalFixture() + public function testLoadGlobalFixture(): void { $this->_fixtureController->globalFixtures = [ '\yiiunit\data\console\controllers\fixtures\Global', @@ -67,7 +67,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertCount(1, FixtureStorage::$firstFixtureData, 'first fixture data should be loaded'); } - public function testLoadGlobalFixtureWithFixture() + public function testLoadGlobalFixtureWithFixture(): void { $this->_fixtureController->globalFixtures = [ '\yiiunit\data\console\controllers\fixtures\GlobalFixture', @@ -79,7 +79,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertCount(1, FixtureStorage::$firstFixtureData, 'first fixture data should be loaded'); } - public function testUnloadGlobalFixture() + public function testUnloadGlobalFixture(): void { $this->_fixtureController->globalFixtures = [ '\yiiunit\data\console\controllers\fixtures\Global', @@ -97,7 +97,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should be unloaded'); } - public function testLoadAll() + public function testLoadAll(): void { $this->assertEmpty(FixtureStorage::$globalFixturesData, 'global fixture data should be empty'); $this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should be empty'); @@ -114,7 +114,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertCount(1, FixtureStorage::$subdirSecondFixtureData, 'subdir / second fixture data should be loaded'); } - public function testUnloadAll() + public function testUnloadAll(): void { FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; FixtureStorage::$firstFixtureData[] = 'some seeded first fixture data'; @@ -137,7 +137,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should be unloaded'); } - public function testLoadParticularExceptOnes() + public function testLoadParticularExceptOnes(): void { $this->_fixtureController->actionLoad(['First', 'subdir/First', '-Second', '-Global', '-subdir/Second']); @@ -148,7 +148,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should not be loaded'); } - public function testUnloadParticularExceptOnes() + public function testUnloadParticularExceptOnes(): void { FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; FixtureStorage::$firstFixtureData[] = 'some seeded first fixture data'; @@ -171,7 +171,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertNotEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should not be unloaded'); } - public function testLoadAllExceptOnes() + public function testLoadAllExceptOnes(): void { $this->_fixtureController->actionLoad(['*', '-Second', '-Global', '-subdir/First']); @@ -182,7 +182,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertEmpty(FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should not be loaded'); } - public function testUnloadAllExceptOnes() + public function testUnloadAllExceptOnes(): void { FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; FixtureStorage::$firstFixtureData[] = 'some seeded first fixture data'; @@ -199,7 +199,7 @@ class FixtureControllerTest extends DatabaseTestCase $this->assertNotEmpty(FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should not be unloaded'); } - public function testNothingToLoadParticularExceptOnes() + public function testNothingToLoadParticularExceptOnes(): void { $this->_fixtureController->actionLoad(['First', '-First']); @@ -209,26 +209,26 @@ class FixtureControllerTest extends DatabaseTestCase ); } - public function testNothingToUnloadParticularExceptOnes() + public function testNothingToUnloadParticularExceptOnes(): void { $this->_fixtureController->actionUnload(['First', '-First']); $this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should not be loaded'); } - public function testNoFixturesWereFoundInLoad() + public function testNoFixturesWereFoundInLoad(): void { $this->expectException('\yii\console\Exception'); $this->_fixtureController->actionLoad(['NotExistingFixture']); } - public function testNoFixturesWereFoundInUnload() + public function testNoFixturesWereFoundInUnload(): void { $this->expectException('\yii\console\Exception'); $this->_fixtureController->actionUnload(['NotExistingFixture']); } - public function testLoadActiveFixtureSequence() + public function testLoadActiveFixtureSequence(): void { $this->assertEmpty(FixtureStorage::$activeFixtureSequence, 'Active fixture sequence should be empty.'); diff --git a/tests/framework/console/controllers/HelpControllerTest.php b/tests/framework/console/controllers/HelpControllerTest.php index 7377716de0..39d4cf3aa1 100644 --- a/tests/framework/console/controllers/HelpControllerTest.php +++ b/tests/framework/console/controllers/HelpControllerTest.php @@ -54,7 +54,7 @@ class HelpControllerTest extends TestCase return $controller->flushStdOutBuffer(); } - public function testModuleControllersList() + public function testModuleControllersList(): void { $this->mockApplication([ 'enableCoreCommands' => false, @@ -77,7 +77,7 @@ STRING , $result); } - public function testActionList() + public function testActionList(): void { $this->mockApplication([ 'enableCoreCommands' => false, @@ -113,7 +113,7 @@ STRING , $result); } - public function testActionListActionOptions() + public function testActionListActionOptions(): void { $this->mockApplication([ 'enableCoreCommands' => false, @@ -135,7 +135,7 @@ STRING , $result); } - public function testActionUsage() + public function testActionUsage(): void { $this->mockApplication([ 'enableCoreCommands' => false, @@ -152,7 +152,7 @@ STRING , $result); } - public function testActionIndex() + public function testActionIndex(): void { $result = Console::stripAnsiFormat($this->runControllerAction('index')); $this->assertStringContainsString('This is Yii version ', $result); @@ -161,7 +161,7 @@ STRING $this->assertStringContainsString('bootstrap.php help', $result); } - public function testActionIndexWithHelpCommand() + public function testActionIndexWithHelpCommand(): void { $result = Console::stripAnsiFormat($this->runControllerAction('index', ['command' => 'help/index'])); $this->assertStringContainsString('Displays available commands or the detailed information', $result); @@ -173,7 +173,7 @@ STRING $this->assertStringContainsString('--interactive: boolean, 0 or 1 (defaults to 1)', $result); } - public function testActionIndexWithServeCommand() + public function testActionIndexWithServeCommand(): void { $result = Console::stripAnsiFormat($this->runControllerAction('index', ['command' => 'serve'])); $this->assertStringContainsString('Runs PHP built-in web server', $result); @@ -188,7 +188,7 @@ STRING $this->assertStringContainsString('--router, -r: string', $result); } - public function testActionListContainsNoEmptyCommands() + public function testActionListContainsNoEmptyCommands(): void { $this->mockApplication([ 'enableCoreCommands' => false, @@ -200,7 +200,7 @@ STRING $this->assertStringContainsString("fake-no-default/index\n", $result); } - public function testActionIndexContainsNoEmptyCommands() + public function testActionIndexContainsNoEmptyCommands(): void { $this->mockApplication([ 'enableCoreCommands' => false, diff --git a/tests/framework/console/controllers/MigrateControllerTest.php b/tests/framework/console/controllers/MigrateControllerTest.php index 20f41abfe6..71cdb1fb60 100644 --- a/tests/framework/console/controllers/MigrateControllerTest.php +++ b/tests/framework/console/controllers/MigrateControllerTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\console\controllers; +use yii\db\Exception; use Yii; use yii\console\controllers\MigrateController; use yii\console\ExitCode; @@ -60,7 +61,7 @@ class MigrateControllerTest extends TestCase return $query->from('migration')->all(); } - public function assertFileContent($expectedFile, $class, $table, $namespace = null) + public function assertFileContent($expectedFile, $class, $table, $namespace = null): void { if ($namespace) { $namespace = "namespace {$namespace};\n\n"; @@ -95,7 +96,7 @@ class MigrateControllerTest extends TestCase $this->assertFileContent($expectedFile, $class, $table, $namespace); } - public function assertFileContentJunction($expectedFile, $class, $junctionTable, $firstTable, $secondTable, $namespace = null) + public function assertFileContentJunction($expectedFile, $class, $junctionTable, $firstTable, $secondTable, $namespace = null): void { if ($namespace) { $namespace = "namespace {$namespace};\n\n"; @@ -341,7 +342,7 @@ class MigrateControllerTest extends TestCase * @param array $params * @dataProvider generateMigrationDataProvider */ - public function testGenerateMigration($expectedFile, $migrationName, $table, $params) + public function testGenerateMigration($expectedFile, $migrationName, $table, $params): void { $this->migrationNamespace = 'yiiunit\runtime\test_migrations'; @@ -386,7 +387,7 @@ class MigrateControllerTest extends TestCase * @param string $secondTable * @dataProvider generateJunctionMigrationDataProvider */ - public function testGenerateJunctionMigration($migrationName, $junctionTable, $firstTable, $secondTable) + public function testGenerateJunctionMigration($migrationName, $junctionTable, $firstTable, $secondTable): void { $this->migrationNamespace = 'yiiunit\runtime\test_migrations'; @@ -413,7 +414,7 @@ class MigrateControllerTest extends TestCase ); } - public function testUpdatingLongNamedMigration() + public function testUpdatingLongNamedMigration(): void { $this->createMigration(str_repeat('a', 180)); @@ -424,7 +425,7 @@ class MigrateControllerTest extends TestCase $this->assertStringContainsString('is too long. Its not possible to apply this migration.', $result); } - public function testNamedMigrationWithCustomLimit() + public function testNamedMigrationWithCustomLimit(): void { Yii::$app->db->createCommand()->createTable('migration', [ 'version' => 'varchar(255) NOT NULL PRIMARY KEY', // varchar(255) is longer than the default of 180 @@ -440,7 +441,7 @@ class MigrateControllerTest extends TestCase $this->assertStringContainsString('Migrated up successfully.', $result); } - public function testCreateLongNamedMigration() + public function testCreateLongNamedMigration(): void { $this->setOutputCallback(function ($output) { return null; @@ -460,9 +461,9 @@ class MigrateControllerTest extends TestCase * Test the migrate:fresh command. * @dataProvider refreshMigrationDataProvider * @param $db - * @throws \yii\db\Exception + * @throws Exception */ - public function testRefreshMigration($db) + public function testRefreshMigration($db): void { if ($db !== 'default') { $this->switchDbConnection($db); @@ -497,7 +498,7 @@ class MigrateControllerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/12980 */ - public function testGetMigrationHistory() + public function testGetMigrationHistory(): void { $controllerConfig = [ 'migrationPath' => null, diff --git a/tests/framework/console/controllers/MigrateControllerTestTrait.php b/tests/framework/console/controllers/MigrateControllerTestTrait.php index 320f220bc7..db301b48bf 100644 --- a/tests/framework/console/controllers/MigrateControllerTestTrait.php +++ b/tests/framework/console/controllers/MigrateControllerTestTrait.php @@ -49,7 +49,7 @@ trait MigrateControllerTestTrait return $this->migrationExitCode; } - public function setUpMigrationPath() + public function setUpMigrationPath(): void { $this->migrationNamespace = 'yiiunit\runtime\test_migrations'; $this->migrationPath = Yii::getAlias('@yiiunit/runtime/test_migrations'); @@ -59,7 +59,7 @@ trait MigrateControllerTestTrait } } - public function tearDownMigrationPath() + public function tearDownMigrationPath(): void { FileHelper::removeDirectory($this->migrationPath); FileHelper::removeDirectory(Yii::getAlias('@yiiunit/runtime/app_migrations')); @@ -221,7 +221,7 @@ CODE; // Tests : - public function testCreate() + public function testCreate(): void { $migrationName = 'test_migration'; $this->runMigrateControllerAction('create', [$migrationName]); @@ -231,7 +231,7 @@ CODE; $this->assertStringContainsString($migrationName, basename($files[0]), 'Wrong migration name!'); } - public function testUp() + public function testUp(): void { $this->createMigration('test_up1'); $this->createMigration('test_up2'); @@ -245,7 +245,7 @@ CODE; /** * @depends testUp */ - public function testUpCount() + public function testUpCount(): void { $this->createMigration('test_down1'); $this->createMigration('test_down2'); @@ -259,7 +259,7 @@ CODE; /** * @depends testUp */ - public function testDownCount() + public function testDownCount(): void { $this->createMigration('test_down_count1'); $this->createMigration('test_down_count2'); @@ -275,7 +275,7 @@ CODE; /** * @depends testDownCount */ - public function testDownAll() + public function testDownAll(): void { $this->createMigration('test_down_all1'); $this->createMigration('test_down_all2'); @@ -291,7 +291,7 @@ CODE; /** * @depends testUp */ - public function testHistory() + public function testHistory(): void { $output = $this->runMigrateControllerAction('history'); $this->assertStringContainsString('No migration', $output); @@ -310,7 +310,7 @@ CODE; /** * @depends testUp */ - public function testNew() + public function testNew(): void { $this->createMigration('test_new1'); @@ -326,7 +326,7 @@ CODE; $this->assertStringNotContainsString('_test_new1', $output); } - public function testMark() + public function testMark(): void { $version = '010101_000001'; $this->createMigration('test_mark1', $version); @@ -337,7 +337,7 @@ CODE; $this->assertMigrationHistory(['m*_base', 'm*_test_mark1']); } - public function testMarkBase() + public function testMarkBase(): void { $version = '010101_000001'; $this->createMigration('test_mark1', $version); @@ -351,7 +351,7 @@ CODE; $this->assertMigrationHistory(['m*_base']); } - public function testTo() + public function testTo(): void { $version = '020202_000001'; $this->createMigration('to1', $version); @@ -365,7 +365,7 @@ CODE; /** * @depends testUp */ - public function testRedo() + public function testRedo(): void { $this->createMigration('test_redo1'); $this->runMigrateControllerAction('up'); @@ -382,7 +382,7 @@ CODE; /** * @depends testCreate */ - public function testNamespaceCreate() + public function testNamespaceCreate(): void { // default namespace apply : $migrationName = 'testDefaultNamespace'; @@ -424,7 +424,7 @@ CODE; /** * @depends testUp */ - public function testNamespaceUp() + public function testNamespaceUp(): void { $this->createNamespaceMigration('nsTest1'); $this->createNamespaceMigration('nsTest2'); @@ -446,7 +446,7 @@ CODE; * @depends testNamespaceUp * @depends testDownCount */ - public function testNamespaceDownCount() + public function testNamespaceDownCount(): void { $this->createNamespaceMigration('down1'); $this->createNamespaceMigration('down2'); @@ -470,7 +470,7 @@ CODE; * @depends testNamespaceUp * @depends testHistory */ - public function testNamespaceHistory() + public function testNamespaceHistory(): void { $controllerConfig = [ 'migrationPath' => null, @@ -494,7 +494,7 @@ CODE; /** * @depends testMark */ - public function testNamespaceMark() + public function testNamespaceMark(): void { $controllerConfig = [ 'migrationPath' => null, @@ -513,7 +513,7 @@ CODE; /** * @depends testTo */ - public function testNamespaceTo() + public function testNamespaceTo(): void { $controllerConfig = [ 'migrationPath' => null, @@ -532,7 +532,7 @@ CODE; /** * Test migration with using multiple migration paths and namespaces. */ - public function testCombinedMigrationProcess() + public function testCombinedMigrationProcess(): void { FileHelper::createDirectory(Yii::getAlias('@yiiunit/runtime/app_migrations')); FileHelper::createDirectory(Yii::getAlias('@yiiunit/runtime/extension_migrations')); diff --git a/tests/framework/console/controllers/PHPMessageControllerTest.php b/tests/framework/console/controllers/PHPMessageControllerTest.php index f67d464296..9551eecce2 100644 --- a/tests/framework/console/controllers/PHPMessageControllerTest.php +++ b/tests/framework/console/controllers/PHPMessageControllerTest.php @@ -99,7 +99,7 @@ class PHPMessageControllerTest extends BaseMessageControllerTest // By default phpunit runs inherited test after inline tests, so `testCreateTranslation()` would be run after // `testCustomFileHeaderAndDocBlock()` (that would break `@depends` annotation). This ensures that // `testCreateTranslation() will be run before `testCustomFileHeaderAndDocBlock()`. - public function testCreateTranslation() + public function testCreateTranslation(): void { parent::testCreateTranslation(); } @@ -107,7 +107,7 @@ class PHPMessageControllerTest extends BaseMessageControllerTest /** * @depends testCreateTranslation */ - public function testCustomFileHeaderAndDocBlock() + public function testCustomFileHeaderAndDocBlock(): void { $category = 'test_headers_category'; $message = 'test message'; @@ -148,7 +148,7 @@ class PHPMessageControllerTest extends BaseMessageControllerTest /** * @dataProvider messageFileCategoriesDataProvider */ - public function testRemoveUnusedBehavior($category, $isUnused, $removeUnused, $isExpectedToExist) + public function testRemoveUnusedBehavior($category, $isUnused, $removeUnused, $isExpectedToExist): void { $this->saveMessages(['test message' => 'test translation'], $category); $filePath = $this->getMessageFilePath($category); diff --git a/tests/framework/console/controllers/ServeControllerTest.php b/tests/framework/console/controllers/ServeControllerTest.php index 1c6eb7b973..a57a195ba9 100644 --- a/tests/framework/console/controllers/ServeControllerTest.php +++ b/tests/framework/console/controllers/ServeControllerTest.php @@ -25,7 +25,7 @@ class ServeControllerTest extends TestCase $this->mockApplication(); } - public function testAddressTaken() + public function testAddressTaken(): void { $docroot = __DIR__ . '/stub'; @@ -50,7 +50,7 @@ class ServeControllerTest extends TestCase $this->assertStringContainsString('http://localhost:8080 is taken by another process.', $result); } - public function testDefaultValues() + public function testDefaultValues(): void { $docroot = __DIR__ . '/stub'; @@ -76,7 +76,7 @@ class ServeControllerTest extends TestCase $this->assertStringContainsString('Quit the server with CTRL-C or COMMAND-C.', $result); } - public function testDoocRootWithNoExistValue() + public function testDoocRootWithNoExistValue(): void { $docroot = '/not/exist/path'; @@ -99,7 +99,7 @@ class ServeControllerTest extends TestCase $this->assertStringContainsString("Document root \"{$docroot}\" does not exist.", $result); } - public function testWithRouterNoExistValue() + public function testWithRouterNoExistValue(): void { $docroot = __DIR__ . '/stub'; $router = '/not/exist/path'; @@ -125,7 +125,7 @@ class ServeControllerTest extends TestCase $this->assertStringContainsString("Routing file \"$router\" does not exist.", $result); } - public function testWithRouterValue() + public function testWithRouterValue(): void { $docroot = __DIR__ . '/stub'; $router = __DIR__ . '/stub/index.php'; diff --git a/tests/framework/console/controllers/SilencedCacheController.php b/tests/framework/console/controllers/SilencedCacheController.php index 659e324048..dbf05c1ca4 100644 --- a/tests/framework/console/controllers/SilencedCacheController.php +++ b/tests/framework/console/controllers/SilencedCacheController.php @@ -18,7 +18,7 @@ class SilencedCacheController extends CacheController /** * {@inheritdoc} */ - public function stdout($string) + public function stdout($string): void { // do nothing } diff --git a/tests/framework/console/controllers/StdOutBufferControllerTrait.php b/tests/framework/console/controllers/StdOutBufferControllerTrait.php index 90593ef01f..92ca9ca0ef 100644 --- a/tests/framework/console/controllers/StdOutBufferControllerTrait.php +++ b/tests/framework/console/controllers/StdOutBufferControllerTrait.php @@ -19,7 +19,7 @@ trait StdOutBufferControllerTrait */ private $stdOutBuffer = ''; - public function stdout($string) + public function stdout($string): void { $this->stdOutBuffer .= $string; } diff --git a/tests/framework/console/widgets/TableTest.php b/tests/framework/console/widgets/TableTest.php index 1889521cda..431f1afcf7 100644 --- a/tests/framework/console/widgets/TableTest.php +++ b/tests/framework/console/widgets/TableTest.php @@ -46,7 +46,7 @@ class TableTest extends TestCase /** * @dataProvider getTableData */ - public function testTable($headers, $rows) + public function testTable($headers, $rows): void { $table = new Table(); @@ -110,7 +110,7 @@ EXPECTED; /** * @dataProvider getMultiLineTableData */ - public function testMultiLineTable($headers, $rows) + public function testMultiLineTable($headers, $rows): void { $table = new Table(); @@ -161,7 +161,7 @@ EXPECTED; /** * @dataProvider getNumericTableData */ - public function testNumericTable($headers, $rows) + public function testNumericTable($headers, $rows): void { $table = new Table(); @@ -184,7 +184,7 @@ EXPECTED; $this->assertEqualsWithoutLE($expected, $tableContent); } - public function testTableWithFullwidthChars() + public function testTableWithFullwidthChars(): void { $table = new Table(); @@ -211,7 +211,7 @@ EXPECTED; ); } - public function testLists() + public function testLists(): void { $table = new Table(); @@ -238,7 +238,7 @@ EXPECTED; ); } - public function testListPrefix() + public function testListPrefix(): void { $table = new Table(); @@ -264,7 +264,7 @@ EXPECTED; ); } - public function testLongerListPrefix() + public function testLongerListPrefix(): void { $table = new Table(); @@ -295,7 +295,7 @@ EXPECTED; ); } - public function testCustomChars() + public function testCustomChars(): void { $table = new Table(); @@ -336,7 +336,7 @@ EXPECTED; ); } - public function testTableWidgetSyntax() + public function testTableWidgetSyntax(): void { $expected = <<<'EXPECTED' ╔═══════════════╤═══════════════╤═══════════════╗ @@ -362,7 +362,7 @@ EXPECTED; ); } - public function testShortRow() + public function testShortRow(): void { $table = new Table(); @@ -396,7 +396,7 @@ EXPECTED; ); } - public function testEmptyRow() + public function testEmptyRow(): void { $table = new Table(); @@ -421,7 +421,7 @@ EXPECTED; ); } - public function testEmptyHeaders() + public function testEmptyHeaders(): void { $table = new Table(); @@ -443,7 +443,7 @@ EXPECTED; ); } - public function testEmptyTable() + public function testEmptyTable(): void { $table = new Table(); @@ -461,7 +461,7 @@ EXPECTED; ); } - public function testEmptyAndZeroTableCell() + public function testEmptyAndZeroTableCell(): void { $table = new Table(); @@ -489,7 +489,7 @@ EXPECTED; ); } - public function testColorizedInput() + public function testColorizedInput(): void { $table = new Table(); @@ -518,7 +518,7 @@ EXPECTED; ); } - public function testColorizedInputStripsANSIMarkersInternally() + public function testColorizedInputStripsANSIMarkersInternally(): void { $table = new Table(); @@ -539,7 +539,7 @@ EXPECTED; $this->assertEquals(8 + 2, $columnWidths[2]); } - public function testCalculateRowHeightShouldNotThrowDivisionByZeroException() + public function testCalculateRowHeightShouldNotThrowDivisionByZeroException(): void { $rows = [ ['XXXXXX', 'XXXXXXXXXXXXXXXXXXXX', '', '', 'XXXXXXXXXXXXXXXXXX', 'X', 'XXX'], @@ -554,7 +554,7 @@ EXPECTED; $this->assertEqualsWithoutLE($table, $table); } - public function testLineBreakTableCell() + public function testLineBreakTableCell(): void { $table = new Table(); @@ -589,7 +589,7 @@ EXPECTED; ); } - public function testColorizedLineBreakTableCell() + public function testColorizedLineBreakTableCell(): void { $table = new Table(); @@ -642,7 +642,7 @@ EXPECTED; * @param $smallString * @dataProvider dataMinimumWidth */ - public function testMinimumWidth($smallString) + public function testMinimumWidth($smallString): void { $bigString = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; @@ -669,7 +669,7 @@ EXPECTED; ]; } - public function testTableWithAnsiFormat() + public function testTableWithAnsiFormat(): void { $table = new Table(); diff --git a/tests/framework/data/ActiveDataFilterTest.php b/tests/framework/data/ActiveDataFilterTest.php index f710d5b080..57b96a6ab6 100644 --- a/tests/framework/data/ActiveDataFilterTest.php +++ b/tests/framework/data/ActiveDataFilterTest.php @@ -167,7 +167,7 @@ class ActiveDataFilterTest extends TestCase * @param array $filter * @param array $expectedResult */ - public function testBuild($filter, $expectedResult) + public function testBuild($filter, $expectedResult): void { $builder = new ActiveDataFilter(); $searchModel = (new DynamicModel(['name' => null, 'number' => null, 'price' => null, 'tags' => null])) @@ -186,7 +186,7 @@ class ActiveDataFilterTest extends TestCase /** * @depends testBuild */ - public function testBuildCallback() + public function testBuildCallback(): void { $builder = new ActiveDataFilter(); $searchModel = (new DynamicModel(['name' => null])) diff --git a/tests/framework/data/ActiveDataProviderCloningTest.php b/tests/framework/data/ActiveDataProviderCloningTest.php index ad2f67e685..c40e50ffdc 100644 --- a/tests/framework/data/ActiveDataProviderCloningTest.php +++ b/tests/framework/data/ActiveDataProviderCloningTest.php @@ -14,7 +14,7 @@ use yiiunit\TestCase; class ActiveDataProviderCloningTest extends TestCase { - public function testClone() + public function testClone(): void { $queryFirst = new Query(); diff --git a/tests/framework/data/ActiveDataProviderTest.php b/tests/framework/data/ActiveDataProviderTest.php index a4018713a2..bff2d173bf 100644 --- a/tests/framework/data/ActiveDataProviderTest.php +++ b/tests/framework/data/ActiveDataProviderTest.php @@ -33,7 +33,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase ActiveRecord::$db = $this->getConnection(); } - public function testActiveQuery() + public function testActiveQuery(): void { $provider = new ActiveDataProvider([ 'query' => Order::find()->orderBy('id'), @@ -55,7 +55,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase $this->assertCount(2, $orders); } - public function testActiveRelation() + public function testActiveRelation(): void { /** @var Customer $customer */ $customer = Customer::findOne(2); @@ -78,7 +78,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase $this->assertCount(1, $orders); } - public function testActiveRelationVia() + public function testActiveRelationVia(): void { /** @var Order $order */ $order = Order::findOne(2); @@ -102,7 +102,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase $this->assertCount(2, $items); } - public function testActiveRelationViaTable() + public function testActiveRelationViaTable(): void { /** @var Order $order */ $order = Order::findOne(1); @@ -124,7 +124,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase $this->assertCount(1, $items); } - public function testQuery() + public function testQuery(): void { $query = new Query(); $provider = new ActiveDataProvider([ @@ -148,7 +148,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase $this->assertCount(2, $orders); } - public function testRefresh() + public function testRefresh(): void { $query = new Query(); $provider = new ActiveDataProvider([ @@ -163,7 +163,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase $this->assertCount(2, $provider->getModels()); } - public function testPaginationBeforeModels() + public function testPaginationBeforeModels(): void { $query = new Query(); $provider = new ActiveDataProvider([ @@ -181,7 +181,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase $this->assertCount(2, $provider->getModels()); } - public function testDoesNotPerformQueryWhenHasNoModels() + public function testDoesNotPerformQueryWhenHasNoModels(): void { $query = new UnqueryableQueryMock(); $provider = new ActiveDataProvider([ diff --git a/tests/framework/data/ArrayDataProviderTest.php b/tests/framework/data/ArrayDataProviderTest.php index 5347014a07..3c747a5486 100644 --- a/tests/framework/data/ArrayDataProviderTest.php +++ b/tests/framework/data/ArrayDataProviderTest.php @@ -22,7 +22,7 @@ class ArrayDataProviderTest extends TestCase $this->mockApplication(); } - public function testGetModels() + public function testGetModels(): void { $simpleArray = [ ['name' => 'zero'], @@ -32,7 +32,7 @@ class ArrayDataProviderTest extends TestCase $this->assertEquals($simpleArray, $dataProvider->getModels()); } - public function testGetSortedData() + public function testGetSortedData(): void { $simpleArray = [['sortField' => 1], ['sortField' => 0]]; $dataProvider = new ArrayDataProvider( @@ -57,7 +57,7 @@ class ArrayDataProviderTest extends TestCase $this->assertEquals($sortedArray, $dataProvider->getModels()); } - public function testGetSortedDataByInnerArrayField() + public function testGetSortedDataByInnerArrayField(): void { $simpleArray = [ ['innerArray' => ['sortField' => 1]], @@ -88,7 +88,7 @@ class ArrayDataProviderTest extends TestCase $this->assertEquals($sortedArray, $dataProvider->getModels()); } - public function testCaseSensitiveSort() + public function testCaseSensitiveSort(): void { // source data $unsortedProjects = [ @@ -157,7 +157,7 @@ class ArrayDataProviderTest extends TestCase $this->assertEquals($sortedProjects, $dataProvider->getModels()); } - public function testGetKeys() + public function testGetKeys(): void { $pagination = ['pageSize' => 2]; @@ -205,7 +205,7 @@ class ArrayDataProviderTest extends TestCase $this->assertEquals(['key1', 'key2'], $dataProvider->getKeys()); } - public function testSortFlags() + public function testSortFlags(): void { $simpleArray = [['sortField' => 1], ['sortField' => 2], ['sortField' => 11]]; $dataProvider = new ArrayDataProvider( diff --git a/tests/framework/data/BaseDataProviderTest.php b/tests/framework/data/BaseDataProviderTest.php index 774844cc82..06ba88b20d 100644 --- a/tests/framework/data/BaseDataProviderTest.php +++ b/tests/framework/data/BaseDataProviderTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\data; +use ReflectionClass; use yii\data\BaseDataProvider; use yiiunit\TestCase; @@ -16,9 +17,9 @@ use yiiunit\TestCase; */ class BaseDataProviderTest extends TestCase { - public function testGenerateId() + public function testGenerateId(): void { - $rc = new \ReflectionClass(BaseDataProvider::className()); + $rc = new ReflectionClass(BaseDataProvider::className()); $rp = $rc->getProperty('counter'); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible diff --git a/tests/framework/data/DataFilterTest.php b/tests/framework/data/DataFilterTest.php index 4c02569a2b..ba82ca2d98 100644 --- a/tests/framework/data/DataFilterTest.php +++ b/tests/framework/data/DataFilterTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\data; +use stdClass; use yii\base\DynamicModel; use yii\data\DataFilter; use yiiunit\data\base\Singer; @@ -27,7 +28,7 @@ class DataFilterTest extends TestCase // Tests : - public function testSetupSearchModel() + public function testSetupSearchModel(): void { $builder = new DataFilter(); @@ -56,10 +57,10 @@ class DataFilterTest extends TestCase $this->assertTrue($model instanceof DynamicModel); $this->expectException('yii\base\InvalidConfigException'); - $builder->setSearchModel(new \stdClass()); + $builder->setSearchModel(new stdClass()); } - public function testLoad() + public function testLoad(): void { $filterValue = [ 'name' => 'value', @@ -263,7 +264,7 @@ class DataFilterTest extends TestCase * @param bool $expectedResult * @param array $expectedErrors */ - public function testValidate($filter, $expectedResult, $expectedErrors) + public function testValidate($filter, $expectedResult, $expectedErrors): void { $builder = new DataFilter(); $searchModel = (new DynamicModel([ @@ -420,7 +421,7 @@ class DataFilterTest extends TestCase * @param array $filter * @param array $expectedResult */ - public function testNormalize($filter, $expectedResult) + public function testNormalize($filter, $expectedResult): void { $builder = new DataFilter(); $searchModel = (new DynamicModel([ @@ -449,7 +450,7 @@ class DataFilterTest extends TestCase $this->assertEquals($expectedResult, $builder->normalize(false)); } - public function testNormalizeNonDefaultNull() + public function testNormalizeNonDefaultNull(): void { $builder = new DataFilter(); $builder->nullValue = 'abcde'; @@ -458,7 +459,7 @@ class DataFilterTest extends TestCase $this->assertEquals(['name' => null], $builder->normalize(false)); } - public function testSetupErrorMessages() + public function testSetupErrorMessages(): void { $builder = new DataFilter(); $builder->setErrorMessages([ diff --git a/tests/framework/data/PaginationTest.php b/tests/framework/data/PaginationTest.php index 9c71cacce1..bc19ce165e 100644 --- a/tests/framework/data/PaginationTest.php +++ b/tests/framework/data/PaginationTest.php @@ -79,7 +79,7 @@ class PaginationTest extends TestCase * @param array $params * @param bool $absolute */ - public function testCreateUrl($page, $pageSize, $expectedUrl, $params, $absolute = false) + public function testCreateUrl($page, $pageSize, $expectedUrl, $params, $absolute = false): void { $pagination = new Pagination(); $pagination->route = 'item/list'; @@ -90,7 +90,7 @@ class PaginationTest extends TestCase /** * @depends testCreateUrl */ - public function testForcePageParam() + public function testForcePageParam(): void { $pagination = new Pagination(); $pagination->route = 'item/list'; @@ -102,7 +102,7 @@ class PaginationTest extends TestCase $this->assertEquals('/index.php?r=item%2Flist', $pagination->createUrl(0)); } - public function testValidatePage() + public function testValidatePage(): void { $pagination = new Pagination(); $pagination->validatePage = true; @@ -139,7 +139,7 @@ class PaginationTest extends TestCase * @param int $totalCount * @param int $pageCount */ - public function testPageCount($pageSize, $totalCount, $pageCount) + public function testPageCount($pageSize, $totalCount, $pageCount): void { $pagination = new Pagination(); $pagination->setPageSize($pageSize); @@ -148,7 +148,7 @@ class PaginationTest extends TestCase $this->assertEquals($pageCount, $pagination->getPageCount()); } - public function testGetDefaultPage() + public function testGetDefaultPage(): void { $this->assertEquals(0, (new Pagination())->getPage()); } @@ -179,7 +179,7 @@ class PaginationTest extends TestCase * @param int $totalCount * @param int $page */ - public function testSetPage($value, $validate, $totalCount, $page) + public function testSetPage($value, $validate, $totalCount, $page): void { $pagination = new Pagination(); $pagination->totalCount = $totalCount; @@ -207,7 +207,7 @@ class PaginationTest extends TestCase * @param array|bool $pageSizeLimit * @param int $pageSize */ - public function testGetPageSize($pageSizeLimit, $pageSize) + public function testGetPageSize($pageSizeLimit, $pageSize): void { $pagination = new Pagination(); $pagination->pageSizeLimit = $pageSizeLimit; @@ -241,7 +241,7 @@ class PaginationTest extends TestCase * @param array|false $pageSizeLimit * @param int $pageSize */ - public function testSetPageSize($value, $validate, $pageSizeLimit, $pageSize) + public function testSetPageSize($value, $validate, $pageSizeLimit, $pageSize): void { $pagination = new Pagination(); $pagination->pageSizeLimit = $pageSizeLimit; @@ -268,7 +268,7 @@ class PaginationTest extends TestCase * @param int $page * @param int $offset */ - public function testGetOffset($pageSize, $page, $offset) + public function testGetOffset($pageSize, $page, $offset): void { $pagination = new Pagination(); $pagination->setPageSize($pageSize); @@ -292,7 +292,7 @@ class PaginationTest extends TestCase * @param int $pageSize * @param int $limit */ - public function testGetLimit($pageSize, $limit) + public function testGetLimit($pageSize, $limit): void { $pagination = new Pagination(); $pagination->setPageSize($pageSize); @@ -390,7 +390,7 @@ class PaginationTest extends TestCase * @param string|null $prev * @param string|null $next */ - public function testGetLinks($page, $pageSize, $totalCount, $self, $first, $last, $prev, $next) + public function testGetLinks($page, $pageSize, $totalCount, $self, $first, $last, $prev, $next): void { $pagination = new Pagination(); $pagination->totalCount = $totalCount; diff --git a/tests/framework/data/SortTest.php b/tests/framework/data/SortTest.php index 5b0a510f46..dc70179c42 100644 --- a/tests/framework/data/SortTest.php +++ b/tests/framework/data/SortTest.php @@ -26,7 +26,7 @@ class SortTest extends TestCase $this->mockApplication(); } - public function testGetOrders() + public function testGetOrders(): void { $sort = new Sort([ 'attributes' => [ @@ -54,7 +54,7 @@ class SortTest extends TestCase $this->assertEquals(SORT_ASC, $orders['age']); } - public function testGetAttributeOrders() + public function testGetAttributeOrders(): void { $sort = new Sort([ 'attributes' => [ @@ -81,7 +81,7 @@ class SortTest extends TestCase $this->assertEquals(SORT_ASC, $orders['age']); } - public function testGetAttributeOrder() + public function testGetAttributeOrder(): void { $sort = new Sort([ 'attributes' => [ @@ -102,7 +102,7 @@ class SortTest extends TestCase $this->assertNull($sort->getAttributeOrder('xyz')); } - public function testSetAttributeOrders() + public function testSetAttributeOrders(): void { $sort = new Sort([ 'attributes' => [ @@ -138,7 +138,7 @@ class SortTest extends TestCase $this->assertEquals($orders, $sort->getAttributeOrders()); } - public function testCreateSortParam() + public function testCreateSortParam(): void { $sort = new Sort([ 'attributes' => [ @@ -181,7 +181,7 @@ class SortTest extends TestCase $this->assertEquals('age', $sort->createSortParam('name')); } - public function testCreateUrl() + public function testCreateUrl(): void { $manager = new UrlManager([ 'baseUrl' => '/', @@ -222,7 +222,7 @@ class SortTest extends TestCase /** * @dataProvider providerForLinkWithParams */ - public function testLinkWithParams($enableMultiSort, $defaultOrder, $link) + public function testLinkWithParams($enableMultiSort, $defaultOrder, $link): void { $this->mockApplication(); $manager = new UrlManager([ @@ -263,7 +263,7 @@ class SortTest extends TestCase /** * @dataProvider providerForLinkWithParamsAndPassedButEmptySort */ - public function testLinkWithParamsAndPassedButEmptySort($defaultOrder) + public function testLinkWithParamsAndPassedButEmptySort($defaultOrder): void { $this->mockApplication(); $manager = new UrlManager([ @@ -310,7 +310,7 @@ class SortTest extends TestCase /** * @dataProvider providerForLinkWithoutParams */ - public function testLinkWithoutParams($enableMultiSort, $defaultOrder, $link) + public function testLinkWithoutParams($enableMultiSort, $defaultOrder, $link): void { $this->mockApplication(); $manager = new UrlManager([ @@ -336,7 +336,7 @@ class SortTest extends TestCase $this->assertEquals($link, $sort->link('age')); } - public function testParseSortParam() + public function testParseSortParam(): void { $sort = new CustomSort([ 'attributes' => [ @@ -359,7 +359,7 @@ class SortTest extends TestCase /** * @see https://github.com/yiisoft/yii2/pull/13260 */ - public function testGetExpressionOrders() + public function testGetExpressionOrders(): void { $sort = new Sort([ 'attributes' => [ diff --git a/tests/framework/data/SqlDataProviderTest.php b/tests/framework/data/SqlDataProviderTest.php index 9af783bef8..e997304e64 100644 --- a/tests/framework/data/SqlDataProviderTest.php +++ b/tests/framework/data/SqlDataProviderTest.php @@ -18,7 +18,7 @@ class SqlDataProviderTest extends DatabaseTestCase { protected $driverName = 'sqlite'; - public function testGetModels() + public function testGetModels(): void { $dataProvider = new SqlDataProvider([ 'sql' => 'select * from `customer`', @@ -27,7 +27,7 @@ class SqlDataProviderTest extends DatabaseTestCase $this->assertCount(3, $dataProvider->getModels()); } - public function testTotalCount() + public function testTotalCount(): void { $dataProvider = new SqlDataProvider([ 'sql' => 'select * from `customer`', @@ -36,7 +36,7 @@ class SqlDataProviderTest extends DatabaseTestCase $this->assertEquals(3, $dataProvider->getTotalCount()); } - public function testTotalCountWithParams() + public function testTotalCountWithParams(): void { $dataProvider = new SqlDataProvider([ 'sql' => 'select * from `customer` where id > :minimum', @@ -66,7 +66,7 @@ class SqlDataProviderTest extends DatabaseTestCase * @dataProvider providerForOrderByColumn * @see https://github.com/yiisoft/yii2/issues/18552 */ - public function testRemovingOrderBy($column) + public function testRemovingOrderBy($column): void { $dataProvider = new SqlDataProvider([ 'sql' => 'select * from `customer` order by ' . $column . ' desc', diff --git a/tests/framework/db/ActiveQueryModelConnectionTest.php b/tests/framework/db/ActiveQueryModelConnectionTest.php index 4adb9d8abb..e8a220c427 100644 --- a/tests/framework/db/ActiveQueryModelConnectionTest.php +++ b/tests/framework/db/ActiveQueryModelConnectionTest.php @@ -32,7 +32,7 @@ class ActiveQueryModelConnectionTest extends TestCase ActiveRecord::$db = $this->modelConnection; } - private function prepareConnectionMock($connection) + private function prepareConnectionMock($connection): void { $command = $this->getMockBuilder('yii\db\Command')->getMock(); $command->method('queryOne')->willReturn(false); @@ -41,7 +41,7 @@ class ActiveQueryModelConnectionTest extends TestCase $connection->expects($this->once())->method('getQueryBuilder')->willReturn($builder); } - public function testEnsureModelConnectionForOne() + public function testEnsureModelConnectionForOne(): void { $this->globalConnection->expects($this->never())->method('getQueryBuilder'); $this->prepareConnectionMock($this->modelConnection); @@ -50,7 +50,7 @@ class ActiveQueryModelConnectionTest extends TestCase $query->one(); } - public function testEnsureGlobalConnectionForOne() + public function testEnsureGlobalConnectionForOne(): void { $this->modelConnection->expects($this->never())->method('getQueryBuilder'); $this->prepareConnectionMock($this->globalConnection); @@ -59,7 +59,7 @@ class ActiveQueryModelConnectionTest extends TestCase $query->one(); } - public function testEnsureModelConnectionForAll() + public function testEnsureModelConnectionForAll(): void { $this->globalConnection->expects($this->never())->method('getQueryBuilder'); $this->prepareConnectionMock($this->modelConnection); @@ -68,7 +68,7 @@ class ActiveQueryModelConnectionTest extends TestCase $query->all(); } - public function testEnsureGlobalConnectionForAll() + public function testEnsureGlobalConnectionForAll(): void { $this->modelConnection->expects($this->never())->method('getQueryBuilder'); $this->prepareConnectionMock($this->globalConnection); diff --git a/tests/framework/db/ActiveQueryTest.php b/tests/framework/db/ActiveQueryTest.php index 6fb6b575a9..e7969ad73b 100644 --- a/tests/framework/db/ActiveQueryTest.php +++ b/tests/framework/db/ActiveQueryTest.php @@ -31,7 +31,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase ActiveRecord::$db = $this->getConnection(); } - public function testConstructor() + public function testConstructor(): void { $config = [ 'on' => ['a' => 'b'], @@ -43,10 +43,10 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertEquals($query->joinWith, $config['joinWith']); } - public function testTriggerInitEvent() + public function testTriggerInitEvent(): void { $where = '1==1'; - $callback = function (\yii\base\Event $event) use ($where) { + $callback = function (Event $event) use ($where) { $event->sender->where = $where; }; Event::on(ActiveQuery::className(), ActiveQuery::EVENT_INIT, $callback); @@ -58,7 +58,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for internal logic of prepare() */ - public function testPrepare() + public function testPrepare(): void { $query = new ActiveQuery(Customer::className()); $builder = new QueryBuilder(new Connection()); @@ -66,7 +66,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertInstanceOf('yii\db\Query', $result); } - public function testPopulate_EmptyRows() + public function testPopulate_EmptyRows(): void { $query = new ActiveQuery(Customer::className()); $rows = []; @@ -77,7 +77,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for internal logic of populate() */ - public function testPopulate_FilledRows() + public function testPopulate_FilledRows(): void { $query = new ActiveQuery(Customer::className()); $rows = $query->all(); @@ -88,7 +88,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for internal logic of one() */ - public function testOne() + public function testOne(): void { $query = new ActiveQuery(Customer::className()); $result = $query->one(); @@ -98,7 +98,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo test internal logic of createCommand() */ - public function testCreateCommand() + public function testCreateCommand(): void { $query = new ActiveQuery(Customer::className()); $result = $query->createCommand(); @@ -108,7 +108,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for internal logic of queryScalar() */ - public function testQueryScalar() + public function testQueryScalar(): void { $query = new ActiveQuery(Customer::className()); $result = $this->invokeMethod($query, 'queryScalar', ['name', null]); @@ -118,7 +118,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for internal logic of joinWith() */ - public function testJoinWith() + public function testJoinWith(): void { $query = new ActiveQuery(Customer::className()); $result = $query->joinWith('profile'); @@ -130,7 +130,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for internal logic of innerJoinWith() */ - public function testInnerJoinWith() + public function testInnerJoinWith(): void { $query = new ActiveQuery(Customer::className()); $result = $query->innerJoinWith('profile'); @@ -139,7 +139,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase ], $result->joinWith); } - public function testBuildJoinWithRemoveDuplicateJoinByTableName() + public function testBuildJoinWithRemoveDuplicateJoinByTableName(): void { $query = new ActiveQuery(Customer::className()); $query->innerJoinWith('orders') @@ -162,14 +162,14 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for the regex inside getQueryTableName */ - public function testGetQueryTableName_from_not_set() + public function testGetQueryTableName_from_not_set(): void { $query = new ActiveQuery(Customer::className()); $result = $this->invokeMethod($query, 'getTableNameAndAlias'); $this->assertEquals(['customer', 'customer'], $result); } - public function testGetQueryTableName_from_set() + public function testGetQueryTableName_from_set(): void { $options = ['from' => ['alias' => 'customer']]; $query = new ActiveQuery(Customer::className(), $options); @@ -177,7 +177,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertEquals(['customer', 'alias'], $result); } - public function testOnCondition() + public function testOnCondition(): void { $query = new ActiveQuery(Customer::className()); $on = ['active' => true]; @@ -187,7 +187,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertEquals($params, $result->params); } - public function testAndOnCondition_on_not_set() + public function testAndOnCondition_on_not_set(): void { $query = new ActiveQuery(Customer::className()); $on = ['active' => true]; @@ -197,7 +197,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertEquals($params, $result->params); } - public function testAndOnCondition_on_set() + public function testAndOnCondition_on_set(): void { $onOld = ['active' => true]; $query = new ActiveQuery(Customer::className()); @@ -210,7 +210,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertEquals($params, $result->params); } - public function testOrOnCondition_on_not_set() + public function testOrOnCondition_on_not_set(): void { $query = new ActiveQuery(Customer::className()); $on = ['active' => true]; @@ -220,7 +220,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertEquals($params, $result->params); } - public function testOrOnCondition_on_set() + public function testOrOnCondition_on_set(): void { $onOld = ['active' => true]; $query = new ActiveQuery(Customer::className()); @@ -236,7 +236,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase /** * @todo tests for internal logic of viaTable() */ - public function testViaTable() + public function testViaTable(): void { $query = new ActiveQuery(Customer::className(), ['primaryModel' => new Order()]); $result = $query->viaTable(Profile::className(), ['id' => 'item_id']); @@ -244,7 +244,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertInstanceOf('yii\db\ActiveQuery', $result->via); } - public function testAlias_not_set() + public function testAlias_not_set(): void { $query = new ActiveQuery(Customer::className()); $result = $query->alias('alias'); @@ -252,7 +252,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $this->assertEquals(['alias' => 'customer'], $result->from); } - public function testAlias_yet_set() + public function testAlias_yet_set(): void { $aliasOld = ['old']; $query = new ActiveQuery(Customer::className()); @@ -267,7 +267,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase return new ActiveQuery(null); } - public function testGetTableNames_notFilledFrom() + public function testGetTableNames_notFilledFrom(): void { $query = new ActiveQuery(Profile::className()); @@ -278,7 +278,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase ], $tables); } - public function testGetTableNames_wontFillFrom() + public function testGetTableNames_wontFillFrom(): void { $query = new ActiveQuery(Profile::className()); $this->assertEquals($query->from, null); @@ -292,7 +292,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase * Issue: Plan 1 -- * Account * -- * User * Our Tests: Category 1 -- * Item * -- * Order */ - public function testDeeplyNestedTableRelationWith() + public function testDeeplyNestedTableRelationWith(): void { /** @var Category $category */ $categories = Category::find()->with('orders')->indexBy('id')->all(); diff --git a/tests/framework/db/ActiveRecordTest.php b/tests/framework/db/ActiveRecordTest.php index e8107d9ad2..173aae9b47 100644 --- a/tests/framework/db/ActiveRecordTest.php +++ b/tests/framework/db/ActiveRecordTest.php @@ -8,6 +8,9 @@ namespace yiiunit\framework\db; +use Yii; +use yii\base\InvalidArgumentException; +use yii\base\InvalidConfigException; use yii\db\ActiveQuery; use yii\db\ActiveRecordInterface; use yii\db\Query; @@ -108,7 +111,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase return OrderItemWithNullFK::className(); } - public function testCustomColumns() + public function testCustomColumns(): void { // find custom column if ($this->driverName === 'oci') { @@ -122,7 +125,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(4, $customer->status2); } - public function testStatisticalFind() + public function testStatisticalFind(): void { // find count, sum, average, min, max, scalar $this->assertEquals(3, Customer::find()->count()); @@ -134,14 +137,14 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(3, Customer::find()->select('COUNT(*)')->scalar()); } - public function testFindScalar() + public function testFindScalar(): void { // query scalar $customerName = Customer::find()->where(['[[id]]' => 2])->select('[[name]]')->scalar(); $this->assertEquals('user2', $customerName); } - public function testFindExists() + public function testFindExists(): void { $this->assertTrue(Customer::find()->where(['[[id]]' => 2])->exists()); $this->assertFalse(Customer::find()->where(['[[id]]' => 42])->exists()); @@ -149,14 +152,14 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertFalse(Customer::find()->where(['[[id]]' => 42])->select('[[name]]')->exists()); } - public function testFindColumn() + public function testFindColumn(): void { /** @var TestCase|ActiveRecordTestTrait $this */ $this->assertEquals(['user1', 'user2', 'user3'], Customer::find()->select('[[name]]')->column()); $this->assertEquals(['user3', 'user2', 'user1'], Customer::find()->orderBy(['[[name]]' => SORT_DESC])->select('[[name]]')->column()); } - public function testFindBySql() + public function testFindBySql(): void { // find one $customer = Customer::findBySql('SELECT * FROM {{customer}} ORDER BY [[id]] DESC')->one(); @@ -178,7 +181,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * * @see https://github.com/yiisoft/yii2/issues/8593 */ - public function testCountWithFindBySql() + public function testCountWithFindBySql(): void { $query = Customer::findBySql('SELECT * FROM {{customer}}'); $this->assertEquals(3, $query->count()); @@ -186,7 +189,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(1, $query->count()); } - public function testFindLazyViaTable() + public function testFindLazyViaTable(): void { /** @var Order $order */ $order = Order::findOne(1); @@ -203,7 +206,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertIsArray($order); } - public function testFindEagerViaTable() + public function testFindEagerViaTable(): void { $orders = Order::find()->with('books')->orderBy('id')->all(); $this->assertCount(3, $orders); @@ -237,7 +240,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase } // deeply nested table relation - public function testDeeplyNestedTableRelation() + public function testDeeplyNestedTableRelation(): void { /** @var Customer $customer */ $customer = Customer::findOne(1); @@ -258,7 +261,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * Issue: Plan 1 -- * Account * -- * User * Our Tests: Category 1 -- * Item * -- * Order */ - public function testDeeplyNestedTableRelation2() + public function testDeeplyNestedTableRelation2(): void { /** @var Category $category */ $category = Category::findOne(1); @@ -279,7 +282,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(2, $orders[0]->id); } - public function testStoreNull() + public function testStoreNull(): void { $record = new NullValues(); $this->assertNull($record->var1); @@ -327,7 +330,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals('', $record->stringcol); } - public function testStoreEmpty() + public function testStoreEmpty(): void { $record = new NullValues(); @@ -345,7 +348,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertSame($record->var2, $record->var3); } - public function testIsPrimaryKey() + public function testIsPrimaryKey(): void { $this->assertFalse(Customer::isPrimaryKey([])); $this->assertTrue(Customer::isPrimaryKey(['id'])); @@ -362,7 +365,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertFalse(OrderItem::isPrimaryKey(['order_id', 'item_id', 'quantity'])); } - public function testJoinWith() + public function testJoinWith(): void { // left join and eager loading $orders = Order::find()->joinWith('customer')->orderBy('customer.id DESC, order.id')->all(); @@ -567,7 +570,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateSimple() + public function testJoinWithDuplicateSimple(): void { // left join and eager loading $orders = Order::find() @@ -587,7 +590,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateCallbackFiltering() + public function testJoinWithDuplicateCallbackFiltering(): void { // inner join filtering and eager loading $orders = Order::find() @@ -607,7 +610,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateCallbackFilteringConditionsOnPrimary() + public function testJoinWithDuplicateCallbackFilteringConditionsOnPrimary(): void { // inner join filtering, eager loading, conditions on both primary and relation $orders = Order::find() @@ -625,7 +628,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateWithSubRelation() + public function testJoinWithDuplicateWithSubRelation(): void { // join with sub-relation $orders = Order::find() @@ -646,7 +649,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateTableAlias1() + public function testJoinWithDuplicateTableAlias1(): void { // join with table alias $orders = Order::find() @@ -668,7 +671,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateTableAlias2() + public function testJoinWithDuplicateTableAlias2(): void { // join with table alias $orders = Order::find() @@ -688,7 +691,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateTableAliasSubRelation() + public function testJoinWithDuplicateTableAliasSubRelation(): void { // join with table alias sub-relation $orders = Order::find() @@ -713,7 +716,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithDuplicateSubRelationCalledInsideClosure() + public function testJoinWithDuplicateSubRelationCalledInsideClosure(): void { // join with sub-relation called inside Closure $orders = Order::find() @@ -741,7 +744,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @depends testJoinWith */ - public function testJoinWithAndScope() + public function testJoinWithAndScope(): void { // hasOne inner join $customers = Customer::find()->active()->innerJoinWith('profile')->orderBy('customer.id')->all(); @@ -777,7 +780,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * * @see https://github.com/yiisoft/yii2/pull/2650 */ - public function testJoinWithVia() + public function testJoinWithVia(): void { Order::getDb()->getQueryBuilder()->separator = "\n"; $rows = Order::find()->joinWith('itemsInOrder1')->joinWith([ @@ -793,7 +796,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * * @see https://github.com/yiisoft/yii2/issues/19507 */ - public function testJoinWithEager() + public function testJoinWithEager(): void { $eagerCustomers = Customer::find()->joinWith(['items'])->all(); $eagerItemsCount = 0; @@ -825,7 +828,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * @dataProvider aliasMethodProvider * @param string $aliasMethod whether alias is specified explicitly or using the query syntax {{@tablename}} */ - public function testJoinWithAlias($aliasMethod) + public function testJoinWithAlias($aliasMethod): void { // left join and eager loading /** @var ActiveQuery $query */ @@ -1009,7 +1012,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(2, $orders[0]->items[0]->category->id); } - public function testJoinWithSameTable() + public function testJoinWithSameTable(): void { // join with the same table but different aliases // alias is defined in the relation definition @@ -1097,7 +1100,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * @see https://github.com/yiisoft/yii2/issues/10201 * @see https://github.com/yiisoft/yii2/issues/9047 */ - public function testFindCompositeRelationWithJoin() + public function testFindCompositeRelationWithJoin(): void { /** @var OrderItem $orderItem */ $orderItem = OrderItem::findOne([1, 1]); @@ -1109,7 +1112,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertInstanceOf('yiiunit\data\ar\OrderItem', $orderItemWithJoin); } - public function testFindSimpleRelationWithJoin() + public function testFindSimpleRelationWithJoin(): void { /** @var Order $order */ $order = Order::findOne(1); @@ -1143,7 +1146,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * @param string $orderTableName * @param string $orderItemTableName */ - public function testRelationWhereParams($orderTableName, $orderItemTableName) + public function testRelationWhereParams($orderTableName, $orderItemTableName): void { Order::$tableName = $orderTableName; OrderItem::$tableName = $orderItemTableName; @@ -1163,7 +1166,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase OrderItem::$tableName = null; } - public function testOutdatedRelationsAreResetForNewRecords() + public function testOutdatedRelationsAreResetForNewRecords(): void { $orderItem = new OrderItem(); $orderItem->order_id = 1; @@ -1184,7 +1187,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(2, $orderItem->item->id); } - public function testOutdatedRelationsAreResetForExistingRecords() + public function testOutdatedRelationsAreResetForExistingRecords(): void { $orderItem = OrderItem::findOne(1); $this->assertEquals(1, $orderItem->order->id); @@ -1203,7 +1206,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(1, $orderItem->item->id); } - public function testOutdatedCompositeKeyRelationsAreReset() + public function testOutdatedCompositeKeyRelationsAreReset(): void { $dossier = Dossier::findOne([ 'department_id' => 1, @@ -1231,7 +1234,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals('Will Smith', $dossier->employee->fullName); } - public function testOutdatedViaTableRelationsAreReset() + public function testOutdatedViaTableRelationsAreReset(): void { $order = Order::findOne(1); $orderItemIds = ArrayHelper::getColumn($order->items, 'id'); @@ -1254,7 +1257,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertSame([2], $orderItemIds); } - public function testAlias() + public function testAlias(): void { $query = Order::find(); $this->assertNull($query->from); @@ -1275,7 +1278,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase ], $query->from); } - public function testInverseOf() + public function testInverseOf(): void { // eager loading: find one and all $customer = Customer::find()->with('orders2')->where(['id' => 1])->one(); @@ -1330,7 +1333,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertSame($orders[1]['customer2']['orders2'][1]['id'], $orders[1]['id']); } - public function testInverseOfDynamic() + public function testInverseOfDynamic(): void { $customer = Customer::findOne(1); @@ -1356,7 +1359,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals($customer['id'], $orders2['customer2']['id']); } - public function testDefaultValues() + public function testDefaultValues(): void { $model = new Type(); $model->loadDefaultValues(); @@ -1388,7 +1391,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(['int_col2' => 1], $model->toArray()); } - public function testUnlinkAllViaTable() + public function testUnlinkAllViaTable(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -1422,7 +1425,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(5, $itemClass::find()->count()); } - public function testCastValues() + public function testCastValues(): void { $model = new Type(); $model->int_col = 123; @@ -1451,7 +1454,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertSame(false, $model->bool_col2); } - public function testIssues() + public function testIssues(): void { // https://github.com/yiisoft/yii2/issues/4938 $category = Category::findOne(2); @@ -1488,7 +1491,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(1, $model->status); } - public function testPopulateRecordCallWhenQueryingOnParentClass() + public function testPopulateRecordCallWhenQueryingOnParentClass(): void { (new Cat())->save(false); (new Dog())->save(false); @@ -1500,14 +1503,14 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals('meow', $animal->getDoes()); } - public function testSaveEmpty() + public function testSaveEmpty(): void { $record = new NullValues(); $this->assertTrue($record->save(false)); $this->assertEquals(1, $record->id); } - public function testOptimisticLock() + public function testOptimisticLock(): void { /** @var Document $record */ $record = Document::findOne(1); @@ -1522,7 +1525,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $record->save(false); } - public function testPopulateWithoutPk() + public function testPopulateWithoutPk(): void { // tests with single pk asArray $aggregation = Customer::find() @@ -1632,7 +1635,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/9006 */ - public function testBit() + public function testBit(): void { $falseBit = BitValues::findOne(1); $this->assertEquals(false, $falseBit->val); @@ -1641,7 +1644,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(true, $trueBit->val); } - public function testLinkWhenRelationIsIndexed2() + public function testLinkWhenRelationIsIndexed2(): void { $order = Order::find() ->with('orderItems2') @@ -1657,7 +1660,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertTrue(isset($order->orderItems2['3'])); } - public function testLinkWhenRelationIsIndexed3() + public function testLinkWhenRelationIsIndexed3(): void { $order = Order::find() ->with('orderItems3') @@ -1673,7 +1676,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertTrue(isset($order->orderItems3['1_3'])); } - public function testUpdateAttributes() + public function testUpdateAttributes(): void { $order = Order::findOne(1); $newTotal = 978; @@ -1691,7 +1694,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals($newTotal, $newOrder->total); } - public function testEmulateExecution() + public function testEmulateExecution(): void { $this->assertGreaterThan(0, Customer::find()->count()); @@ -1751,7 +1754,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/12213 */ - public function testUnlinkAllOnCondition() + public function testUnlinkAllOnCondition(): void { /** @var Category $categoryClass */ $categoryClass = $this->getCategoryClass(); @@ -1782,7 +1785,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/12213 */ - public function testUnlinkAllOnConditionViaTable() + public function testUnlinkAllOnConditionViaTable(): void { /** @var Order $orderClass */ $orderClass = $this->getOrderClass(); @@ -1812,7 +1815,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * https://github.com/yiisoft/yii2/pull/13891 */ - public function testIndexByAfterLoadingRelations() + public function testIndexByAfterLoadingRelations(): void { $orderClass = $this->getOrderClass(); @@ -1832,7 +1835,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * Verify that {{}} are not going to be replaced in parameters. */ - public function testNoTablenameReplacement() + public function testNoTablenameReplacement(): void { /** @var Customer $customer */ $class = $this->getCustomerClass(); @@ -1859,7 +1862,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * * @see https://github.com/yiisoft/yii2/issues/13757 */ - public function testAmbiguousColumnFindOne() + public function testAmbiguousColumnFindOne(): void { CustomerQuery::$joinWithProfile = true; $model = Customer::findOne(1); @@ -1867,7 +1870,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase CustomerQuery::$joinWithProfile = false; } - public function testFindOneByColumnName() + public function testFindOneByColumnName(): void { $model = Customer::findOne(['id' => 1]); $this->assertEquals(1, $model->id); @@ -1882,12 +1885,12 @@ abstract class ActiveRecordTest extends DatabaseTestCase * @dataProvider filterTableNamesFromAliasesProvider * @param $fromParams * @param $expectedAliases - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ - public function testFilterTableNamesFromAliases($fromParams, $expectedAliases) + public function testFilterTableNamesFromAliases($fromParams, $expectedAliases): void { $query = Customer::find()->from($fromParams); - $aliases = $this->invokeMethod(\Yii::createObject(Customer::className()), 'filterValidAliases', [$query]); + $aliases = $this->invokeMethod(Yii::createObject(Customer::className()), 'filterValidAliases', [$query]); $this->assertEquals($expectedAliases, $aliases); } @@ -1926,10 +1929,10 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @dataProvider legalValuesForFindByCondition */ - public function testLegalValuesForFindByCondition($modelClassName, $validFilter) + public function testLegalValuesForFindByCondition($modelClassName, $validFilter): void { /** @var Query $query */ - $query = $this->invokeMethod(\Yii::createObject($modelClassName), 'findByCondition', [$validFilter]); + $query = $this->invokeMethod(Yii::createObject($modelClassName), 'findByCondition', [$validFilter]); Customer::getDb()->queryBuilder->build($query); $this->assertTrue(true); @@ -1967,12 +1970,12 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @dataProvider illegalValuesForFindByCondition */ - public function testValueEscapingInFindByCondition($modelClassName, $filterWithInjection) + public function testValueEscapingInFindByCondition($modelClassName, $filterWithInjection): void { - $this->expectException(\yii\base\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageMatches('/^Key "(.+)?" is not a column name and can not be used as a filter$/'); /** @var Query $query */ - $query = $this->invokeMethod(\Yii::createObject($modelClassName), 'findByCondition', $filterWithInjection); + $query = $this->invokeMethod(Yii::createObject($modelClassName), 'findByCondition', $filterWithInjection); Customer::getDb()->queryBuilder->build($query); } @@ -1981,7 +1984,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * * @see https://github.com/yiisoft/yii2/issues/13859 */ - public function testAmbiguousColumnIndexBy() + public function testAmbiguousColumnIndexBy(): void { switch ($this->driverName) { case 'pgsql': @@ -2010,7 +2013,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * * @depends testJoinWith */ - public function testFindWithConstructors() + public function testFindWithConstructors(): void { /** @var OrderWithConstructor[] $orders */ $orders = OrderWithConstructor::find() @@ -2055,15 +2058,15 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(3, $orders); } - public function testCustomARRelation() + public function testCustomARRelation(): void { $orderItem = OrderItem::findOne(1); $this->assertInstanceOf(Order::className(), $orderItem->custom); } - public function testRefresh_querySetAlias_findRecord() + public function testRefresh_querySetAlias_findRecord(): void { - $customer = new \yiiunit\data\ar\CustomerWithAlias(); + $customer = new CustomerWithAlias(); $customer->id = 1; $customer->refresh(); @@ -2071,7 +2074,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(1, $customer->id); } - public function testResetNotSavedRelation() + public function testResetNotSavedRelation(): void { $order = new Order(); $order->customer_id = 1; @@ -2085,7 +2088,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(1, sizeof($order->orderItems)); } - public function testIssetThrowable() + public function testIssetThrowable(): void { $cat = new Cat(); $this->assertFalse(isset($cat->throwable)); @@ -2094,7 +2097,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/15482 */ - public function testEagerLoadingUsingStringIdentifiers() + public function testEagerLoadingUsingStringIdentifiers(): void { if (!in_array($this->driverName, ['mysql', 'pgsql', 'sqlite'])) { $this->markTestSkipped('This test has fixtures only for databases MySQL, PostgreSQL and SQLite.'); @@ -2118,7 +2121,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/16492 */ - public function testEagerLoadingWithTypeCastedCompositeIdentifier() + public function testEagerLoadingWithTypeCastedCompositeIdentifier(): void { $aggregation = Order::find()->joinWith('quantityOrderItems', true)->all(); foreach ($aggregation as $item) { @@ -2142,7 +2145,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * @dataProvider providerForUnlinkDelete * @see https://github.com/yiisoft/yii2/issues/17174 */ - public function testUnlinkWithViaOnCondition($delete, $count) + public function testUnlinkWithViaOnCondition($delete, $count): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -2167,7 +2170,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase ])); } - public function testVirtualRelation() + public function testVirtualRelation(): void { /** @var ActiveRecordInterface $orderClass */ $orderClass = $this->getOrderClass(); @@ -2202,7 +2205,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase * @dataProvider labelTestModelProvider * @param \yii\db\ActiveRecord $model */ - public function testGetAttributeLabel($model) + public function testGetAttributeLabel($model): void { $this->assertEquals('model3.attr1 from model2', $model->getAttributeLabel('model2.model3.attr1')); $this->assertEquals('attr2 from model3', $model->getAttributeLabel('model2.model3.attr2')); @@ -2211,7 +2214,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals($model->generateAttributeLabel($attr), $model->getAttributeLabel($attr)); } - public function testLoadRelations() + public function testLoadRelations(): void { // Test eager loading relations for multiple primary models using loadRelationsFor(). /** @var Customer[] $customers */ diff --git a/tests/framework/db/BatchQueryResultTest.php b/tests/framework/db/BatchQueryResultTest.php index 6415c7afa7..22321b987b 100644 --- a/tests/framework/db/BatchQueryResultTest.php +++ b/tests/framework/db/BatchQueryResultTest.php @@ -21,7 +21,7 @@ abstract class BatchQueryResultTest extends DatabaseTestCase ActiveRecord::$db = $this->getConnection(); } - public function testQuery() + public function testQuery(): void { $db = $this->getConnection(); @@ -86,7 +86,7 @@ abstract class BatchQueryResultTest extends DatabaseTestCase $this->assertEquals('address3', $allRows['user3']['address']); } - public function testActiveQuery() + public function testActiveQuery(): void { $db = $this->getConnection(); @@ -109,7 +109,7 @@ abstract class BatchQueryResultTest extends DatabaseTestCase $this->assertCount(0, $customers[2]->orders); } - public function testBatchWithoutDbParameter() + public function testBatchWithoutDbParameter(): void { $query = Customer::find()->orderBy('id')->limit(3); $customers = $this->getAllRowsFromBatch($query->batch(2)); @@ -119,7 +119,7 @@ abstract class BatchQueryResultTest extends DatabaseTestCase $this->assertEquals('user3', $customers[2]->name); } - public function testBatchWithIndexBy() + public function testBatchWithIndexBy(): void { $query = Customer::find()->orderBy('id')->limit(3)->indexBy('id'); $customers = $this->getAllRowsFromBatch($query->batch(2)); diff --git a/tests/framework/db/ColumnSchemaBuilderTest.php b/tests/framework/db/ColumnSchemaBuilderTest.php index 85bfd07369..28b151cc22 100644 --- a/tests/framework/db/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/ColumnSchemaBuilderTest.php @@ -55,7 +55,7 @@ abstract class ColumnSchemaBuilderTest extends DatabaseTestCase * @param int|null $length * @param mixed $calls */ - public function testCustomTypes($expected, $type, $length, $calls) + public function testCustomTypes($expected, $type, $length, $calls): void { $this->checkBuildString($expected, $type, $length, $calls); } @@ -66,7 +66,7 @@ abstract class ColumnSchemaBuilderTest extends DatabaseTestCase * @param int|null $length * @param array $calls */ - public function checkBuildString($expected, $type, $length, $calls) + public function checkBuildString($expected, $type, $length, $calls): void { $builder = $this->getColumnSchemaBuilder($type, $length); foreach ($calls as $call) { diff --git a/tests/framework/db/CommandTest.php b/tests/framework/db/CommandTest.php index 8cb4ce737a..a2254031b2 100644 --- a/tests/framework/db/CommandTest.php +++ b/tests/framework/db/CommandTest.php @@ -8,6 +8,12 @@ namespace yiiunit\framework\db; +use PDO; +use Throwable; +use yii\base\InvalidArgumentException; +use yiiunit\framework\db\enums\Status; +use yiiunit\framework\db\enums\StatusTypeString; +use yiiunit\framework\db\enums\StatusTypeInt; use ArrayObject; use yii\caching\ArrayCache; use yii\db\Connection; @@ -21,7 +27,7 @@ abstract class CommandTest extends DatabaseTestCase { protected $upsertTestCharCast = 'CAST([[address]] AS VARCHAR(255))'; - public function testConstruct() + public function testConstruct(): void { $db = $this->getConnection(false); @@ -35,7 +41,7 @@ abstract class CommandTest extends DatabaseTestCase $this->assertEquals($sql, $command->sql); } - public function testGetSetSql() + public function testGetSetSql(): void { $db = $this->getConnection(false); @@ -48,7 +54,7 @@ abstract class CommandTest extends DatabaseTestCase $this->assertEquals($sql2, $command->sql); } - public function testAutoQuoting() + public function testAutoQuoting(): void { $db = $this->getConnection(false); @@ -57,7 +63,7 @@ abstract class CommandTest extends DatabaseTestCase $this->assertEquals('SELECT `id`, `t`.`name` FROM `customer` t', $command->sql); } - public function testPrepareCancel() + public function testPrepareCancel(): void { $db = $this->getConnection(false); @@ -69,7 +75,7 @@ abstract class CommandTest extends DatabaseTestCase $this->assertNull($command->pdoStatement); } - public function testExecute() + public function testExecute(): void { $db = $this->getConnection(); @@ -86,7 +92,7 @@ abstract class CommandTest extends DatabaseTestCase $command->execute(); } - public function testQuery() + public function testQuery(): void { $db = $this->getConnection(); @@ -147,7 +153,7 @@ abstract class CommandTest extends DatabaseTestCase $command->query(); } - public function testBindParamValue() + public function testBindParamValue(): void { if (\defined('HHVM_VERSION') && $this->driverName === 'pgsql') { $this->markTestSkipped('HHVMs PgSQL implementation has some specific behavior that breaks some parts of this test.'); @@ -178,7 +184,7 @@ SQL; $command = $db->createCommand($sql); $intCol = 123; $charCol = str_repeat('abc', 33) . 'x'; // a 100 char string - $command->bindParam(':int_col', $intCol, \PDO::PARAM_INT); + $command->bindParam(':int_col', $intCol, PDO::PARAM_INT); $command->bindParam(':char_col', $charCol); if ($this->driverName === 'oci') { // can't bind floats without support from a custom PDO driver @@ -189,10 +195,10 @@ SQL; // You can create a table with a column of datatype CHAR(1) and store either “Y” or “N” in that column // to indicate TRUE or FALSE. $boolCol = '0'; - $command->bindParam(':float_col', $floatCol, \PDO::PARAM_INT); - $command->bindParam(':numeric_col', $numericCol, \PDO::PARAM_INT); + $command->bindParam(':float_col', $floatCol, PDO::PARAM_INT); + $command->bindParam(':numeric_col', $numericCol, PDO::PARAM_INT); $command->bindParam(':blob_col', $blobCol); - $command->bindParam(':bool_col', $boolCol, \PDO::PARAM_BOOL); + $command->bindParam(':bool_col', $boolCol, PDO::PARAM_BOOL); } else { $floatCol = 1.230; $numericCol = '1.23'; @@ -201,7 +207,7 @@ SQL; $command->bindParam(':float_col', $floatCol); $command->bindParam(':numeric_col', $numericCol); $command->bindParam(':blob_col', $blobCol); - $command->bindParam(':bool_col', $boolCol, \PDO::PARAM_BOOL); + $command->bindParam(':bool_col', $boolCol, PDO::PARAM_BOOL); } $this->assertEquals(1, $command->execute()); @@ -253,7 +259,7 @@ SQL; * @dataProvider paramsNonWhereProvider * @param string $sql */ - public function testBindParamsNonWhere($sql) + public function testBindParamsNonWhere($sql): void { $db = $this->getConnection(); @@ -267,7 +273,7 @@ SQL; $this->assertEquals('Params', $command->queryScalar()); } - public function testFetchMode() + public function testFetchMode(): void { $db = $this->getConnection(); @@ -280,18 +286,18 @@ SQL; // FETCH_OBJ, customized via fetchMode property $sql = 'SELECT * FROM {{customer}}'; $command = $db->createCommand($sql); - $command->fetchMode = \PDO::FETCH_OBJ; + $command->fetchMode = PDO::FETCH_OBJ; $result = $command->queryOne(); $this->assertIsObject($result); // FETCH_NUM, customized in query method $sql = 'SELECT * FROM {{customer}}'; $command = $db->createCommand($sql); - $result = $command->queryOne([], \PDO::FETCH_NUM); + $result = $command->queryOne([], PDO::FETCH_NUM); $this->assertTrue(\is_array($result) && isset($result[0])); } - public function testBatchInsert() + public function testBatchInsert(): void { $command = $this->getConnection()->createCommand(); $command->batchInsert( @@ -314,7 +320,7 @@ SQL; $this->assertEquals(0, $command->execute()); } - public function testBatchInsertWithYield() + public function testBatchInsertWithYield(): void { include __DIR__ . '/testBatchInsertWithYield.php'; } @@ -326,7 +332,7 @@ SQL; * * https://github.com/yiisoft/yii2/issues/6526 */ - public function testBatchInsertDataTypesLocale() + public function testBatchInsertDataTypesLocale(): void { $locale = setlocale(LC_NUMERIC, 0); if (false === $locale) { @@ -367,7 +373,7 @@ SQL; } catch (\Exception $e) { setlocale(LC_NUMERIC, $locale); throw $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { setlocale(LC_NUMERIC, $locale); throw $e; } @@ -426,7 +432,7 @@ SQL; * @param mixed $expected * @param array $expectedParams */ - public function testBatchInsertSQL($table, $columns, $values, $expected, array $expectedParams = []) + public function testBatchInsertSQL($table, $columns, $values, $expected, array $expectedParams = []): void { $command = $this->getConnection()->createCommand(); $command->batchInsert($table, $columns, $values); @@ -435,7 +441,7 @@ SQL; $this->assertSame($expectedParams, $command->params); } - public function testInsert() + public function testInsert(): void { $db = $this->getConnection(); $db->createCommand('DELETE FROM {{customer}}')->execute(); @@ -461,7 +467,7 @@ SQL; /** * verify that {{}} are not going to be replaced in parameters. */ - public function testNoTablenameReplacement() + public function testNoTablenameReplacement(): void { $db = $this->getConnection(); @@ -498,7 +504,7 @@ SQL; /** * Test INSERT INTO ... SELECT SQL statement. */ - public function testInsertSelect() + public function testInsertSelect(): void { $db = $this->getConnection(); $db->createCommand('DELETE FROM {{customer}}')->execute(); @@ -513,7 +519,7 @@ SQL; ] )->execute(); - $query = new \yii\db\Query(); + $query = new Query(); $query->select( [ '{{customer}}.[[email]] as name', @@ -553,7 +559,7 @@ SQL; /** * Test INSERT INTO ... SELECT SQL statement with alias syntax. */ - public function testInsertSelectAlias() + public function testInsertSelectAlias(): void { $db = $this->getConnection(); $db->createCommand('DELETE FROM {{customer}}')->execute(); @@ -568,7 +574,7 @@ SQL; ] )->execute(); - $query = new \yii\db\Query(); + $query = new Query(); $query->select( [ 'email' => '{{customer}}.[[email]]', @@ -625,15 +631,15 @@ SQL; * * @param mixed $invalidSelectColumns */ - public function testInsertSelectFailed($invalidSelectColumns) + public function testInsertSelectFailed($invalidSelectColumns): void { - $query = new \yii\db\Query(); + $query = new Query(); $query->select($invalidSelectColumns)->from('{{customer}}'); $db = $this->getConnection(); $command = $db->createCommand(); - $this->expectException(\yii\base\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected select query object with enumerated (named) parameters'); $this->expectException('yii\base\InvalidParamException'); @@ -641,7 +647,7 @@ SQL; $command->insert('{{customer}}', $query)->execute(); } - public function testInsertExpression() + public function testInsertExpression(): void { $db = $this->getConnection(); $db->createCommand('DELETE FROM {{order_with_null_fk}}')->execute(); @@ -679,7 +685,7 @@ SQL; ], $record); } - public function testsInsertQueryAsColumnValue() + public function testsInsertQueryAsColumnValue(): void { $time = time(); @@ -698,7 +704,7 @@ SQL; $orderId = $db->getLastInsertID(); } - $columnValueQuery = new \yii\db\Query(); + $columnValueQuery = new Query(); $columnValueQuery->select('created_at')->from('{{order}}')->where(['id' => $orderId]); $command = $db->createCommand(); @@ -717,7 +723,7 @@ SQL; $db->createCommand('DELETE FROM {{order}} WHERE [[id]] = ' . $orderId)->execute(); } - public function testCreateTable() + public function testCreateTable(): void { $db = $this->getConnection(); @@ -733,7 +739,7 @@ SQL; ], $records); } - public function testAlterTable() + public function testAlterTable(): void { if ($this->driverName === 'sqlite') { $this->markTestSkipped('Sqlite does not support alterTable'); @@ -758,7 +764,7 @@ SQL; ], $records); } - public function testDropTable() + public function testDropTable(): void { $db = $this->getConnection(); @@ -768,7 +774,7 @@ SQL; $this->assertNull($db->getSchema()->getTableSchema($tableName)); } - public function testTruncateTable() + public function testTruncateTable(): void { $db = $this->getConnection(); @@ -779,7 +785,7 @@ SQL; $this->assertCount(0, $rows); } - public function testRenameTable() + public function testRenameTable(): void { $db = $this->getConnection(); @@ -1026,7 +1032,7 @@ SQL; * @param array $firstData * @param array $secondData */ - public function testUpsert(array $firstData, array $secondData) + public function testUpsert(array $firstData, array $secondData): void { $db = $this->getConnection(); $this->assertEquals(0, $db->createCommand('SELECT COUNT(*) FROM {{T_upsert}}')->queryScalar()); @@ -1075,7 +1081,7 @@ SQL; } */ - public function testAddDropPrimaryKey() + public function testAddDropPrimaryKey(): void { $db = $this->getConnection(false); $tableName = 'test_pk'; @@ -1102,7 +1108,7 @@ SQL; $this->assertEquals(['int1', 'int2'], $schema->getTablePrimaryKey($tableName, true)->columnNames); } - public function testAddDropForeignKey() + public function testAddDropForeignKey(): void { $db = $this->getConnection(false); $tableName = 'test_fk'; @@ -1135,7 +1141,7 @@ SQL; $this->assertEquals(['int3', 'int4'], $schema->getTableForeignKeys($tableName, true)[0]->foreignColumnNames); } - public function testCreateDropIndex() + public function testCreateDropIndex(): void { $db = $this->getConnection(false); $tableName = 'test_idx'; @@ -1179,7 +1185,7 @@ SQL; $this->assertTrue($schema->getTableIndexes($tableName, true)[0]->isUnique); } - public function testAddDropUnique() + public function testAddDropUnique(): void { $db = $this->getConnection(false); $tableName = 'test_uq'; @@ -1206,7 +1212,7 @@ SQL; $this->assertEquals(['int1', 'int2'], $schema->getTableUniques($tableName, true)[0]->columnNames); } - public function testAddDropCheck() + public function testAddDropCheck(): void { $db = $this->getConnection(false); @@ -1237,12 +1243,12 @@ SQL; $this->assertEmpty($schema->getTableChecks($tableName, true)); } - public function testAddDropDefaultValue() + public function testAddDropDefaultValue(): void { $this->markTestSkipped($this->driverName . ' does not support adding/dropping default value constraints.'); } - public function testIntegrityViolation() + public function testIntegrityViolation(): void { $this->expectException('\yii\db\IntegrityException'); @@ -1254,7 +1260,7 @@ SQL; $command->execute(); } - public function testLastInsertId() + public function testLastInsertId(): void { $db = $this->getConnection(); @@ -1264,7 +1270,7 @@ SQL; $this->assertEquals(3, $db->getSchema()->getLastInsertID()); } - public function testQueryCache() + public function testQueryCache(): void { $db = $this->getConnection(); $db->enableQueryCache = true; @@ -1309,10 +1315,10 @@ SQL; }, 10); } - public function testColumnCase() + public function testColumnCase(): void { $db = $this->getConnection(false); - $this->assertEquals(\PDO::CASE_NATURAL, $db->slavePdo->getAttribute(\PDO::ATTR_CASE)); + $this->assertEquals(PDO::CASE_NATURAL, $db->slavePdo->getAttribute(PDO::ATTR_CASE)); $sql = 'SELECT [[customer_id]], [[total]] FROM {{order}}'; $rows = $db->createCommand($sql)->queryAll(); @@ -1320,13 +1326,13 @@ SQL; $this->assertTrue(isset($rows[0]['customer_id'])); $this->assertTrue(isset($rows[0]['total'])); - $db->slavePdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER); + $db->slavePdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); $rows = $db->createCommand($sql)->queryAll(); $this->assertTrue(isset($rows[0])); $this->assertTrue(isset($rows[0]['customer_id'])); $this->assertTrue(isset($rows[0]['total'])); - $db->slavePdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_UPPER); + $db->slavePdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); $rows = $db->createCommand($sql)->queryAll(); $this->assertTrue(isset($rows[0])); $this->assertTrue(isset($rows[0]['CUSTOMER_ID'])); @@ -1397,14 +1403,14 @@ SQL; * @param array $params * @param string $expectedRawSql */ - public function testGetRawSql($sql, array $params, $expectedRawSql) + public function testGetRawSql($sql, array $params, $expectedRawSql): void { $db = $this->getConnection(false); $command = $db->createCommand($sql, $params); $this->assertEquals($expectedRawSql, $command->getRawSql()); } - public function testAutoRefreshTableSchema() + public function testAutoRefreshTableSchema(): void { if ($this->driverName === 'sqlsrv') { // related to https://github.com/yiisoft/yii2/pull/17364 @@ -1451,7 +1457,7 @@ SQL; $this->assertNull($db->getSchema()->getTableSchema($tableName)); } - public function testTransaction() + public function testTransaction(): void { $connection = $this->getConnection(false); $this->assertNull($connection->transaction); @@ -1462,7 +1468,7 @@ SQL; $this->assertEquals(1, $connection->createCommand("SELECT COUNT(*) FROM {{profile}} WHERE [[description]] = 'command transaction'")->queryScalar()); } - public function testRetryHandler() + public function testRetryHandler(): void { $connection = $this->getConnection(false); $this->assertNull($connection->transaction); @@ -1491,10 +1497,10 @@ SQL; $this->assertTrue($hitCatch); } - public function testCreateView() + public function testCreateView(): void { $db = $this->getConnection(); - $subquery = (new \yii\db\Query()) + $subquery = (new Query()) ->select('bar') ->from('testCreateViewTable') ->where(['>', 'bar', '5']); @@ -1516,7 +1522,7 @@ SQL; $this->assertEquals([['bar' => 6]], $records); } - public function testDropView() + public function testDropView(): void { $db = $this->getConnection(); $viewName = 'animal_view'; // since it already exists in the fixtures @@ -1527,26 +1533,26 @@ SQL; } // TODO: Remove in Yii 2.1 - public function testBindValuesSupportsDeprecatedPDOCastingFormat() + public function testBindValuesSupportsDeprecatedPDOCastingFormat(): void { $db = $this->getConnection(); - $db->createCommand()->setSql('SELECT :p1')->bindValues([':p1' => [2, \PDO::PARAM_STR]]); + $db->createCommand()->setSql('SELECT :p1')->bindValues([':p1' => [2, PDO::PARAM_STR]]); $this->assertTrue(true); } - public function testBindValuesSupportsEnums() + public function testBindValuesSupportsEnums(): void { if (version_compare(PHP_VERSION, '8.1.0') >= 0) { $db = $this->getConnection(); $command = $db->createCommand(); - $command->setSql('SELECT :p1')->bindValues([':p1' => enums\Status::Active]); + $command->setSql('SELECT :p1')->bindValues([':p1' => Status::Active]); $this->assertSame('Active', $command->params[':p1']); - $command->setSql('SELECT :p1')->bindValues([':p1' => enums\StatusTypeString::Active]); + $command->setSql('SELECT :p1')->bindValues([':p1' => StatusTypeString::Active]); $this->assertSame('active', $command->params[':p1']); - $command->setSql('SELECT :p1')->bindValues([':p1' => enums\StatusTypeInt::Active]); + $command->setSql('SELECT :p1')->bindValues([':p1' => StatusTypeInt::Active]); $this->assertSame(1, $command->params[':p1']); } else { $this->markTestSkipped('Enums are not supported in PHP < 8.1'); diff --git a/tests/framework/db/ConnectionTest.php b/tests/framework/db/ConnectionTest.php index 23ef80bbb1..7e937310fb 100644 --- a/tests/framework/db/ConnectionTest.php +++ b/tests/framework/db/ConnectionTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db; +use Exception; use Yii; use yii\base\InvalidConfigException; use yii\caching\ArrayCache; @@ -18,7 +19,7 @@ use yii\db\Transaction; abstract class ConnectionTest extends DatabaseTestCase { - public function testConstruct() + public function testConstruct(): void { $connection = $this->getConnection(false); $params = $this->database; @@ -28,7 +29,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals($params['password'], $connection->password); } - public function testOpenClose() + public function testOpenClose(): void { $connection = $this->getConnection(false, false); @@ -49,7 +50,7 @@ abstract class ConnectionTest extends DatabaseTestCase $connection->open(); } - public function testQueryBuilderConfigurationAfterOpenClose() + public function testQueryBuilderConfigurationAfterOpenClose(): void { $connection = $this->getConnection(false, false); $connection->setQueryBuilder([ @@ -93,7 +94,7 @@ abstract class ConnectionTest extends DatabaseTestCase ); } - public function testSerialize() + public function testSerialize(): void { $connection = $this->getConnection(false, false); $connection->open(); @@ -108,13 +109,13 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals(123, $unserialized->createCommand('SELECT 123')->queryScalar()); } - public function testGetDriverName() + public function testGetDriverName(): void { $connection = $this->getConnection(false, false); $this->assertEquals($this->driverName, $connection->driverName); } - public function testQuoteValue() + public function testQuoteValue(): void { $connection = $this->getConnection(false); $this->assertEquals(123, $connection->quoteValue(123)); @@ -122,7 +123,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals("'It\\'s interesting'", $connection->quoteValue("It's interesting")); } - public function testQuoteTableName() + public function testQuoteTableName(): void { $connection = $this->getConnection(false, false); $this->assertEquals('`table`', $connection->quoteTableName('table')); @@ -135,7 +136,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals('`table(0)`', $connection->quoteTableName('table(0)')); } - public function testQuoteColumnName() + public function testQuoteColumnName(): void { $connection = $this->getConnection(false, false); $this->assertEquals('`column`', $connection->quoteColumnName('column')); @@ -148,7 +149,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals('`column`', $connection->quoteSql('{{column}}')); } - public function testQuoteFullColumnName() + public function testQuoteFullColumnName(): void { $connection = $this->getConnection(false, false); $this->assertEquals('`table`.`column`', $connection->quoteColumnName('table.column')); @@ -170,7 +171,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals('`table`.`column`', $connection->quoteSql('{{%table}}.`column`')); } - public function testTransaction() + public function testTransaction(): void { $connection = $this->getConnection(false); $this->assertNull($connection->transaction); @@ -205,7 +206,7 @@ abstract class ConnectionTest extends DatabaseTestCase ); } - public function testTransactionIsolation() + public function testTransactionIsolation(): void { $connection = $this->getConnection(true); @@ -224,15 +225,15 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertTrue(true); // should not be any exception so far } - public function testTransactionShortcutException() + public function testTransactionShortcutException(): void { $connection = $this->getConnection(true); - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $connection->transaction(function () use ($connection) { $connection->createCommand()->insert('profile', ['description' => 'test transaction shortcut'])->execute(); - throw new \Exception('Exception in transaction shortcut'); + throw new Exception('Exception in transaction shortcut'); }); $profilesCount = $connection @@ -241,7 +242,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals(0, $profilesCount, 'profile should not be inserted in transaction shortcut'); } - public function testTransactionShortcutCorrect() + public function testTransactionShortcutCorrect(): void { $connection = $this->getConnection(true); @@ -259,7 +260,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertEquals(1, $profilesCount, 'profile should be inserted in transaction shortcut'); } - public function testTransactionShortcutCustom() + public function testTransactionShortcutCustom(): void { $connection = $this->getConnection(true); @@ -278,7 +279,7 @@ abstract class ConnectionTest extends DatabaseTestCase * Tests nested transactions with partial rollback. * @see https://github.com/yiisoft/yii2/issues/9851 */ - public function testNestedTransaction() + public function testNestedTransaction(): void { /** @var Connection $connection */ $connection = $this->getConnection(true); @@ -292,7 +293,7 @@ abstract class ConnectionTest extends DatabaseTestCase }); } - public function testNestedTransactionNotSupported() + public function testNestedTransactionNotSupported(): void { $connection = $this->getConnection(); $connection->enableSavepoint = false; @@ -303,7 +304,7 @@ abstract class ConnectionTest extends DatabaseTestCase }); } - public function testEnableQueryLog() + public function testEnableQueryLog(): void { $connection = $this->getConnection(); foreach (['qlog1', 'qlog2', 'qlog3', 'qlog4'] as $table) { @@ -316,54 +317,54 @@ abstract class ConnectionTest extends DatabaseTestCase $connection->enableLogging = true; $connection->enableProfiling = true; - \Yii::getLogger()->messages = []; + Yii::getLogger()->messages = []; $connection->createCommand()->createTable('qlog1', ['id' => 'pk'])->execute(); - $this->assertCount(3, \Yii::getLogger()->messages); + $this->assertCount(3, Yii::getLogger()->messages); $this->assertNotNull($connection->getTableSchema('qlog1', true)); - \Yii::getLogger()->messages = []; + Yii::getLogger()->messages = []; $connection->createCommand('SELECT * FROM {{qlog1}}')->queryAll(); - $this->assertCount(3, \Yii::getLogger()->messages); + $this->assertCount(3, Yii::getLogger()->messages); // profiling only $connection->enableLogging = false; $connection->enableProfiling = true; - \Yii::getLogger()->messages = []; + Yii::getLogger()->messages = []; $connection->createCommand()->createTable('qlog2', ['id' => 'pk'])->execute(); - $this->assertCount(2, \Yii::getLogger()->messages); + $this->assertCount(2, Yii::getLogger()->messages); $this->assertNotNull($connection->getTableSchema('qlog2', true)); - \Yii::getLogger()->messages = []; + Yii::getLogger()->messages = []; $connection->createCommand('SELECT * FROM {{qlog2}}')->queryAll(); - $this->assertCount(2, \Yii::getLogger()->messages); + $this->assertCount(2, Yii::getLogger()->messages); // logging only $connection->enableLogging = true; $connection->enableProfiling = false; - \Yii::getLogger()->messages = []; + Yii::getLogger()->messages = []; $connection->createCommand()->createTable('qlog3', ['id' => 'pk'])->execute(); - $this->assertCount(1, \Yii::getLogger()->messages); + $this->assertCount(1, Yii::getLogger()->messages); $this->assertNotNull($connection->getTableSchema('qlog3', true)); - \Yii::getLogger()->messages = []; + Yii::getLogger()->messages = []; $connection->createCommand('SELECT * FROM {{qlog3}}')->queryAll(); - $this->assertCount(1, \Yii::getLogger()->messages); + $this->assertCount(1, Yii::getLogger()->messages); // disabled $connection->enableLogging = false; $connection->enableProfiling = false; - \Yii::getLogger()->messages = []; + Yii::getLogger()->messages = []; $connection->createCommand()->createTable('qlog4', ['id' => 'pk'])->execute(); $this->assertNotNull($connection->getTableSchema('qlog4', true)); - $this->assertCount(0, \Yii::getLogger()->messages); + $this->assertCount(0, Yii::getLogger()->messages); $connection->createCommand('SELECT * FROM {{qlog4}}')->queryAll(); - $this->assertCount(0, \Yii::getLogger()->messages); + $this->assertCount(0, Yii::getLogger()->messages); } - public function testExceptionContainsRawQuery() + public function testExceptionContainsRawQuery(): void { $connection = $this->getConnection(); if ($connection->getTableSchema('qlog1', true) === null) { @@ -396,7 +397,7 @@ abstract class ConnectionTest extends DatabaseTestCase /** * @param Connection $connection */ - private function runExceptionTest($connection) + private function runExceptionTest($connection): void { $thrown = false; try { @@ -430,7 +431,7 @@ abstract class ConnectionTest extends DatabaseTestCase * Make sure each connection element has its own PDO instance i.e. own connection to the DB. * Also transaction elements should not be shared between two connections. */ - public function testClone() + public function testClone(): void { $connection = $this->getConnection(true, false); $this->assertNull($connection->transaction); @@ -482,7 +483,7 @@ abstract class ConnectionTest extends DatabaseTestCase * * @see https://github.com/yiisoft/yii2/issues/14165 */ - public function testGetPdoAfterClose() + public function testGetPdoAfterClose(): void { $connection = $this->getConnection(); $connection->slaves[] = [ @@ -503,7 +504,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertNotSame($masterPdo, $slavePdo); } - public function testServerStatusCacheWorks() + public function testServerStatusCacheWorks(): void { $cache = new ArrayCache(); Yii::$app->set('cache', $cache); @@ -533,7 +534,7 @@ abstract class ConnectionTest extends DatabaseTestCase $connection->close(); } - public function testServerStatusCacheCanBeDisabled() + public function testServerStatusCacheCanBeDisabled(): void { $cache = new ArrayCache(); Yii::$app->set('cache', $cache); diff --git a/tests/framework/db/DatabaseTestCase.php b/tests/framework/db/DatabaseTestCase.php index 1d0d7d9347..23ffac69ed 100644 --- a/tests/framework/db/DatabaseTestCase.php +++ b/tests/framework/db/DatabaseTestCase.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\db; +use Exception; +use Yii; use yii\caching\DummyCache; use yii\db\Connection; use yiiunit\TestCase; @@ -27,7 +29,7 @@ abstract class DatabaseTestCase extends TestCase protected function setUp(): void { if ($this->driverName === null) { - throw new \Exception('driverName is not set for a DatabaseTestCase.'); + throw new Exception('driverName is not set for a DatabaseTestCase.'); } parent::setUp(); @@ -55,7 +57,7 @@ abstract class DatabaseTestCase extends TestCase /** * @param bool $reset whether to clean up the test database * @param bool $open whether to open and populate test database - * @return \yii\db\Connection + * @return Connection */ public function getConnection($reset = true, $open = true) { @@ -71,7 +73,7 @@ abstract class DatabaseTestCase extends TestCase } try { $this->_db = $this->prepareDatabase($config, $fixture, $open); - } catch (\Exception $e) { + } catch (Exception $e) { $this->markTestSkipped('Something wrong when preparing database: ' . $e->getMessage()); } @@ -83,8 +85,8 @@ abstract class DatabaseTestCase extends TestCase if (!isset($config['class'])) { $config['class'] = 'yii\db\Connection'; } - /** @var \yii\db\Connection $db */ - $db = \Yii::createObject($config); + /** @var Connection $db */ + $db = Yii::createObject($config); if (!$open) { return $db; } @@ -132,7 +134,7 @@ abstract class DatabaseTestCase extends TestCase } /** - * @return \yii\db\Connection + * @return Connection */ protected function getConnectionWithInvalidSlave() { diff --git a/tests/framework/db/GetTablesAliasTestTrait.php b/tests/framework/db/GetTablesAliasTestTrait.php index 5b8f04fdad..831c97147e 100644 --- a/tests/framework/db/GetTablesAliasTestTrait.php +++ b/tests/framework/db/GetTablesAliasTestTrait.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\db; +use stdClass; +use yii\db\Expression; use yii\db\ActiveQuery; use yii\db\Query; @@ -18,7 +20,7 @@ trait GetTablesAliasTestTrait */ abstract protected function createQuery(); - public function testGetTableNames_isFromArrayWithAlias() + public function testGetTableNames_isFromArrayWithAlias(): void { $query = $this->createQuery(); $query->from = [ @@ -38,7 +40,7 @@ trait GetTablesAliasTestTrait ], $tables); } - public function testGetTableNames_isFromArrayWithoutAlias() + public function testGetTableNames_isFromArrayWithoutAlias(): void { $query = $this->createQuery(); $query->from = [ @@ -54,7 +56,7 @@ trait GetTablesAliasTestTrait ], $tables); } - public function testGetTableNames_isFromString() + public function testGetTableNames_isFromString(): void { $query = $this->createQuery(); $query->from = 'profile AS \'prf\', user "usr", `order`, "customer", "a b" as "c d"'; @@ -70,17 +72,17 @@ trait GetTablesAliasTestTrait ], $tables); } - public function testGetTableNames_isFromObject_generateException() + public function testGetTableNames_isFromObject_generateException(): void { $query = $this->createQuery(); - $query->from = new \stdClass(); + $query->from = new stdClass(); $this->expectException('\yii\base\InvalidConfigException'); $query->getTablesUsedInFrom(); } - public function testGetTablesAlias_isFromString() + public function testGetTablesAlias_isFromString(): void { $query = $this->createQuery(); $query->from = 'profile AS \'prf\', user "usr", service srv, order, [a b] [c d], {{something}} AS myalias'; @@ -100,7 +102,7 @@ trait GetTablesAliasTestTrait /** * @see https://github.com/yiisoft/yii2/issues/14150 */ - public function testGetTableNames_isFromPrefixedTableName() + public function testGetTableNames_isFromPrefixedTableName(): void { $query = $this->createQuery(); $query->from = '{{%order_item}}'; @@ -115,7 +117,7 @@ trait GetTablesAliasTestTrait /** * @see https://github.com/yiisoft/yii2/issues/14211 */ - public function testGetTableNames_isFromTableNameWithDatabase() + public function testGetTableNames_isFromTableNameWithDatabase(): void { $query = $this->createQuery(); $query->from = 'tickets.workflows'; @@ -127,10 +129,10 @@ trait GetTablesAliasTestTrait ], $tables); } - public function testGetTableNames_isFromAliasedExpression() + public function testGetTableNames_isFromAliasedExpression(): void { $query = $this->createQuery(); - $expression = new \yii\db\Expression('(SELECT id FROM user)'); + $expression = new Expression('(SELECT id FROM user)'); $query->from = $expression; $this->expectException('yii\base\InvalidParamException'); @@ -140,10 +142,10 @@ trait GetTablesAliasTestTrait $this->assertEquals(['{{x}}' => $expression], $tables); } - public function testGetTableNames_isFromAliasedArrayWithExpression() + public function testGetTableNames_isFromAliasedArrayWithExpression(): void { $query = $this->createQuery(); - $query->from = ['x' => new \yii\db\Expression('(SELECT id FROM user)')]; + $query->from = ['x' => new Expression('(SELECT id FROM user)')]; $tables = $query->getTablesUsedInFrom(); @@ -152,7 +154,7 @@ trait GetTablesAliasTestTrait ], $tables); } - public function testGetTableNames_isFromAliasedSubquery() + public function testGetTableNames_isFromAliasedSubquery(): void { $query = $this->createQuery(); $subQuery = $this->createQuery(); diff --git a/tests/framework/db/QueryBuilderTest.php b/tests/framework/db/QueryBuilderTest.php index e0fb82cfa0..2699db38a3 100644 --- a/tests/framework/db/QueryBuilderTest.php +++ b/tests/framework/db/QueryBuilderTest.php @@ -8,6 +8,10 @@ namespace yiiunit\framework\db; +use Yii; +use Exception; +use Closure; +use yii\base\NotSupportedException; use yii\db\ColumnSchemaBuilder; use yii\db\conditions\BetweenColumnsCondition; use yii\db\conditions\LikeCondition; @@ -48,13 +52,13 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param bool $reset * @param bool $open * @return QueryBuilder - * @throws \Exception + * @throws Exception */ protected function getQueryBuilder($reset = true, $open = false) { $connection = $this->getConnection($reset, $open); - \Yii::$container->set('db', $connection); + Yii::$container->set('db', $connection); switch ($this->driverName) { case 'mysql': @@ -70,7 +74,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase case 'oci': return new OracleQueryBuilder($connection); } - throw new \Exception('Test is not implemented for ' . $this->driverName); + throw new Exception('Test is not implemented for ' . $this->driverName); } /** @@ -1060,7 +1064,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase return array_values($items); } - public function testGetColumnType() + public function testGetColumnType(): void { $qb = $this->getQueryBuilder(); @@ -1081,7 +1085,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase } } - public function testCreateTableColumnTypes() + public function testCreateTableColumnTypes(): void { $qb = $this->getQueryBuilder(); if ($qb->db->getTableSchema('column_type_table', true) !== null) { @@ -1321,9 +1325,9 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @dataProvider buildFromDataProvider * @param $table * @param $expected - * @throws \Exception + * @throws Exception */ - public function testBuildFrom($table, $expected) + public function testBuildFrom($table, $expected): void { $params = []; $sql = $this->getQueryBuilder()->buildFrom([$table], $params); @@ -1345,9 +1349,9 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param array $condition * @param string $expected * @param array $expectedParams - * @throws \Exception + * @throws Exception */ - public function testBuildCondition($condition, $expected, $expectedParams) + public function testBuildCondition($condition, $expected, $expectedParams): void { $query = (new Query())->where($condition); list($sql, $params) = $this->getQueryBuilder()->build($query); @@ -1361,7 +1365,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param string $expected * @param array $expectedParams */ - public function testBuildFilterCondition($condition, $expected, $expectedParams) + public function testBuildFilterCondition($condition, $expected, $expectedParams): void { $query = (new Query())->filterWhere($condition); list($sql, $params) = $this->getQueryBuilder()->build($query); @@ -1399,7 +1403,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @dataProvider primaryKeysProvider * @param string $sql */ - public function testAddDropPrimaryKey($sql, \Closure $builder) + public function testAddDropPrimaryKey($sql, Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } @@ -1435,7 +1439,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @dataProvider foreignKeysProvider * @param string $sql */ - public function testAddDropForeignKey($sql, \Closure $builder) + public function testAddDropForeignKey($sql, Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } @@ -1483,7 +1487,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @dataProvider indexesProvider * @param string $sql */ - public function testCreateDropIndex($sql, \Closure $builder) + public function testCreateDropIndex($sql, Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } @@ -1520,7 +1524,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @dataProvider uniquesProvider * @param string $sql */ - public function testAddDropUnique($sql, \Closure $builder) + public function testAddDropUnique($sql, Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } @@ -1549,7 +1553,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @dataProvider checksProvider * @param string $sql */ - public function testAddDropCheck($sql, \Closure $builder) + public function testAddDropCheck($sql, Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } @@ -1578,7 +1582,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @dataProvider defaultValuesProvider * @param string $sql */ - public function testAddDropDefaultValue($sql, \Closure $builder) + public function testAddDropDefaultValue($sql, Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } @@ -1596,7 +1600,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param string $cond * @param string $expectedQuerySql */ - public function testBuildWhereExists($cond, $expectedQuerySql) + public function testBuildWhereExists($cond, $expectedQuerySql): void { $expectedQueryParams = []; @@ -1614,7 +1618,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals($expectedQueryParams, $actualQueryParams); } - public function testBuildWhereExistsWithParameters() + public function testBuildWhereExistsWithParameters(): void { $expectedQuerySql = $this->replaceQuotes( 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (w.merchant_id = :merchant_id))) AND (t.some_column = :some_value)' @@ -1638,7 +1642,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals($expectedQueryParams, $queryParams); } - public function testBuildWhereExistsWithArrayParameters() + public function testBuildWhereExistsWithArrayParameters(): void { $expectedQuerySql = $this->replaceQuotes( 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (([[w]].[[merchant_id]]=:qp0) AND ([[w]].[[user_id]]=:qp1)))) AND ([[t]].[[some_column]]=:qp2)' @@ -1666,7 +1670,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * This test contains three select queries connected with UNION and UNION ALL constructions. * It could be useful to use "phpunit --group=db --filter testBuildUnion" command for run it. */ - public function testBuildUnion() + public function testBuildUnion(): void { $expectedQuerySql = $this->replaceQuotes( '(SELECT [[id]] FROM [[TotalExample]] [[t1]] WHERE (w > 0) AND (x < 2)) UNION ( SELECT [[id]] FROM [[TotalTotalExample]] [[t2]] WHERE w > 5 ) UNION ALL ( SELECT [[id]] FROM [[TotalTotalExample]] [[t3]] WHERE w = 3 )' @@ -1690,7 +1694,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals([], $queryParams); } - public function testBuildWithQuery() + public function testBuildWithQuery(): void { $expectedQuerySql = $this->replaceQuotes( 'WITH a1 AS (SELECT [[id]] FROM [[t1]] WHERE expr = 1), a2 AS ((SELECT [[id]] FROM [[t2]] INNER JOIN [[a1]] ON t2.id = a1.id WHERE expr = 2) UNION ( SELECT [[id]] FROM [[t3]] WHERE expr = 3 )) SELECT * FROM [[a2]]' @@ -1721,7 +1725,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals([], $queryParams); } - public function testBuildWithQueryRecursive() + public function testBuildWithQueryRecursive(): void { $expectedQuerySql = $this->replaceQuotes( 'WITH RECURSIVE a1 AS (SELECT [[id]] FROM [[t1]] WHERE expr = 1) SELECT * FROM [[a1]]' @@ -1740,7 +1744,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals([], $queryParams); } - public function testSelectSubquery() + public function testSelectSubquery(): void { $subquery = (new Query()) ->select('COUNT(*)') @@ -1756,7 +1760,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEmpty($params); } - public function testComplexSelect() + public function testComplexSelect(): void { $query = (new Query()) ->select([ @@ -1777,7 +1781,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEmpty($params); } - public function testSelectExpression() + public function testSelectExpression(): void { $query = (new Query()) ->select(new Expression('1 AS ab')) @@ -1809,7 +1813,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/10869 */ - public function testFromIndexHint() + public function testFromIndexHint(): void { $query = (new Query())->from([new Expression('{{%user}} USE INDEX (primary)')]); list($sql, $params) = $this->getQueryBuilder()->build($query); @@ -1826,7 +1830,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEmpty($params); } - public function testFromSubquery() + public function testFromSubquery(): void { // query subquery $subquery = (new Query())->from('user')->where('account_id = accounts.id'); @@ -1859,7 +1863,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEmpty($params); } - public function testOrderBy() + public function testOrderBy(): void { // simple string $query = (new Query()) @@ -1903,7 +1907,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals([':to' => 4], $params); } - public function testGroupBy() + public function testGroupBy(): void { // simple string $query = (new Query()) @@ -2044,7 +2048,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param string $expectedSQL * @param array $expectedParams */ - public function testInsert($table, $columns, $params, $expectedSQL, $expectedParams) + public function testInsert($table, $columns, $params, $expectedSQL, $expectedParams): void { $actualParams = $params; $actualSQL = $this->getQueryBuilder()->insert($table, $columns, $actualParams); @@ -2055,7 +2059,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * Dummy test to speed up QB's tests which rely on DB schema */ - public function testInitFixtures() + public function testInitFixtures(): void { $this->assertInstanceOf('yii\db\QueryBuilder', $this->getQueryBuilder(true, true)); } @@ -2268,10 +2272,10 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param array|null $updateColumns * @param string|string[] $expectedSQL * @param array $expectedParams - * @throws \yii\base\NotSupportedException - * @throws \Exception + * @throws NotSupportedException + * @throws Exception */ - public function testUpsert($table, $insertColumns, $updateColumns, $expectedSQL, $expectedParams) + public function testUpsert($table, $insertColumns, $updateColumns, $expectedSQL, $expectedParams): void { $actualParams = []; $actualSQL = $this->getQueryBuilder(true, $this->driverName === 'sqlite')->upsert($table, $insertColumns, $updateColumns, $actualParams); @@ -2341,9 +2345,9 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param array $columns * @param array $value * @param string $expected - * @throws \Exception + * @throws Exception */ - public function testBatchInsert($table, $columns, $value, $expected) + public function testBatchInsert($table, $columns, $value, $expected): void { $queryBuilder = $this->getQueryBuilder(); @@ -2380,7 +2384,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param string $expectedSQL * @param array $expectedParams */ - public function testUpdate($table, $columns, $condition, $expectedSQL, $expectedParams) + public function testUpdate($table, $columns, $condition, $expectedSQL, $expectedParams): void { $actualParams = []; $actualSQL = $this->getQueryBuilder()->update($table, $columns, $condition, $actualParams); @@ -2412,7 +2416,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param string $expectedSQL * @param array $expectedParams */ - public function testDelete($table, $condition, $expectedSQL, $expectedParams) + public function testDelete($table, $condition, $expectedSQL, $expectedParams): void { $actualParams = []; $actualSQL = $this->getQueryBuilder()->delete($table, $condition, $actualParams); @@ -2420,7 +2424,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertSame($expectedParams, $actualParams); } - public function testCommentColumn() + public function testCommentColumn(): void { $qb = $this->getQueryBuilder(); @@ -2437,7 +2441,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals($this->replaceQuotes($expected), $sql); } - public function testCommentTable() + public function testCommentTable(): void { $qb = $this->getQueryBuilder(); @@ -2518,7 +2522,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase * @param string $expected * @param array $expectedParams */ - public function testBuildLikeCondition($condition, $expected, $expectedParams) + public function testBuildLikeCondition($condition, $expected, $expectedParams): void { $query = (new Query())->where($condition); list($sql, $params) = $this->getQueryBuilder()->build($query); @@ -2529,7 +2533,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/15653 */ - public function testIssue15653() + public function testIssue15653(): void { $query = (new Query()) ->from('admin_user') diff --git a/tests/framework/db/QueryTest.php b/tests/framework/db/QueryTest.php index fb4a08645f..6b007abe40 100644 --- a/tests/framework/db/QueryTest.php +++ b/tests/framework/db/QueryTest.php @@ -18,7 +18,7 @@ abstract class QueryTest extends DatabaseTestCase { use GetTablesAliasTestTrait; - public function testSelect() + public function testSelect(): void { // default $query = new Query(); @@ -107,14 +107,14 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals(['DISTINCT ON(tour_dates.date_from) tour_dates.date_from', 'tour_dates.id' => 'tour_dates.id'], $query->select); } - public function testFrom() + public function testFrom(): void { $query = new Query(); $query->from('user'); $this->assertEquals(['user'], $query->from); } - public function testFromTableIsArrayWithExpression() + public function testFromTableIsArrayWithExpression(): void { $query = new Query(); $tables = new Expression('(SELECT id,name FROM user) u'); @@ -127,7 +127,7 @@ abstract class QueryTest extends DatabaseTestCase return new Query(); } - public function testWhere() + public function testWhere(): void { $query = new Query(); $query->where('id = :id', [':id' => 1]); @@ -143,7 +143,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals([':id' => 1, ':name' => 'something', ':age' => '30'], $query->params); } - public function testFilterWhereWithHashFormat() + public function testFilterWhereWithHashFormat(): void { $query = new Query(); $query->filterWhere([ @@ -160,7 +160,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals(['id' => 0], $query->where); } - public function testFilterWhereWithOperatorFormat() + public function testFilterWhereWithOperatorFormat(): void { $query = new Query(); $condition = ['like', 'name', 'Alex']; @@ -195,7 +195,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals($condition, $query->where); } - public function testFilterHavingWithHashFormat() + public function testFilterHavingWithHashFormat(): void { $query = new Query(); $query->filterHaving([ @@ -212,7 +212,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals(['id' => 0], $query->having); } - public function testFilterHavingWithOperatorFormat() + public function testFilterHavingWithOperatorFormat(): void { $query = new Query(); $condition = ['like', 'name', 'Alex']; @@ -247,7 +247,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals($condition, $query->having); } - public function testFilterRecursively() + public function testFilterRecursively(): void { $query = new Query(); $query->filterWhere(['and', ['like', 'name', ''], ['like', 'title', ''], ['id' => 1], ['not', ['like', 'name', '']]]); @@ -258,7 +258,7 @@ abstract class QueryTest extends DatabaseTestCase { }*/ - public function testGroup() + public function testGroup(): void { $query = new Query(); $query->groupBy('team'); @@ -271,7 +271,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals(['team', 'company', 'age'], $query->groupBy); } - public function testHaving() + public function testHaving(): void { $query = new Query(); $query->having('id = :id', [':id' => 1]); @@ -287,7 +287,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals([':id' => 1, ':name' => 'something', ':age' => '30'], $query->params); } - public function testOrder() + public function testOrder(): void { $query = new Query(); $query->orderBy('team'); @@ -314,7 +314,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals([$expression, $expression], $query->orderBy); } - public function testLimitOffset() + public function testLimitOffset(): void { $query = new Query(); $query->limit(10)->offset(5); @@ -322,7 +322,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals(5, $query->offset); } - public function testLimitOffsetWithExpression() + public function testLimitOffsetWithExpression(): void { $query = (new Query())->from('customer')->select('id')->orderBy('id'); $query @@ -337,7 +337,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals([2, 3], $result); } - public function testUnion() + public function testUnion(): void { $connection = $this->getConnection(); $query = (new Query()) @@ -355,7 +355,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertCount(4, $result); } - public function testOne() + public function testOne(): void { $db = $this->getConnection(); @@ -366,7 +366,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertFalse($result); } - public function testExists() + public function testExists(): void { $db = $this->getConnection(); @@ -377,7 +377,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertFalse($result); } - public function testColumn() + public function testColumn(): void { $db = $this->getConnection(); $result = (new Query())->select('name')->from('customer')->orderBy(['id' => SORT_DESC])->column($db); @@ -422,7 +422,7 @@ abstract class QueryTest extends DatabaseTestCase * * @see https://github.com/yiisoft/yii2/issues/13859 */ - public function testAmbiguousColumnIndexBy() + public function testAmbiguousColumnIndexBy(): void { switch ($this->driverName) { case 'pgsql': @@ -447,7 +447,7 @@ abstract class QueryTest extends DatabaseTestCase ], $result); } - public function testCount() + public function testCount(): void { $db = $this->getConnection(); @@ -472,7 +472,7 @@ abstract class QueryTest extends DatabaseTestCase * @depends testFilterWhereWithHashFormat * @depends testFilterWhereWithOperatorFormat */ - public function testAndFilterCompare() + public function testAndFilterCompare(): void { $query = new Query(); @@ -505,7 +505,7 @@ abstract class QueryTest extends DatabaseTestCase * * @depends testCount */ - public function testCountHavingWithoutGroupBy() + public function testCountHavingWithoutGroupBy(): void { if (!\in_array($this->driverName, ['mysql'])) { $this->markTestSkipped("{$this->driverName} does not support having without group by."); @@ -517,7 +517,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals(1, $count); } - public function testEmulateExecution() + public function testEmulateExecution(): void { $db = $this->getConnection(); @@ -614,7 +614,7 @@ abstract class QueryTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/13745 */ - public function testMultipleLikeConditions() + public function testMultipleLikeConditions(): void { $db = $this->getConnection(); $tableName = 'like_test'; @@ -660,12 +660,12 @@ abstract class QueryTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/15355 */ - public function testExpressionInFrom() + public function testExpressionInFrom(): void { $db = $this->getConnection(); $query = (new Query()) ->from( - new \yii\db\Expression( + new Expression( '(SELECT [[id]], [[name]], [[email]], [[address]], [[status]] FROM {{customer}}) c' ) ) @@ -675,7 +675,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals('user3', $result['name']); } - public function testQueryCache() + public function testQueryCache(): void { $db = $this->getConnection(); $db->enableQueryCache = true; @@ -736,7 +736,7 @@ abstract class QueryTest extends DatabaseTestCase /** * checks that all needed properties copied from source to new query */ - public function testQueryCreation() + public function testQueryCreation(): void { $where = 'id > :min_user_id'; $limit = 50; diff --git a/tests/framework/db/SchemaTest.php b/tests/framework/db/SchemaTest.php index 366f5c4170..86526410ae 100644 --- a/tests/framework/db/SchemaTest.php +++ b/tests/framework/db/SchemaTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db; +use Exception; use PDO; use yii\caching\ArrayCache; use yii\caching\FileCache; @@ -35,7 +36,7 @@ abstract class SchemaTest extends DatabaseTestCase ]; } - public function testGetSchemaNames() + public function testGetSchemaNames(): void { /** @var Schema $schema */ $schema = $this->getConnection()->schema; @@ -51,7 +52,7 @@ abstract class SchemaTest extends DatabaseTestCase * @dataProvider pdoAttributesProvider * @param array $pdoAttributes */ - public function testGetTableNames($pdoAttributes) + public function testGetTableNames($pdoAttributes): void { $connection = $this->getConnection(); foreach ($pdoAttributes as $name => $value) { @@ -84,7 +85,7 @@ abstract class SchemaTest extends DatabaseTestCase * @dataProvider pdoAttributesProvider * @param array $pdoAttributes */ - public function testGetTableSchemas($pdoAttributes) + public function testGetTableSchemas($pdoAttributes): void { $connection = $this->getConnection(); foreach ($pdoAttributes as $name => $value) { @@ -103,22 +104,22 @@ abstract class SchemaTest extends DatabaseTestCase } } - public function testGetTableSchemasWithAttrCase() + public function testGetTableSchemasWithAttrCase(): void { $db = $this->getConnection(false); - $db->slavePdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER); + $db->slavePdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); $this->assertEquals(\count($db->schema->getTableNames()), \count($db->schema->getTableSchemas())); - $db->slavePdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_UPPER); + $db->slavePdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); $this->assertEquals(\count($db->schema->getTableNames()), \count($db->schema->getTableSchemas())); } - public function testGetNonExistingTableSchema() + public function testGetNonExistingTableSchema(): void { $this->assertNull($this->getConnection()->schema->getTableSchema('nonexisting_table')); } - public function testSchemaCache() + public function testSchemaCache(): void { /** @var Connection $db */ $db = $this->getConnection(); @@ -142,7 +143,7 @@ abstract class SchemaTest extends DatabaseTestCase /** * @depends testSchemaCache */ - public function testRefreshTableSchema() + public function testRefreshTableSchema(): void { /** @var Schema $schema */ $schema = $this->getConnection()->schema; @@ -201,7 +202,7 @@ abstract class SchemaTest extends DatabaseTestCase * @dataProvider tableSchemaCachePrefixesProvider * @depends testSchemaCache */ - public function testTableSchemaCacheWithTablePrefixes($tablePrefix, $tableName, $testTablePrefix, $testTableName) + public function testTableSchemaCacheWithTablePrefixes($tablePrefix, $tableName, $testTablePrefix, $testTableName): void { /** @var Schema $schema */ $schema = $this->getConnection()->schema; @@ -232,7 +233,7 @@ abstract class SchemaTest extends DatabaseTestCase $this->assertNotSame($testNoCacheTable, $testRefreshedTable); } - public function testCompositeFk() + public function testCompositeFk(): void { /** @var Schema $schema */ $schema = $this->getConnection()->schema; @@ -246,18 +247,18 @@ abstract class SchemaTest extends DatabaseTestCase $this->assertEquals('item_id', $table->foreignKeys['FK_composite_fk_order_item']['item_id']); } - public function testGetPDOType() + public function testGetPDOType(): void { $values = [ - [null, \PDO::PARAM_NULL], - ['', \PDO::PARAM_STR], - ['hello', \PDO::PARAM_STR], - [0, \PDO::PARAM_INT], - [1, \PDO::PARAM_INT], - [1337, \PDO::PARAM_INT], - [true, \PDO::PARAM_BOOL], - [false, \PDO::PARAM_BOOL], - [$fp = fopen(__FILE__, 'rb'), \PDO::PARAM_LOB], + [null, PDO::PARAM_NULL], + ['', PDO::PARAM_STR], + ['hello', PDO::PARAM_STR], + [0, PDO::PARAM_INT], + [1, PDO::PARAM_INT], + [1337, PDO::PARAM_INT], + [true, PDO::PARAM_BOOL], + [false, PDO::PARAM_BOOL], + [$fp = fopen(__FILE__, 'rb'), PDO::PARAM_LOB], ]; /** @var Schema $schema */ @@ -491,7 +492,7 @@ abstract class SchemaTest extends DatabaseTestCase ]; } - public function testNegativeDefaultValues() + public function testNegativeDefaultValues(): void { /** @var Schema $schema */ $schema = $this->getConnection()->schema; @@ -505,7 +506,7 @@ abstract class SchemaTest extends DatabaseTestCase $this->assertEquals(-33.22, $table->getColumn('numeric_col')->defaultValue); } - public function testColumnSchema() + public function testColumnSchema(): void { $columns = $this->getExpectedColumns(); @@ -540,7 +541,7 @@ abstract class SchemaTest extends DatabaseTestCase } } - public function testColumnSchemaDbTypecastWithEmptyCharType() + public function testColumnSchemaDbTypecastWithEmptyCharType(): void { $columnSchema = new ColumnSchema(['type' => Schema::TYPE_CHAR]); $this->assertSame('', $columnSchema->dbTypecast('')); @@ -551,7 +552,7 @@ abstract class SchemaTest extends DatabaseTestCase * @param mixed $value * @param bool $expected */ - public function testColumnSchemaDbTypecastBooleanPhpType($value, $expected) + public function testColumnSchemaDbTypecastBooleanPhpType($value, $expected): void { $columnSchema = new ColumnSchema(['phpType' => Schema::TYPE_BOOLEAN]); $this->assertSame($expected, $columnSchema->dbTypecast($value)); @@ -579,7 +580,7 @@ abstract class SchemaTest extends DatabaseTestCase ]; } - public function testFindUniqueIndexes() + public function testFindUniqueIndexes(): void { if ($this->driverName === 'sqlsrv') { $this->markTestSkipped('`\yii\db\mssql\Schema::findUniqueIndexes()` returns only unique constraints not unique indexes.'); @@ -589,7 +590,7 @@ abstract class SchemaTest extends DatabaseTestCase try { $db->createCommand()->dropTable('uniqueIndex')->execute(); - } catch (\Exception $e) { + } catch (Exception $e) { } $db->createCommand()->createTable('uniqueIndex', [ 'somecol' => 'string', @@ -630,7 +631,7 @@ abstract class SchemaTest extends DatabaseTestCase ], $uniqueIndexes); } - public function testContraintTablesExistance() + public function testContraintTablesExistance(): void { $tableNames = [ 'T_constraints_1', @@ -768,7 +769,7 @@ abstract class SchemaTest extends DatabaseTestCase * @param string $type * @param mixed $expected */ - public function testTableSchemaConstraints($tableName, $type, $expected) + public function testTableSchemaConstraints($tableName, $type, $expected): void { if ($expected === false) { $this->expectException('yii\base\NotSupportedException'); @@ -784,7 +785,7 @@ abstract class SchemaTest extends DatabaseTestCase * @param string $type * @param mixed $expected */ - public function testTableSchemaConstraintsWithPdoUppercase($tableName, $type, $expected) + public function testTableSchemaConstraintsWithPdoUppercase($tableName, $type, $expected): void { if ($expected === false) { $this->expectException('yii\base\NotSupportedException'); @@ -802,7 +803,7 @@ abstract class SchemaTest extends DatabaseTestCase * @param string $type * @param mixed $expected */ - public function testTableSchemaConstraintsWithPdoLowercase($tableName, $type, $expected) + public function testTableSchemaConstraintsWithPdoLowercase($tableName, $type, $expected): void { if ($expected === false) { $this->expectException('yii\base\NotSupportedException'); diff --git a/tests/framework/db/cubrid/CommandTest.php b/tests/framework/db/cubrid/CommandTest.php index 1a273e8ba7..29b2add60f 100644 --- a/tests/framework/db/cubrid/CommandTest.php +++ b/tests/framework/db/cubrid/CommandTest.php @@ -16,7 +16,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest { public $driverName = 'cubrid'; - public function testBindParamValue() + public function testBindParamValue(): void { $db = $this->getConnection(); @@ -76,7 +76,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('user5@example.com', $command->queryScalar()); } - public function testAutoQuoting() + public function testAutoQuoting(): void { $db = $this->getConnection(false); @@ -94,7 +94,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest return $data; } - public function testAddDropCheck() + public function testAddDropCheck(): void { $this->markTestSkipped('CUBRID does not support adding/dropping check constraints.'); } diff --git a/tests/framework/db/cubrid/ConnectionTest.php b/tests/framework/db/cubrid/ConnectionTest.php index 5a05cdab12..1ce9af0616 100644 --- a/tests/framework/db/cubrid/ConnectionTest.php +++ b/tests/framework/db/cubrid/ConnectionTest.php @@ -16,7 +16,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { public $driverName = 'cubrid'; - public function testQuoteValue() + public function testQuoteValue(): void { $connection = $this->getConnection(false); $this->assertEquals(123, $connection->quoteValue(123)); @@ -24,7 +24,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals("'It''s interesting'", $connection->quoteValue("It's interesting")); } - public function testQuoteTableName() + public function testQuoteTableName(): void { $connection = $this->getConnection(false); $this->assertEquals('"table"', $connection->quoteTableName('table')); @@ -36,7 +36,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('(table)', $connection->quoteTableName('(table)')); } - public function testQuoteColumnName() + public function testQuoteColumnName(): void { $connection = $this->getConnection(false); $this->assertEquals('"column"', $connection->quoteColumnName('column')); @@ -49,7 +49,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('"column"', $connection->quoteSql('{{column}}')); } - public function testQuoteFullColumnName() + public function testQuoteFullColumnName(): void { $connection = $this->getConnection(false, false); $this->assertEquals('"table"."column"', $connection->quoteColumnName('table.column')); diff --git a/tests/framework/db/cubrid/QueryBuilderTest.php b/tests/framework/db/cubrid/QueryBuilderTest.php index dd1b7f94e7..ee0a30476b 100644 --- a/tests/framework/db/cubrid/QueryBuilderTest.php +++ b/tests/framework/db/cubrid/QueryBuilderTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\db\cubrid; +use PDO; + /** * @group db * @group cubrid @@ -33,17 +35,17 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return array_merge(parent::columnTypes(), []); } - public function checksProvider() + public function checksProvider(): void { $this->markTestSkipped('Adding/dropping check constraints is not supported in CUBRID.'); } - public function defaultValuesProvider() + public function defaultValuesProvider(): void { $this->markTestSkipped('Adding/dropping default constraints is not supported in CUBRID.'); } - public function testResetSequence() + public function testResetSequence(): void { $qb = $this->getQueryBuilder(); @@ -56,9 +58,9 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expected, $sql); } - public function testCommentColumn() + public function testCommentColumn(): void { - $version = $this->getQueryBuilder(false)->db->getSlavePdo(true)->getAttribute(\PDO::ATTR_SERVER_VERSION); + $version = $this->getQueryBuilder(false)->db->getSlavePdo(true)->getAttribute(PDO::ATTR_SERVER_VERSION); if (version_compare($version, '10.0', '<')) { $this->markTestSkipped('Comments on columns are supported starting with CUBRID 10.0.'); return; diff --git a/tests/framework/db/cubrid/SchemaTest.php b/tests/framework/db/cubrid/SchemaTest.php index ac0a2dc7d5..23f9a374f9 100644 --- a/tests/framework/db/cubrid/SchemaTest.php +++ b/tests/framework/db/cubrid/SchemaTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\cubrid; +use PDO; use yii\db\Expression; use yiiunit\framework\db\AnyCaseValue; @@ -19,23 +20,23 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest { public $driverName = 'cubrid'; - public function testGetSchemaNames() + public function testGetSchemaNames(): void { $this->markTestSkipped('Schemas are not supported in CUBRID.'); } - public function testGetPDOType() + public function testGetPDOType(): void { $values = [ - [null, \PDO::PARAM_NULL], - ['', \PDO::PARAM_STR], - ['hello', \PDO::PARAM_STR], - [0, \PDO::PARAM_INT], - [1, \PDO::PARAM_INT], - [1337, \PDO::PARAM_INT], - [true, \PDO::PARAM_INT], - [false, \PDO::PARAM_INT], - [$fp = fopen(__FILE__, 'rb'), \PDO::PARAM_LOB], + [null, PDO::PARAM_NULL], + ['', PDO::PARAM_STR], + ['hello', PDO::PARAM_STR], + [0, PDO::PARAM_INT], + [1, PDO::PARAM_INT], + [1337, PDO::PARAM_INT], + [true, PDO::PARAM_INT], + [false, PDO::PARAM_INT], + [$fp = fopen(__FILE__, 'rb'), PDO::PARAM_LOB], ]; $schema = $this->getConnection()->schema; @@ -107,12 +108,12 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $result; } - public function lowercaseConstraintsProvider() + public function lowercaseConstraintsProvider(): void { $this->markTestSkipped('This test hangs on CUBRID.'); } - public function uppercaseConstraintsProvider() + public function uppercaseConstraintsProvider(): void { $this->markTestSkipped('This test hangs on CUBRID.'); } diff --git a/tests/framework/db/mssql/ActiveRecordTest.php b/tests/framework/db/mssql/ActiveRecordTest.php index 43bcfa5a65..ccb2b15065 100644 --- a/tests/framework/db/mssql/ActiveRecordTest.php +++ b/tests/framework/db/mssql/ActiveRecordTest.php @@ -22,12 +22,12 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { public $driverName = 'sqlsrv'; - public function testExplicitPkOnAutoIncrement() + public function testExplicitPkOnAutoIncrement(): void { $this->markTestSkipped('MSSQL does not support explicit value for an IDENTITY column.'); } - public function testCastValues() + public function testCastValues(): void { $model = new Type(); $model->int_col = 123; @@ -59,7 +59,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest /** * @throws Exception */ - public function testSaveWithTrigger() + public function testSaveWithTrigger(): void { $db = $this->getConnection(); @@ -93,7 +93,7 @@ END'; /** * @throws Exception */ - public function testSaveWithComputedColumn() + public function testSaveWithComputedColumn(): void { $db = $this->getConnection(); @@ -120,7 +120,7 @@ END'; /** * @throws Exception */ - public function testSaveWithRowVersionColumn() + public function testSaveWithRowVersionColumn(): void { $db = $this->getConnection(); @@ -137,7 +137,7 @@ END'; /** * @throws Exception */ - public function testSaveWithRowVersionNullColumn() + public function testSaveWithRowVersionNullColumn(): void { $db = $this->getConnection(); diff --git a/tests/framework/db/mssql/CommandTest.php b/tests/framework/db/mssql/CommandTest.php index 82f61073c7..f161c9c001 100644 --- a/tests/framework/db/mssql/CommandTest.php +++ b/tests/framework/db/mssql/CommandTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\mssql; +use yii\db\pgsql\Schema; use yii\db\Query; /** @@ -18,7 +19,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest { protected $driverName = 'sqlsrv'; - public function testAutoQuoting() + public function testAutoQuoting(): void { $db = $this->getConnection(false); @@ -27,12 +28,12 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('SELECT [id], [t].[name] FROM [customer] t', $command->sql); } - public function testPrepareCancel() + public function testPrepareCancel(): void { $this->markTestSkipped('MSSQL driver does not support this feature.'); } - public function testBindParamValue() + public function testBindParamValue(): void { $db = $this->getConnection(); @@ -98,12 +99,12 @@ class CommandTest extends \yiiunit\framework\db\CommandTest ]; } - public function testAddDropDefaultValue() + public function testAddDropDefaultValue(): void { $db = $this->getConnection(false); $tableName = 'test_def'; $name = 'test_def_constraint'; - /** @var \yii\db\pgsql\Schema $schema */ + /** @var Schema $schema */ $schema = $db->getSchema(); if ($schema->getTableSchema($tableName) !== null) { @@ -132,7 +133,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest return $data; } - public function testUpsertVarbinary() + public function testUpsertVarbinary(): void { $db = $this->getConnection(); diff --git a/tests/framework/db/mssql/ConnectionTest.php b/tests/framework/db/mssql/ConnectionTest.php index 4b78a36875..bb00efc63d 100644 --- a/tests/framework/db/mssql/ConnectionTest.php +++ b/tests/framework/db/mssql/ConnectionTest.php @@ -16,7 +16,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { protected $driverName = 'sqlsrv'; - public function testQuoteValue() + public function testQuoteValue(): void { $connection = $this->getConnection(false); $this->assertEquals(123, $connection->quoteValue(123)); @@ -24,7 +24,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals("'It''s interesting'", $connection->quoteValue("It's interesting")); } - public function testQuoteTableName() + public function testQuoteTableName(): void { $connection = $this->getConnection(false); $this->assertEquals('[table]', $connection->quoteTableName('table')); @@ -36,7 +36,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('(table)', $connection->quoteTableName('(table)')); } - public function testQuoteColumnName() + public function testQuoteColumnName(): void { $connection = $this->getConnection(false); $this->assertEquals('[column]', $connection->quoteColumnName('column')); @@ -49,7 +49,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('[column]', $connection->quoteSql('{{column}}')); } - public function testQuoteFullColumnName() + public function testQuoteFullColumnName(): void { $connection = $this->getConnection(false, false); $this->assertEquals('[table].[column]', $connection->quoteColumnName('table.column')); diff --git a/tests/framework/db/mssql/QueryBuilderTest.php b/tests/framework/db/mssql/QueryBuilderTest.php index 8c585ce8c9..285e90d4b3 100644 --- a/tests/framework/db/mssql/QueryBuilderTest.php +++ b/tests/framework/db/mssql/QueryBuilderTest.php @@ -28,7 +28,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest '\\\\' => '[\\]', ]; - public function testOffsetLimit() + public function testOffsetLimit(): void { $expectedQuerySql = 'SELECT [id] FROM [example] ORDER BY (SELECT NULL) OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY'; $expectedQueryParams = []; @@ -42,7 +42,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expectedQueryParams, $actualQueryParams); } - public function testLimit() + public function testLimit(): void { $expectedQuerySql = 'SELECT [id] FROM [example] ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY'; $expectedQueryParams = []; @@ -56,7 +56,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expectedQueryParams, $actualQueryParams); } - public function testOffset() + public function testOffset(): void { $expectedQuerySql = 'SELECT [id] FROM [example] ORDER BY (SELECT NULL) OFFSET 10 ROWS'; $expectedQueryParams = []; @@ -128,7 +128,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $db->createCommand($sql)->execute(); } - public function testCommentAdditionOnTableAndOnColumn() + public function testCommentAdditionOnTableAndOnColumn(): void { $table = 'profile'; $tableComment = 'A comment for profile table.'; @@ -175,7 +175,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ], $result[0]); } - public function testCommentAdditionOnQuotedTableOrColumn() + public function testCommentAdditionOnQuotedTableOrColumn(): void { $table = 'stranger \'table'; $tableComment = 'A comment for stranger \'table.'; @@ -200,7 +200,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ], $resultColumn[0]); } - public function testCommentRemovalFromTableAndFromColumn() + public function testCommentRemovalFromTableAndFromColumn(): void { $table = 'profile'; $tableComment = 'A comment for profile table.'; @@ -217,7 +217,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals([], $result); } - public function testCommentRemovalFromQuotedTableOrColumn() + public function testCommentRemovalFromQuotedTableOrColumn(): void { $table = 'stranger \'table'; $tableComment = 'A comment for stranger \'table.'; @@ -234,12 +234,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals([], $result); } - public function testCommentColumn() + public function testCommentColumn(): void { $this->markTestSkipped('Testing the behavior, not sql generation anymore.'); } - public function testCommentTable() + public function testCommentTable(): void { $this->markTestSkipped('Testing the behavior, not sql generation anymore.'); } @@ -361,7 +361,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]; } - public function testResetSequence() + public function testResetSequence(): void { $qb = $this->getQueryBuilder(); @@ -447,7 +447,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $data; } - public function testAlterColumn() + public function testAlterColumn(): void { $qb = $this->getQueryBuilder(); @@ -639,7 +639,7 @@ ALTER TABLE [foo1] ADD CONSTRAINT [UQ_foo1_bar] UNIQUE ([bar])"; $this->assertEquals($expected, $sql); } - public function testAlterColumnOnDb() + public function testAlterColumnOnDb(): void { $connection = $this->getConnection(); @@ -657,7 +657,7 @@ ALTER TABLE [foo1] ADD CONSTRAINT [UQ_foo1_bar] UNIQUE ([bar])"; $this->assertEquals(false, $schema->getColumn('bar')->allowNull); } - public function testAlterColumnWithNull() + public function testAlterColumnWithNull(): void { $qb = $this->getQueryBuilder(); @@ -689,7 +689,7 @@ ALTER TABLE [foo1] ADD CONSTRAINT [DF_foo1_bar] DEFAULT NULL FOR [bar]"; $this->assertEquals($expected, $sql); } - public function testAlterColumnWithExpression() + public function testAlterColumnWithExpression(): void { $qb = $this->getQueryBuilder(); @@ -721,7 +721,7 @@ ALTER TABLE [foo1] ADD CONSTRAINT [DF_foo1_bar] DEFAULT CAST(GETDATE() AS INT) F $this->assertEquals($expected, $sql); } - public function testAlterColumnWithCheckConstraintOnDb() + public function testAlterColumnWithCheckConstraintOnDb(): void { $connection = $this->getConnection(); @@ -735,7 +735,7 @@ ALTER TABLE [foo1] ADD CONSTRAINT [DF_foo1_bar] DEFAULT CAST(GETDATE() AS INT) F $this->assertEquals(1, $connection->createCommand($sql)->execute()); } - public function testAlterColumnWithCheckConstraintOnDbWithException() + public function testAlterColumnWithCheckConstraintOnDbWithException(): void { $connection = $this->getConnection(); @@ -747,7 +747,7 @@ ALTER TABLE [foo1] ADD CONSTRAINT [DF_foo1_bar] DEFAULT CAST(GETDATE() AS INT) F $this->assertEquals(1, $connection->createCommand($sql)->execute()); } - public function testAlterColumnWithUniqueConstraintOnDbWithException() + public function testAlterColumnWithUniqueConstraintOnDbWithException(): void { $connection = $this->getConnection(); @@ -761,7 +761,7 @@ ALTER TABLE [foo1] ADD CONSTRAINT [DF_foo1_bar] DEFAULT CAST(GETDATE() AS INT) F $this->assertEquals(1, $connection->createCommand($sql)->execute()); } - public function testDropColumn() + public function testDropColumn(): void { $qb = $this->getQueryBuilder(); @@ -792,7 +792,7 @@ ALTER TABLE [foo1] DROP COLUMN [bar]"; $this->assertEquals($expected, $sql); } - public function testDropColumnOnDb() + public function testDropColumnOnDb(): void { $connection = $this->getConnection(); diff --git a/tests/framework/db/mssql/QueryCacheTest.php b/tests/framework/db/mssql/QueryCacheTest.php index 78fcbb012e..01f0a3fb30 100644 --- a/tests/framework/db/mssql/QueryCacheTest.php +++ b/tests/framework/db/mssql/QueryCacheTest.php @@ -20,7 +20,7 @@ class QueryCacheTest extends DatabaseTestCase { protected $driverName = 'sqlsrv'; - public function testQueryCacheFileCache() + public function testQueryCacheFileCache(): void { $db = $this->getConnection(); $db->enableQueryCache = true; diff --git a/tests/framework/db/mssql/QueryTest.php b/tests/framework/db/mssql/QueryTest.php index 3f4de9b733..9fe5c445e6 100644 --- a/tests/framework/db/mssql/QueryTest.php +++ b/tests/framework/db/mssql/QueryTest.php @@ -18,7 +18,7 @@ class QueryTest extends \yiiunit\framework\db\QueryTest { protected $driverName = 'sqlsrv'; - public function testUnion() + public function testUnion(): void { $connection = $this->getConnection(); diff --git a/tests/framework/db/mssql/SchemaTest.php b/tests/framework/db/mssql/SchemaTest.php index 3a45bf8637..0414abaad5 100644 --- a/tests/framework/db/mssql/SchemaTest.php +++ b/tests/framework/db/mssql/SchemaTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\mssql; +use yii\base\NotSupportedException; use yii\db\DefaultValueConstraint; use yii\db\mssql\Schema; use yiiunit\framework\db\AnyValue; @@ -45,7 +46,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $result; } - public function testGetStringFieldsSize() + public function testGetStringFieldsSize(): void { /** @var Connection $db */ $db = $this->getConnection(); @@ -90,9 +91,9 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest * @dataProvider quoteTableNameDataProvider * @param $name * @param $expectedName - * @throws \yii\base\NotSupportedException + * @throws NotSupportedException */ - public function testQuoteTableName($name, $expectedName) + public function testQuoteTableName($name, $expectedName): void { $schema = $this->getConnection()->getSchema(); $quotedName = $schema->quoteTableName($name); @@ -117,9 +118,9 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest * @dataProvider getTableSchemaDataProvider * @param $name * @param $expectedName - * @throws \yii\base\NotSupportedException + * @throws NotSupportedException */ - public function testGetTableSchema($name, $expectedName) + public function testGetTableSchema($name, $expectedName): void { $schema = $this->getConnection()->getSchema(); $tableSchema = $schema->getTableSchema($name); @@ -183,7 +184,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $columns; } - public function testGetPrimaryKey() + public function testGetPrimaryKey(): void { $db = $this->getConnection(); diff --git a/tests/framework/db/mssql/type/BooleanTest.php b/tests/framework/db/mssql/type/BooleanTest.php index 26d3af23d1..01aa035e7f 100644 --- a/tests/framework/db/mssql/type/BooleanTest.php +++ b/tests/framework/db/mssql/type/BooleanTest.php @@ -19,7 +19,7 @@ class BooleanTest extends DatabaseTestCase { protected $driverName = 'sqlsrv'; - public function testBoolean() + public function testBoolean(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -60,7 +60,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCast); } - public function testBooleanWithValueInteger() + public function testBooleanWithValueInteger(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -101,7 +101,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCast); } - public function testBooleanValueNegative() + public function testBooleanValueNegative(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -133,7 +133,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCast); } - public function testBooleanWithValueNull() + public function testBooleanWithValueNull(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -165,7 +165,7 @@ class BooleanTest extends DatabaseTestCase $this->assertNull($phpTypeCast); } - public function testBooleanWithValueOverflow() + public function testBooleanWithValueOverflow(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); diff --git a/tests/framework/db/mssql/type/VarbinaryTest.php b/tests/framework/db/mssql/type/VarbinaryTest.php index e3811b4330..b3f3eb6d1d 100644 --- a/tests/framework/db/mssql/type/VarbinaryTest.php +++ b/tests/framework/db/mssql/type/VarbinaryTest.php @@ -19,7 +19,7 @@ class VarbinaryTest extends DatabaseTestCase { protected $driverName = 'sqlsrv'; - public function testVarbinary() + public function testVarbinary(): void { $db = $this->getConnection(); diff --git a/tests/framework/db/mysql/ActiveRecordTest.php b/tests/framework/db/mysql/ActiveRecordTest.php index bbda237c45..1509a57fc9 100644 --- a/tests/framework/db/mysql/ActiveRecordTest.php +++ b/tests/framework/db/mysql/ActiveRecordTest.php @@ -19,7 +19,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { public $driverName = 'mysql'; - public function testCastValues() + public function testCastValues(): void { $model = new Type(); $model->int_col = 123; @@ -48,7 +48,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest //$this->assertSame(false, $model->bool_col2); } - public function testJsonColumn() + public function testJsonColumn(): void { if (version_compare($this->getConnection()->getSchema()->getServerVersion(), '5.7', '<')) { $this->markTestSkipped('JSON columns are not supported in MySQL < 5.7'); diff --git a/tests/framework/db/mysql/BaseActiveRecordTest.php b/tests/framework/db/mysql/BaseActiveRecordTest.php index 8acdc27ac8..a6812ccd59 100644 --- a/tests/framework/db/mysql/BaseActiveRecordTest.php +++ b/tests/framework/db/mysql/BaseActiveRecordTest.php @@ -17,7 +17,7 @@ class BaseActiveRecordTest extends \yiiunit\framework\db\BaseActiveRecordTest * * @dataProvider provideArrayValueWithChange */ - public function testJsonDirtyAttributesWithDataChange($actual, $modified) + public function testJsonDirtyAttributesWithDataChange($actual, $modified): void { if (version_compare($this->getConnection()->getSchema()->getServerVersion(), '5.7', '<')) { $this->markTestSkipped('JSON columns are not supported in MySQL < 5.7'); diff --git a/tests/framework/db/mysql/CommandTest.php b/tests/framework/db/mysql/CommandTest.php index 498d0f1feb..f77f612260 100644 --- a/tests/framework/db/mysql/CommandTest.php +++ b/tests/framework/db/mysql/CommandTest.php @@ -18,7 +18,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest protected $upsertTestCharCast = 'CONVERT([[address]], CHAR)'; - public function testAddDropCheckSeveral() + public function testAddDropCheckSeveral(): void { $db = $this->getConnection(false); diff --git a/tests/framework/db/mysql/ConnectionTest.php b/tests/framework/db/mysql/ConnectionTest.php index 8a700afa01..e4320d785c 100644 --- a/tests/framework/db/mysql/ConnectionTest.php +++ b/tests/framework/db/mysql/ConnectionTest.php @@ -21,7 +21,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest /** * @doesNotPerformAssertions */ - public function testTransactionAutocommit() + public function testTransactionAutocommit(): void { /** @var Connection $connection */ $connection = $this->getConnection(true); diff --git a/tests/framework/db/mysql/QueryBuilderTest.php b/tests/framework/db/mysql/QueryBuilderTest.php index 03455f0e0c..8ff9696a94 100644 --- a/tests/framework/db/mysql/QueryBuilderTest.php +++ b/tests/framework/db/mysql/QueryBuilderTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\mysql; +use PDO; use yii\base\DynamicModel; use yii\db\Expression; use yii\db\JsonExpression; @@ -126,7 +127,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest /** * @link https://github.com/yiisoft/yii2/issues/14367 */ - $mysqlVersion = $this->getDb()->getSlavePdo(true)->getAttribute(\PDO::ATTR_SERVER_VERSION); + $mysqlVersion = $this->getDb()->getSlavePdo(true)->getAttribute(PDO::ATTR_SERVER_VERSION); $supportsFractionalSeconds = version_compare($mysqlVersion, '5.6.4', '>='); if ($supportsFractionalSeconds) { $expectedValues = [ @@ -197,12 +198,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $result; } - public function defaultValuesProvider() + public function defaultValuesProvider(): void { $this->markTestSkipped('Adding/dropping default constraints is not supported in MySQL.'); } - public function testResetSequence() + public function testResetSequence(): void { $qb = $this->getQueryBuilder(); @@ -339,7 +340,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $items; } - public function testIssue17449() + public function testIssue17449(): void { $db = $this->getConnection(); $pdo = $db->pdo; @@ -366,7 +367,7 @@ MySqlStatement; /** * Test for issue https://github.com/yiisoft/yii2/issues/14663 */ - public function testInsertInteger() + public function testInsertInteger(): void { $db = $this->getConnection(); $command = $db->createCommand(); @@ -391,7 +392,7 @@ MySqlStatement; /** * Test for issue https://github.com/yiisoft/yii2/issues/15500 */ - public function testDefaultValues() + public function testDefaultValues(): void { $db = $this->getConnection(); $command = $db->createCommand(); diff --git a/tests/framework/db/mysql/QueryTest.php b/tests/framework/db/mysql/QueryTest.php index 30d2adc1a8..6fddd84886 100644 --- a/tests/framework/db/mysql/QueryTest.php +++ b/tests/framework/db/mysql/QueryTest.php @@ -22,7 +22,7 @@ class QueryTest extends \yiiunit\framework\db\QueryTest /** * Tests MySQL specific syntax for index hints. */ - public function testQueryIndexHint() + public function testQueryIndexHint(): void { $db = $this->getConnection(); @@ -33,7 +33,7 @@ class QueryTest extends \yiiunit\framework\db\QueryTest $this->assertArrayHasKey('email', $row); } - public function testLimitOffsetWithExpression() + public function testLimitOffsetWithExpression(): void { $query = (new Query())->from('customer')->select('id')->orderBy('id'); // In MySQL limit and offset arguments must both be nonnegative integer constant diff --git a/tests/framework/db/mysql/SchemaTest.php b/tests/framework/db/mysql/SchemaTest.php index 91bdaa3419..b63e556c95 100644 --- a/tests/framework/db/mysql/SchemaTest.php +++ b/tests/framework/db/mysql/SchemaTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\mysql; +use PDO; use yii\db\Expression; use yii\db\mysql\ColumnSchema; use yii\db\mysql\Schema; @@ -21,9 +22,9 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest { public $driverName = 'mysql'; - public function testLoadDefaultDatetimeColumn() + public function testLoadDefaultDatetimeColumn(): void { - if (!version_compare($this->getConnection()->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '5.6', '>=')) { + if (!version_compare($this->getConnection()->pdo->getAttribute(PDO::ATTR_SERVER_VERSION), '5.6', '>=')) { $this->markTestSkipped('Default datetime columns are supported since MySQL 5.6.'); } $sql = <<assertEquals('CURRENT_TIMESTAMP', (string)$dt->defaultValue); } - public function testDefaultDatetimeColumnWithMicrosecs() + public function testDefaultDatetimeColumnWithMicrosecs(): void { - if (!version_compare($this->getConnection()->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '5.6.4', '>=')) { + if (!version_compare($this->getConnection()->pdo->getAttribute(PDO::ATTR_SERVER_VERSION), '5.6.4', '>=')) { $this->markTestSkipped('CURRENT_TIMESTAMP with microseconds as default column value is supported since MySQL 5.6.4.'); } $sql = <<assertEquals('CURRENT_TIMESTAMP(3)', (string)$ts->defaultValue); } - public function testGetSchemaNames() + public function testGetSchemaNames(): void { $this->markTestSkipped('Schemas are not supported in MySQL.'); } @@ -95,7 +96,7 @@ SQL; * @param string $type * @param mixed $expected */ - public function testTableSchemaConstraints($tableName, $type, $expected) + public function testTableSchemaConstraints($tableName, $type, $expected): void { $version = $this->getConnection(false)->getServerVersion(); @@ -130,7 +131,7 @@ SQL; * @param string $type * @param mixed $expected */ - public function testTableSchemaConstraintsWithPdoUppercase($tableName, $type, $expected) + public function testTableSchemaConstraintsWithPdoUppercase($tableName, $type, $expected): void { $version = $this->getConnection(false)->getServerVersion(); @@ -156,7 +157,7 @@ SQL; } $connection = $this->getConnection(false); - $connection->getSlavePdo(true)->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_UPPER); + $connection->getSlavePdo(true)->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); $constraints = $connection->getSchema()->{'getTable' . ucfirst($type)}($tableName, true); $this->assertMetadataEquals($expected, $constraints); } @@ -167,7 +168,7 @@ SQL; * @param string $type * @param mixed $expected */ - public function testTableSchemaConstraintsWithPdoLowercase($tableName, $type, $expected) + public function testTableSchemaConstraintsWithPdoLowercase($tableName, $type, $expected): void { $version = $this->getConnection(false)->getServerVersion(); @@ -193,7 +194,7 @@ SQL; } $connection = $this->getConnection(false); - $connection->getSlavePdo(true)->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER); + $connection->getSlavePdo(true)->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); $constraints = $connection->getSchema()->{'getTable' . ucfirst($type)}($tableName, true); $this->assertMetadataEquals($expected, $constraints); } @@ -205,7 +206,7 @@ SQL; * @see https://mariadb.com/kb/en/library/now/#description * @see https://github.com/yiisoft/yii2/issues/15167 */ - public function testAlternativeDisplayOfDefaultCurrentTimestampInMariaDB() + public function testAlternativeDisplayOfDefaultCurrentTimestampInMariaDB(): void { /** * We do not have a real database MariaDB >= 10.2.3 for tests, so we emulate the information that database @@ -235,7 +236,7 @@ SQL; * * @see https://github.com/yiisoft/yii2/issues/19047 */ - public function testAlternativeDisplayOfDefaultCurrentTimestampAsNullInMariaDB() + public function testAlternativeDisplayOfDefaultCurrentTimestampAsNullInMariaDB(): void { $schema = new Schema(); $column = $this->invokeMethod($schema, 'loadColumnSchema', [[ diff --git a/tests/framework/db/mysql/connection/DeadLockTest.php b/tests/framework/db/mysql/connection/DeadLockTest.php index 72559b548f..ed6bb74cec 100644 --- a/tests/framework/db/mysql/connection/DeadLockTest.php +++ b/tests/framework/db/mysql/connection/DeadLockTest.php @@ -8,6 +8,10 @@ namespace yiiunit\framework\db\mysql\connection; +use yiiunit\framework\db\mysql\ConnectionTest; +use Throwable; +use RuntimeException; +use ErrorException; use yii\db\Connection; use yii\db\Exception; use yii\db\Transaction; @@ -16,7 +20,7 @@ use yii\db\Transaction; * @group db * @group mysql */ -class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest +class DeadLockTest extends ConnectionTest { /** @var string Shared log filename for children */ private $logFile; @@ -30,7 +34,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest * @link https://github.com/yiisoft/yii2/issues/12715 * @link https://github.com/yiisoft/yii2/pull/13346 */ - public function testDeadlockException() + public function testDeadlockException(): void { if (\stripos($this->getConnection(false)->getServerVersion(), 'MariaDB') !== false) { $this->markTestSkipped('MariaDB does not support this test'); @@ -91,7 +95,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest } $this->deleteLog(); throw $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { // wait all children while (-1 !== pcntl_wait($status)) { // nothing to do @@ -177,7 +181,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest $this->log('child 1: send signal to child 2'); // let child to continue if (!posix_kill($pidSecond, SIGUSR1)) { - throw new \RuntimeException('Cannot send signal'); + throw new RuntimeException('Cannot send signal'); } // now child 2 tries to do the 2nd update, and hits the lock and waits @@ -204,7 +208,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest } catch (\Exception $e) { $this->log('child 1: ! exit <<' . \get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->log('child 1: ! exit <<' . \get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } @@ -267,7 +271,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest } catch (\Exception $e) { $this->log('child 2: ! exit <<' . \get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->log('child 2: ! exit <<' . \get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } @@ -281,11 +285,11 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest * all the rest tests. So, all the rest tests in this case will run both in the child * and parent processes. Such mess must be prevented with child's own error handler. */ - private function setErrorHandler() + private function setErrorHandler(): void { if (PHP_VERSION_ID < 70000) { set_error_handler(function ($errno, $errstr, $errfile, $errline) { - throw new \ErrorException($errstr, $errno, $errno, $errfile, $errline); + throw new ErrorException($errstr, $errno, $errno, $errfile, $errline); }); } } @@ -294,7 +298,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest * Sets filename for log file shared between children processes. * @param string $filename */ - private function setLogFile($filename) + private function setLogFile($filename): void { $this->logFile = $filename; } @@ -303,7 +307,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest * Deletes shared log file. * Deletes the file [[logFile]] if it exists. */ - private function deleteLog() + private function deleteLog(): void { if (null !== $this->logFile && is_file($this->logFile)) { unlink($this->logFile); @@ -333,7 +337,7 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest * @param string $message Message to append to the log. The message will be prepended * with timestamp and appended with new line. */ - private function log($message) + private function log($message): void { if (null !== $this->logFile) { $time = microtime(true); diff --git a/tests/framework/db/oci/ActiveRecordTest.php b/tests/framework/db/oci/ActiveRecordTest.php index 63a57b62f6..98be9d4b11 100644 --- a/tests/framework/db/oci/ActiveRecordTest.php +++ b/tests/framework/db/oci/ActiveRecordTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\oci; +use yii\db\ActiveRecordInterface; use yii\db\ActiveQuery; use yiiunit\data\ar\BitValues; use yiiunit\data\ar\DefaultPk; @@ -23,7 +24,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { protected $driverName = 'oci'; - public function testCastValues() + public function testCastValues(): void { // pass, because boolean casting is not available $model = new Type(); @@ -53,7 +54,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertEquals('0', $model->bool_col2); } - public function testDefaultValues() + public function testDefaultValues(): void { $model = new Type(); $model->loadDefaultValues(); @@ -78,9 +79,9 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertEquals('something', $model->char_col2); } - public function testFindAsArray() + public function testFindAsArray(): void { - /** @var \yii\db\ActiveRecordInterface $customerClass */ + /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); // asArray @@ -118,7 +119,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertArrayHasKey('bool_status', $customers[2]); } - public function testPrimaryKeyAfterSave() + public function testPrimaryKeyAfterSave(): void { $record = new DefaultPk(); $record->type = 'type'; @@ -126,7 +127,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertEquals(5, $record->primaryKey); } - public function testMultiplePrimaryKeyAfterSave() + public function testMultiplePrimaryKeyAfterSave(): void { $record = new DefaultMultiplePk(); $record->id = 5; @@ -140,7 +141,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest /** * @see https://github.com/yiisoft/yii2/issues/9006 */ - public function testBit() + public function testBit(): void { $falseBit = BitValues::findOne(1); $this->assertEquals('0', $falseBit->val); @@ -153,11 +154,10 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest * Some PDO implementations(e.g. cubrid) do not support boolean values. * Make sure this does not affect AR layer. */ - public function testBooleanAttribute() + public function testBooleanAttribute(): void { /** @var TestCase|ActiveRecordTestTrait $this */ - - /** @var \yii\db\ActiveRecordInterface $customerClass */ + /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); $customer = new $customerClass(); $customer->name = 'boolean customer'; @@ -186,7 +186,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest * @dataProvider aliasMethodProvider * @param string $aliasMethod whether alias is specified explicitly or using the query syntax {{@tablename}} */ - public function testJoinWithAlias($aliasMethod) + public function testJoinWithAlias($aliasMethod): void { // left join and eager loading /** @var ActiveQuery $query */ diff --git a/tests/framework/db/oci/CommandTest.php b/tests/framework/db/oci/CommandTest.php index 0c49c922ae..470ac8924b 100644 --- a/tests/framework/db/oci/CommandTest.php +++ b/tests/framework/db/oci/CommandTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\db\oci; +use Exception; +use Throwable; use yii\caching\ArrayCache; use yii\db\Connection; use yii\db\Query; @@ -21,7 +23,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest { protected $driverName = 'oci'; - public function testAutoQuoting() + public function testAutoQuoting(): void { $db = $this->getConnection(false); @@ -30,7 +32,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('SELECT "id", "t"."name" FROM "customer" t', $command->sql); } - public function testLastInsertId() + public function testLastInsertId(): void { $db = $this->getConnection(); @@ -58,7 +60,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest * * @return void */ - public function testCLOBStringInsertion() + public function testCLOBStringInsertion(): void { $db = $this->getConnection(); @@ -78,7 +80,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $db->createCommand()->dropTable('longstring')->execute(); } - public function testQueryCache() + public function testQueryCache(): void { $db = $this->getConnection(true); @@ -168,7 +170,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest ]; } - public function testInsert() + public function testInsert(): void { $db = $this->getConnection(); $db->createCommand('DELETE FROM {{customer}}')->execute(); @@ -194,7 +196,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest /** * Test INSERT INTO ... SELECT SQL statement with alias syntax. */ - public function testInsertSelectAlias() + public function testInsertSelectAlias(): void { $db = $this->getConnection(); @@ -245,7 +247,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest * * https://github.com/yiisoft/yii2/issues/6526 */ - public function testBatchInsertDataTypesLocale() + public function testBatchInsertDataTypesLocale(): void { $locale = setlocale(LC_NUMERIC, 0); if (false === $locale) { @@ -290,10 +292,10 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('1', $data[0]['bool_col']); $this->assertIsOneOf($data[1]['bool_col'], ['0', false]); $this->assertIsOneOf($data[2]['bool_col'], ['0', false]); - } catch (\Exception $e) { + } catch (Exception $e) { setlocale(LC_NUMERIC, $locale); throw $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { setlocale(LC_NUMERIC, $locale); throw $e; } @@ -303,7 +305,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest /** * verify that {{}} are not going to be replaced in parameters. */ - public function testNoTablenameReplacement() + public function testNoTablenameReplacement(): void { $db = $this->getConnection(); @@ -335,7 +337,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('Some {{%updated}} address', $customer['address']); } - public function testCreateTable() + public function testCreateTable(): void { $db = $this->getConnection(); @@ -362,7 +364,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest ], $records); } - public function testsInsertQueryAsColumnValue() + public function testsInsertQueryAsColumnValue(): void { $time = time(); @@ -378,7 +380,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $orderId = $db->getLastInsertID('order_SEQ'); - $columnValueQuery = new \yii\db\Query(); + $columnValueQuery = new Query(); $columnValueQuery->select('created_at')->from('{{order}}')->where(['id' => $orderId]); $command = $db->createCommand(); @@ -399,7 +401,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $db->createCommand('DELETE FROM {{order}} WHERE [[id]] = ' . $orderId)->execute(); } - public function testAlterTable() + public function testAlterTable(): void { $db = $this->getConnection(); @@ -439,7 +441,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest ], $records); } - public function testCreateView() + public function testCreateView(): void { $db = $this->getConnection(); @@ -479,7 +481,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals([['bar' => 6]], $records); } - public function testColumnCase() + public function testColumnCase(): void { $this->markTestSkipped('Should be fixed.'); } diff --git a/tests/framework/db/oci/ConnectionTest.php b/tests/framework/db/oci/ConnectionTest.php index 2edf3b0432..a8cf7185ba 100644 --- a/tests/framework/db/oci/ConnectionTest.php +++ b/tests/framework/db/oci/ConnectionTest.php @@ -19,7 +19,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { protected $driverName = 'oci'; - public function testSerialize() + public function testSerialize(): void { $connection = $this->getConnection(false, false); $connection->open(); @@ -30,7 +30,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals(123, $unserialized->createCommand('SELECT 123 FROM DUAL')->queryScalar()); } - public function testQuoteTableName() + public function testQuoteTableName(): void { $connection = $this->getConnection(false); $this->assertEquals('"table"', $connection->quoteTableName('table')); @@ -42,7 +42,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('(table)', $connection->quoteTableName('(table)')); } - public function testQuoteColumnName() + public function testQuoteColumnName(): void { $connection = $this->getConnection(false); $this->assertEquals('"column"', $connection->quoteColumnName('column')); @@ -55,7 +55,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('"column"', $connection->quoteSql('{{column}}')); } - public function testQuoteFullColumnName() + public function testQuoteFullColumnName(): void { $connection = $this->getConnection(false, false); $this->assertEquals('"table"."column"', $connection->quoteColumnName('table.column')); @@ -77,7 +77,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('"table"."column"', $connection->quoteSql('{{%table}}."column"')); } - public function testTransactionIsolation() + public function testTransactionIsolation(): void { $connection = $this->getConnection(true); @@ -96,7 +96,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest * * Change Transaction::READ_UNCOMMITTED => Transaction::READ_COMMITTED. */ - public function testTransactionShortcutCustom() + public function testTransactionShortcutCustom(): void { $connection = $this->getConnection(true); @@ -113,7 +113,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals(1, $profilesCount, 'profile should be inserted in transaction shortcut'); } - public function testQuoteValue() + public function testQuoteValue(): void { $connection = $this->getConnection(false); $this->assertEquals(123, $connection->quoteValue(123)); diff --git a/tests/framework/db/oci/QueryBuilderTest.php b/tests/framework/db/oci/QueryBuilderTest.php index 2e6503a511..92e4047059 100644 --- a/tests/framework/db/oci/QueryBuilderTest.php +++ b/tests/framework/db/oci/QueryBuilderTest.php @@ -8,6 +8,9 @@ namespace yiiunit\framework\db\oci; +use Closure; +use Exception; +use yii\base\NotSupportedException; use yii\db\oci\QueryBuilder; use yii\db\oci\Schema; use yii\helpers\ArrayHelper; @@ -81,12 +84,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest * @dataProvider defaultValuesProvider * @param string $sql */ - public function testAddDropDefaultValue($sql, \Closure $builder) + public function testAddDropDefaultValue($sql, Closure $builder): void { $this->markTestSkipped('Adding/dropping default constraints is not supported in Oracle.'); } - public function testCommentColumn() + public function testCommentColumn(): void { $qb = $this->getQueryBuilder(); @@ -99,7 +102,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($this->replaceQuotes($expected), $sql); } - public function testCommentTable() + public function testCommentTable(): void { $qb = $this->getQueryBuilder(); @@ -112,7 +115,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($this->replaceQuotes($expected), $sql); } - public function testExecuteResetSequence() + public function testExecuteResetSequence(): void { $db = $this->getConnection(); $qb = $this->getQueryBuilder(); @@ -136,7 +139,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest try { $encodedBackslash = substr($this->getDb()->quoteValue('\\'), 1, -1); $this->likeParameterReplacements[$encodedBackslash] = '\\'; - } catch (\Exception $e) { + } catch (Exception $e) { $this->markTestSkipped('Could not execute Connection::quoteValue() method: ' . $e->getMessage()); } @@ -283,7 +286,7 @@ WHERE rownum <= 1) "EXCLUDED" ON ("T_upsert"."email"="EXCLUDED"."email") WHEN NO /** * Dummy test to speed up QB's tests which rely on DB schema */ - public function testInitFixtures() + public function testInitFixtures(): void { $this->assertInstanceOf('yii\db\QueryBuilder', $this->getQueryBuilder(true, true)); } @@ -296,10 +299,10 @@ WHERE rownum <= 1) "EXCLUDED" ON ("T_upsert"."email"="EXCLUDED"."email") WHEN NO * @param array|null $updateColumns * @param string|string[] $expectedSQL * @param array $expectedParams - * @throws \yii\base\NotSupportedException - * @throws \Exception + * @throws NotSupportedException + * @throws Exception */ - public function testUpsert($table, $insertColumns, $updateColumns, $expectedSQL, $expectedParams) + public function testUpsert($table, $insertColumns, $updateColumns, $expectedSQL, $expectedParams): void { $actualParams = []; $actualSQL = $this->getQueryBuilder(true, $this->driverName === 'sqlite')->upsert($table, $insertColumns, $updateColumns, $actualParams); diff --git a/tests/framework/db/oci/QueryTest.php b/tests/framework/db/oci/QueryTest.php index 292a7a1921..e88ccaf3e8 100644 --- a/tests/framework/db/oci/QueryTest.php +++ b/tests/framework/db/oci/QueryTest.php @@ -16,7 +16,7 @@ class QueryTest extends \yiiunit\framework\db\QueryTest { protected $driverName = 'oci'; - public function testUnion() + public function testUnion(): void { $this->markTestSkipped('Unsupported use of WITH clause in Oracle.'); } diff --git a/tests/framework/db/oci/SchemaTest.php b/tests/framework/db/oci/SchemaTest.php index 99e224b6c9..cea1d2e478 100644 --- a/tests/framework/db/oci/SchemaTest.php +++ b/tests/framework/db/oci/SchemaTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\oci; +use Exception; use yii\db\CheckConstraint; use yiiunit\framework\db\AnyValue; @@ -103,7 +104,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest * Autoincrement columns detection should be disabled for Oracle * because there is no way of associating a column with a sequence. */ - public function testAutoincrementDisabled() + public function testAutoincrementDisabled(): void { $table = $this->getConnection(false)->schema->getTableSchema('order', true); $this->assertFalse($table->columns['id']->autoIncrement); @@ -177,7 +178,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $result; } - public function testFindUniqueIndexes() + public function testFindUniqueIndexes(): void { if ($this->driverName === 'sqlsrv') { $this->markTestSkipped('`\yii\db\mssql\Schema::findUniqueIndexes()` returns only unique constraints not unique indexes.'); @@ -187,7 +188,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest try { $db->createCommand()->dropTable('uniqueIndex')->execute(); - } catch (\Exception $e) { + } catch (Exception $e) { } $db->createCommand()->createTable('uniqueIndex', [ 'somecol' => 'string', @@ -229,7 +230,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest ], $uniqueIndexes); } - public function testCompositeFk() + public function testCompositeFk(): void { $this->markTestSkipped('Should be fixed.'); } diff --git a/tests/framework/db/oci/UniqueValidatorTest.php b/tests/framework/db/oci/UniqueValidatorTest.php index 2ed63a7595..300002ff2d 100644 --- a/tests/framework/db/oci/UniqueValidatorTest.php +++ b/tests/framework/db/oci/UniqueValidatorTest.php @@ -20,7 +20,7 @@ class UniqueValidatorTest extends \yiiunit\framework\validators\UniqueValidatorT { public $driverName = 'oci'; - public function testValidateEmptyAttributeInStringField() + public function testValidateEmptyAttributeInStringField(): void { ValidatorTestMainModel::deleteAll(); diff --git a/tests/framework/db/pgsql/ActiveFixtureTest.php b/tests/framework/db/pgsql/ActiveFixtureTest.php index c00886c728..281874d55e 100644 --- a/tests/framework/db/pgsql/ActiveFixtureTest.php +++ b/tests/framework/db/pgsql/ActiveFixtureTest.php @@ -19,7 +19,7 @@ class ActiveFixtureTest extends \yiiunit\framework\test\ActiveFixtureTest { public $driverName = 'pgsql'; - public function testFixturesLoadingResetsSeqence() + public function testFixturesLoadingResetsSeqence(): void { $test = new CustomerDbTestCase(); $test->setUp(); diff --git a/tests/framework/db/pgsql/ActiveRecordTest.php b/tests/framework/db/pgsql/ActiveRecordTest.php index 67c8041128..1f6f32c407 100644 --- a/tests/framework/db/pgsql/ActiveRecordTest.php +++ b/tests/framework/db/pgsql/ActiveRecordTest.php @@ -27,7 +27,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { protected $driverName = 'pgsql'; - public function testBooleanAttribute() + public function testBooleanAttribute(): void { /** @var TestCase|ActiveRecordTestTrait $this */ @@ -55,7 +55,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertCount(1, $customers); } - public function testFindAsArray() + public function testFindAsArray(): void { /** @var ActiveRecordInterface $customerClass */ $customerClass = $this->getCustomerClass(); @@ -95,7 +95,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertArrayHasKey('bool_status', $customers[2]); } - public function testBooleanValues() + public function testBooleanValues(): void { $db = $this->getConnection(); $command = $db->createCommand(); @@ -126,7 +126,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest /** * @see https://github.com/yiisoft/yii2/issues/4672 */ - public function testBooleanValues2() + public function testBooleanValues2(): void { $db = $this->getConnection(); $db->charset = 'utf8'; @@ -159,7 +159,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertCount(1, UserAR::find()->where(['is_deleted' => [true, false]])->all($db)); } - public function testBooleanDefaultValues() + public function testBooleanDefaultValues(): void { $model = new BoolAR(); $this->assertNull($model->bool_col); @@ -173,7 +173,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertTrue($model->save(false)); } - public function testPrimaryKeyAfterSave() + public function testPrimaryKeyAfterSave(): void { $record = new DefaultPk(); $record->type = 'type'; @@ -184,7 +184,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest /** * @dataProvider arrayValuesProvider $attributes */ - public function testArrayValues($attributes) + public function testArrayValues($attributes): void { $type = new ArrayAndJsonTypes(); foreach ($attributes as $attribute => $expected) { diff --git a/tests/framework/db/pgsql/ArrayParserTest.php b/tests/framework/db/pgsql/ArrayParserTest.php index a58237ab4b..6aa8d6ba3d 100644 --- a/tests/framework/db/pgsql/ArrayParserTest.php +++ b/tests/framework/db/pgsql/ArrayParserTest.php @@ -39,7 +39,7 @@ class ArrayParserTest extends TestCase /** * @dataProvider convertProvider */ - public function testConvert($string, $expected) + public function testConvert($string, $expected): void { $this->assertSame($expected, $this->arrayParser->parse($string)); } diff --git a/tests/framework/db/pgsql/BaseActiveRecordTest.php b/tests/framework/db/pgsql/BaseActiveRecordTest.php index db6f126481..c0af29e83f 100644 --- a/tests/framework/db/pgsql/BaseActiveRecordTest.php +++ b/tests/framework/db/pgsql/BaseActiveRecordTest.php @@ -18,7 +18,7 @@ class BaseActiveRecordTest extends \yiiunit\framework\db\BaseActiveRecordTest * * @dataProvider provideArrayValueWithChange */ - public function testJsonDirtyAttributesWithDataChange($actual, $modified) + public function testJsonDirtyAttributesWithDataChange($actual, $modified): void { $createdStorage = new ArrayAndJsonType([ 'json_col' => new JsonExpression($actual), diff --git a/tests/framework/db/pgsql/CommandTest.php b/tests/framework/db/pgsql/CommandTest.php index 6357e9c2d8..23fe9f8026 100644 --- a/tests/framework/db/pgsql/CommandTest.php +++ b/tests/framework/db/pgsql/CommandTest.php @@ -19,7 +19,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest { public $driverName = 'pgsql'; - public function testAutoQuoting() + public function testAutoQuoting(): void { $db = $this->getConnection(false); @@ -28,7 +28,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('SELECT "id", "t"."name" FROM "customer" t', $command->sql); } - public function testBooleanValuesInsert() + public function testBooleanValuesInsert(): void { $db = $this->getConnection(); $command = $db->createCommand(); @@ -45,7 +45,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals(1, $command->queryScalar()); } - public function testBooleanValuesBatchInsert() + public function testBooleanValuesBatchInsert(): void { $db = $this->getConnection(); $command = $db->createCommand(); @@ -65,7 +65,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals(1, $command->queryScalar()); } - public function testLastInsertId() + public function testLastInsertId(): void { $db = $this->getConnection(); @@ -94,7 +94,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest /** * @see https://github.com/yiisoft/yii2/issues/11498 */ - public function testSaveSerializedObject() + public function testSaveSerializedObject(): void { if (\defined('HHVM_VERSION')) { $this->markTestSkipped('HHVMs PgSQL implementation does not seem to support blob colums in the way they are used here.'); @@ -157,7 +157,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest /** * @see https://github.com/yiisoft/yii2/issues/15827 */ - public function testIssue15827() + public function testIssue15827(): void { $db = $this->getConnection(); diff --git a/tests/framework/db/pgsql/ConnectionTest.php b/tests/framework/db/pgsql/ConnectionTest.php index a7fb939a36..73f141bbcc 100644 --- a/tests/framework/db/pgsql/ConnectionTest.php +++ b/tests/framework/db/pgsql/ConnectionTest.php @@ -18,12 +18,12 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { protected $driverName = 'pgsql'; - public function testConnection() + public function testConnection(): void { $this->assertIsObject($this->getConnection(true)); } - public function testQuoteValue() + public function testQuoteValue(): void { $connection = $this->getConnection(false); $this->assertEquals(123, $connection->quoteValue(123)); @@ -31,7 +31,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals("'It''s interesting'", $connection->quoteValue("It's interesting")); } - public function testQuoteTableName() + public function testQuoteTableName(): void { $connection = $this->getConnection(false); $this->assertEquals('"table"', $connection->quoteTableName('table')); @@ -43,7 +43,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('(table)', $connection->quoteTableName('(table)')); } - public function testQuoteColumnName() + public function testQuoteColumnName(): void { $connection = $this->getConnection(false); $this->assertEquals('"column"', $connection->quoteColumnName('column')); @@ -56,7 +56,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('"column"', $connection->quoteSql('{{column}}')); } - public function testQuoteFullColumnName() + public function testQuoteFullColumnName(): void { $connection = $this->getConnection(false, false); $this->assertEquals('"table"."column"', $connection->quoteColumnName('table.column')); @@ -78,7 +78,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals('"table"."column"', $connection->quoteSql('{{%table}}."column"')); } - public function testTransactionIsolation() + public function testTransactionIsolation(): void { $connection = $this->getConnection(true); diff --git a/tests/framework/db/pgsql/ExistValidatorTest.php b/tests/framework/db/pgsql/ExistValidatorTest.php index bb937830ae..968ec61933 100644 --- a/tests/framework/db/pgsql/ExistValidatorTest.php +++ b/tests/framework/db/pgsql/ExistValidatorTest.php @@ -22,7 +22,7 @@ class ExistValidatorTest extends \yiiunit\framework\validators\ExistValidatorTes /** * @see https://github.com/yiisoft/yii2/issues/14274 */ - public function testWithCameCasedTableName() + public function testWithCameCasedTableName(): void { // The same target table $validator = new ExistValidator(['targetAttribute' => 'ref']); diff --git a/tests/framework/db/pgsql/QueryBuilderTest.php b/tests/framework/db/pgsql/QueryBuilderTest.php index ee108070a0..501e7fe211 100644 --- a/tests/framework/db/pgsql/QueryBuilderTest.php +++ b/tests/framework/db/pgsql/QueryBuilderTest.php @@ -155,7 +155,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]); } - public function testAlterColumn() + public function testAlterColumn(): void { $qb = $this->getQueryBuilder(); @@ -211,12 +211,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $result; } - public function defaultValuesProvider() + public function defaultValuesProvider(): void { $this->markTestSkipped('Adding/dropping default constraints is not supported in PostgreSQL.'); } - public function testCommentColumn() + public function testCommentColumn(): void { $qb = $this->getQueryBuilder(); @@ -229,7 +229,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($this->replaceQuotes($expected), $sql); } - public function testCommentTable() + public function testCommentTable(): void { $qb = $this->getQueryBuilder(); @@ -253,7 +253,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $data; } - public function testResetSequence() + public function testResetSequence(): void { $qb = $this->getQueryBuilder(); @@ -266,7 +266,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expected, $sql); } - public function testResetSequencePostgres12() + public function testResetSequencePostgres12(): void { if (version_compare($this->getConnection(false)->getServerVersion(), '12.0', '<')) { $this->markTestSkipped('PostgreSQL < 12.0 does not support GENERATED AS IDENTITY columns.'); @@ -409,7 +409,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $items; } - public function testDropIndex() + public function testDropIndex(): void { $qb = $this->getQueryBuilder(); diff --git a/tests/framework/db/pgsql/QueryTest.php b/tests/framework/db/pgsql/QueryTest.php index df8d370840..830010136e 100644 --- a/tests/framework/db/pgsql/QueryTest.php +++ b/tests/framework/db/pgsql/QueryTest.php @@ -18,7 +18,7 @@ class QueryTest extends \yiiunit\framework\db\QueryTest { public $driverName = 'pgsql'; - public function testBooleanValues() + public function testBooleanValues(): void { $db = $this->getConnection(); $command = $db->createCommand(); diff --git a/tests/framework/db/pgsql/SchemaTest.php b/tests/framework/db/pgsql/SchemaTest.php index 66e7c5e84e..1fe2655cd2 100644 --- a/tests/framework/db/pgsql/SchemaTest.php +++ b/tests/framework/db/pgsql/SchemaTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\pgsql; +use PDO; use yii\db\Expression; use yiiunit\data\ar\ActiveRecord; use yiiunit\data\ar\EnumTypeInCustomSchema; @@ -163,7 +164,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $columns; } - public function testCompositeFk() + public function testCompositeFk(): void { $schema = $this->getConnection()->schema; @@ -176,18 +177,18 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertEquals('item_id', $table->foreignKeys['fk_composite_fk_order_item']['item_id']); } - public function testGetPDOType() + public function testGetPDOType(): void { $values = [ - [null, \PDO::PARAM_NULL], - ['', \PDO::PARAM_STR], - ['hello', \PDO::PARAM_STR], - [0, \PDO::PARAM_INT], - [1, \PDO::PARAM_INT], - [1337, \PDO::PARAM_INT], - [true, \PDO::PARAM_BOOL], - [false, \PDO::PARAM_BOOL], - [$fp = fopen(__FILE__, 'rb'), \PDO::PARAM_LOB], + [null, PDO::PARAM_NULL], + ['', PDO::PARAM_STR], + ['hello', PDO::PARAM_STR], + [0, PDO::PARAM_INT], + [1, PDO::PARAM_INT], + [1337, PDO::PARAM_INT], + [true, PDO::PARAM_BOOL], + [false, PDO::PARAM_BOOL], + [$fp = fopen(__FILE__, 'rb'), PDO::PARAM_LOB], ]; $schema = $this->getConnection()->schema; @@ -198,7 +199,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest fclose($fp); } - public function testBooleanDefaultValues() + public function testBooleanDefaultValues(): void { $schema = $this->getConnection()->schema; @@ -207,7 +208,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertFalse($table->getColumn('default_false')->defaultValue); } - public function testSequenceName() + public function testSequenceName(): void { $connection = $this->getConnection(); @@ -223,7 +224,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertEquals($sequenceName, $connection->schema->getTableSchema('item')->sequenceName); } - public function testGeneratedValues() + public function testGeneratedValues(): void { if (version_compare($this->getConnection(false)->getServerVersion(), '12.0', '<')) { $this->markTestSkipped('PostgreSQL < 12.0 does not support GENERATED AS IDENTITY columns.'); @@ -240,7 +241,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertTrue($table->getColumn('id_default')->autoIncrement); } - public function testPartitionedTable() + public function testPartitionedTable(): void { if (version_compare($this->getConnection(false)->getServerVersion(), '10.0', '<')) { $this->markTestSkipped('PostgreSQL < 10.0 does not support PARTITION BY clause.'); @@ -253,7 +254,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertNotNull($this->getConnection(false)->schema->getTableSchema('partitioned')); } - public function testFindSchemaNames() + public function testFindSchemaNames(): void { $schema = $this->getConnection()->schema; @@ -277,7 +278,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest * @dataProvider bigintValueProvider * @param int $bigint */ - public function testBigintValue($bigint) + public function testBigintValue($bigint): void { $this->mockApplication(); ActiveRecord::$db = $this->getConnection(); @@ -299,7 +300,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @see https://github.com/yiisoft/yii2/issues/12483 */ - public function testParenthesisDefaultValue() + public function testParenthesisDefaultValue(): void { $db = $this->getConnection(false); if ($db->schema->getTableSchema('test_default_parenthesis') !== null) { @@ -324,7 +325,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @see https://github.com/yiisoft/yii2/issues/14192 */ - public function testTimestampNullDefaultValue() + public function testTimestampNullDefaultValue(): void { $db = $this->getConnection(false); if ($db->schema->getTableSchema('test_timestamp_default_null') !== null) { @@ -344,7 +345,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @see https://github.com/yiisoft/yii2/issues/20329 */ - public function testTimestampUtcNowDefaultValue() + public function testTimestampUtcNowDefaultValue(): void { $db = $this->getConnection(false); if ($db->schema->getTableSchema('test_timestamp_utc_now_default') !== null) { @@ -364,7 +365,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @see https://github.com/yiisoft/yii2/issues/20329 */ - public function testTimestampNowDefaultValue() + public function testTimestampNowDefaultValue(): void { $db = $this->getConnection(false); if ($db->schema->getTableSchema('test_timestamp_now_default') !== null) { @@ -384,7 +385,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @see https://github.com/yiisoft/yii2/issues/20329 */ - public function testTimestampUtcStringDefaultValue() + public function testTimestampUtcStringDefaultValue(): void { $db = $this->getConnection(false); if ($db->schema->getTableSchema('test_timestamp_utc_string_default') !== null) { @@ -411,7 +412,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $result; } - public function testCustomTypeInNonDefaultSchema() + public function testCustomTypeInNonDefaultSchema(): void { $connection = $this->getConnection(); ActiveRecord::$db = $this->getConnection(); diff --git a/tests/framework/db/pgsql/UniqueValidatorTest.php b/tests/framework/db/pgsql/UniqueValidatorTest.php index df4817872d..d45480995f 100644 --- a/tests/framework/db/pgsql/UniqueValidatorTest.php +++ b/tests/framework/db/pgsql/UniqueValidatorTest.php @@ -20,7 +20,7 @@ class UniqueValidatorTest extends \yiiunit\framework\validators\UniqueValidatorT { public $driverName = 'pgsql'; - public function testPrepareParams() + public function testPrepareParams(): void { parent::testPrepareParams(); diff --git a/tests/framework/db/pgsql/type/BooleanTest.php b/tests/framework/db/pgsql/type/BooleanTest.php index 6d7e600f11..d4dcc4df19 100644 --- a/tests/framework/db/pgsql/type/BooleanTest.php +++ b/tests/framework/db/pgsql/type/BooleanTest.php @@ -19,7 +19,7 @@ class BooleanTest extends DatabaseTestCase { protected $driverName = 'pgsql'; - public function testBoolean() + public function testBoolean(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -60,7 +60,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCast); } - public function testBooleanWithValueInteger() + public function testBooleanWithValueInteger(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -101,7 +101,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCast); } - public function testBooleanWithValueNegative() + public function testBooleanWithValueNegative(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -133,7 +133,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCast); } - public function testBooleanWithValueNull() + public function testBooleanWithValueNull(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -165,7 +165,7 @@ class BooleanTest extends DatabaseTestCase $this->assertNull($phpTypeCast); } - public function testBooleanWithValueOverflow() + public function testBooleanWithValueOverflow(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -197,7 +197,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCast); } - public function testBooleanWithValueString() + public function testBooleanWithValueString(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); diff --git a/tests/framework/db/sqlite/CommandTest.php b/tests/framework/db/sqlite/CommandTest.php index ea31986b02..20ebbf789f 100644 --- a/tests/framework/db/sqlite/CommandTest.php +++ b/tests/framework/db/sqlite/CommandTest.php @@ -18,7 +18,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest { protected $driverName = 'sqlite'; - public function testAutoQuoting() + public function testAutoQuoting(): void { $db = $this->getConnection(false); @@ -32,7 +32,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest * @param array $firstData * @param array $secondData */ - public function testUpsert(array $firstData, array $secondData) + public function testUpsert(array $firstData, array $secondData): void { if (version_compare($this->getConnection(false)->getServerVersion(), '3.8.3', '<')) { $this->markTestSkipped('SQLite < 3.8.3 does not support "WITH" keyword.'); @@ -42,27 +42,27 @@ class CommandTest extends \yiiunit\framework\db\CommandTest parent::testUpsert($firstData, $secondData); } - public function testAddDropPrimaryKey() + public function testAddDropPrimaryKey(): void { $this->markTestSkipped('SQLite does not support adding/dropping primary keys.'); } - public function testAddDropForeignKey() + public function testAddDropForeignKey(): void { $this->markTestSkipped('SQLite does not support adding/dropping foreign keys.'); } - public function testAddDropUnique() + public function testAddDropUnique(): void { $this->markTestSkipped('SQLite does not support adding/dropping unique constraints.'); } - public function testAddDropCheck() + public function testAddDropCheck(): void { $this->markTestSkipped('SQLite does not support adding/dropping check constraints.'); } - public function testMultiStatementSupport() + public function testMultiStatementSupport(): void { $db = $this->getConnection(false); $sql = <<<'SQL' @@ -113,7 +113,7 @@ SQL; return $parent; } - public function testResetSequence() + public function testResetSequence(): void { $db = $this->getConnection(); @@ -151,7 +151,7 @@ SQL; $this->assertEquals(5, $db->createCommand('SELECT MAX([[id]]) FROM {{reset_sequence}}')->queryScalar()); } - public function testResetSequenceExceptionTableNoExist() + public function testResetSequenceExceptionTableNoExist(): void { $this->expectException('yii\base\InvalidArgumentException'); $this->expectExceptionMessage('Table not found: no_exist_table'); @@ -160,7 +160,7 @@ SQL; $db->createCommand()->resetSequence('no_exist_table', 5)->execute(); } - public function testResetSequenceExceptionSquenceNoExist() + public function testResetSequenceExceptionSquenceNoExist(): void { $this->expectException('yii\base\InvalidArgumentException'); $this->expectExceptionMessage("There is not sequence associated with table 'type'."); diff --git a/tests/framework/db/sqlite/ConnectionTest.php b/tests/framework/db/sqlite/ConnectionTest.php index 4b39055997..8874a23730 100644 --- a/tests/framework/db/sqlite/ConnectionTest.php +++ b/tests/framework/db/sqlite/ConnectionTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\db\sqlite; +use Exception; +use Yii; use yii\db\Connection; use yii\db\Transaction; use yiiunit\data\ar\ActiveRecord; @@ -21,7 +23,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { protected $driverName = 'sqlite'; - public function testConstruct() + public function testConstruct(): void { $connection = $this->getConnection(false); $params = $this->database; @@ -29,7 +31,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals($params['dsn'], $connection->dsn); } - public function testQuoteValue() + public function testQuoteValue(): void { $connection = $this->getConnection(false); $this->assertEquals(123, $connection->quoteValue(123)); @@ -37,7 +39,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertEquals("'It''s interesting'", $connection->quoteValue("It's interesting")); } - public function testTransactionIsolation() + public function testTransactionIsolation(): void { $connection = $this->getConnection(true); @@ -50,7 +52,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertTrue(true); // No exceptions means test is passed. } - public function testMasterSlave() + public function testMasterSlave(): void { $counts = [[0, 2], [1, 2], [2, 2]]; @@ -104,7 +106,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest } } - public function testMastersShuffled() + public function testMastersShuffled(): void { $mastersCount = 2; $slavesCount = 2; @@ -129,7 +131,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertCount($slavesCount, $hit_slaves, 'all slaves hit'); } - public function testMastersSequential() + public function testMastersSequential(): void { $mastersCount = 2; $slavesCount = 2; @@ -155,16 +157,16 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $this->assertCount($slavesCount, $hit_slaves, 'all slaves hit'); } - public function testRestoreMasterAfterException() + public function testRestoreMasterAfterException(): void { $db = $this->prepareMasterSlave(1, 1); $this->assertTrue($db->enableSlaves); try { $db->useMaster(function (Connection $db) { - throw new \Exception('fail'); + throw new Exception('fail'); }); $this->fail('Exception was caught somewhere'); - } catch (\Exception $e) { + } catch (Exception $e) { // ok } $this->assertTrue($db->enableSlaves); @@ -179,7 +181,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { $databases = self::getParam('databases'); $fixture = $databases[$this->driverName]['fixture']; - $basePath = \Yii::getAlias('@yiiunit/runtime'); + $basePath = Yii::getAlias('@yiiunit/runtime'); $config = [ 'class' => 'yii\db\Connection', @@ -201,10 +203,10 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $config['slaves'][] = $slave; } - return \Yii::createObject($config); + return Yii::createObject($config); } - public function testAliasDbPath() + public function testAliasDbPath(): void { $config = [ 'dsn' => 'sqlite:@yiiunit/runtime/yii2aliastest.sq3', @@ -217,7 +219,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $connection->close(); } - public function testExceptionContainsRawQuery() + public function testExceptionContainsRawQuery(): void { $this->markTestSkipped('This test does not work on sqlite because preparing the failing query fails'); } diff --git a/tests/framework/db/sqlite/QueryBuilderTest.php b/tests/framework/db/sqlite/QueryBuilderTest.php index 0f0889ac42..4c6f716a86 100644 --- a/tests/framework/db/sqlite/QueryBuilderTest.php +++ b/tests/framework/db/sqlite/QueryBuilderTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\sqlite; +use PDO; use yii\db\Query; use yii\db\Schema; use yii\db\sqlite\QueryBuilder; @@ -53,12 +54,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]); } - public function primaryKeysProvider() + public function primaryKeysProvider(): void { $this->markTestSkipped('Adding/dropping primary keys is not supported in SQLite.'); } - public function foreignKeysProvider() + public function foreignKeysProvider(): void { $this->markTestSkipped('Adding/dropping foreign keys is not supported in SQLite.'); } @@ -82,27 +83,27 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $result; } - public function uniquesProvider() + public function uniquesProvider(): void { $this->markTestSkipped('Adding/dropping unique constraints is not supported in SQLite.'); } - public function checksProvider() + public function checksProvider(): void { $this->markTestSkipped('Adding/dropping check constraints is not supported in SQLite.'); } - public function defaultValuesProvider() + public function defaultValuesProvider(): void { $this->markTestSkipped('Adding/dropping default constraints is not supported in SQLite.'); } - public function testCommentColumn() + public function testCommentColumn(): void { $this->markTestSkipped('Comments are not supported in SQLite'); } - public function testCommentTable() + public function testCommentTable(): void { $this->markTestSkipped('Comments are not supported in SQLite'); } @@ -114,17 +115,17 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $data; } - public function testBatchInsertOnOlderVersions() + public function testBatchInsertOnOlderVersions(): void { $db = $this->getConnection(); - if (version_compare($db->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '3.7.11', '>=')) { + if (version_compare($db->pdo->getAttribute(PDO::ATTR_SERVER_VERSION), '3.7.11', '>=')) { $this->markTestSkipped('This test is only relevant for SQLite < 3.7.11'); } $sql = $this->getQueryBuilder()->batchInsert('{{customer}} t', ['t.id', 't.name'], [[1, 'a'], [2, 'b']]); $this->assertEquals("INSERT INTO {{customer}} t (`t`.`id`, `t`.`name`) SELECT 1, 'a' UNION SELECT 2, 'b'", $sql); } - public function testRenameTable() + public function testRenameTable(): void { $sql = $this->getQueryBuilder()->renameTable('table_from', 'table_to'); $this->assertEquals('ALTER TABLE `table_from` RENAME TO `table_to`', $sql); @@ -133,7 +134,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest /** * {@inheritdoc} */ - public function testBuildUnion() + public function testBuildUnion(): void { $expectedQuerySql = $this->replaceQuotes( 'SELECT `id` FROM `TotalExample` `t1` WHERE (w > 0) AND (x < 2) UNION SELECT `id` FROM `TotalTotalExample` `t2` WHERE w > 5 UNION ALL SELECT `id` FROM `TotalTotalExample` `t3` WHERE w = 3' @@ -157,7 +158,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals([], $queryParams); } - public function testBuildWithQuery() + public function testBuildWithQuery(): void { $expectedQuerySql = $this->replaceQuotes( 'WITH a1 AS (SELECT [[id]] FROM [[t1]] WHERE expr = 1), a2 AS (SELECT [[id]] FROM [[t2]] INNER JOIN [[a1]] ON t2.id = a1.id WHERE expr = 2 UNION SELECT [[id]] FROM [[t3]] WHERE expr = 3) SELECT * FROM [[a2]]' @@ -188,7 +189,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals([], $queryParams); } - public function testResetSequence() + public function testResetSequence(): void { $qb = $this->getQueryBuilder(true, true); diff --git a/tests/framework/db/sqlite/QueryTest.php b/tests/framework/db/sqlite/QueryTest.php index 67c5873960..47baf7f0e4 100644 --- a/tests/framework/db/sqlite/QueryTest.php +++ b/tests/framework/db/sqlite/QueryTest.php @@ -18,7 +18,7 @@ class QueryTest extends \yiiunit\framework\db\QueryTest { protected $driverName = 'sqlite'; - public function testUnion() + public function testUnion(): void { $connection = $this->getConnection(); $query = new Query(); diff --git a/tests/framework/db/sqlite/SchemaTest.php b/tests/framework/db/sqlite/SchemaTest.php index b4ca70e685..2786e6c110 100644 --- a/tests/framework/db/sqlite/SchemaTest.php +++ b/tests/framework/db/sqlite/SchemaTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\db\sqlite; +use yii\base\NotSupportedException; use yii\db\Constraint; use yiiunit\framework\db\AnyValue; @@ -19,7 +20,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest { protected $driverName = 'sqlite'; - public function testGetSchemaNames() + public function testGetSchemaNames(): void { $this->markTestSkipped('Schemas are not supported in SQLite.'); } @@ -44,7 +45,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $columns; } - public function testCompositeFk() + public function testCompositeFk(): void { $schema = $this->getConnection()->schema; @@ -88,9 +89,9 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest * @dataProvider quoteTableNameDataProvider * @param $name * @param $expectedName - * @throws \yii\base\NotSupportedException + * @throws NotSupportedException */ - public function testQuoteTableName($name, $expectedName) + public function testQuoteTableName($name, $expectedName): void { $schema = $this->getConnection()->getSchema(); $quotedName = $schema->quoteTableName($name); diff --git a/tests/framework/db/sqlite/SqlTokenizerTest.php b/tests/framework/db/sqlite/SqlTokenizerTest.php index e870f5e45e..f1acd34ef8 100644 --- a/tests/framework/db/sqlite/SqlTokenizerTest.php +++ b/tests/framework/db/sqlite/SqlTokenizerTest.php @@ -1122,7 +1122,7 @@ SELECT*from/*foo*/`T_constraints_1`WHERE not`C_check`=\'foo\'\'bar\'--bar * @dataProvider sqlProvider * @param string $sql */ - public function testTokenizer($sql, SqlToken $expectedToken) + public function testTokenizer($sql, SqlToken $expectedToken): void { $actualToken = (new SqlTokenizer($sql))->tokenize(); $this->assertEquals($expectedToken, $actualToken); diff --git a/tests/framework/db/sqlite/type/BooleanTest.php b/tests/framework/db/sqlite/type/BooleanTest.php index 128c4afb5e..c56a4efea4 100644 --- a/tests/framework/db/sqlite/type/BooleanTest.php +++ b/tests/framework/db/sqlite/type/BooleanTest.php @@ -19,7 +19,7 @@ class BooleanTest extends DatabaseTestCase { protected $driverName = 'sqlite'; - public function testBoolean() + public function testBoolean(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -72,7 +72,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCastBoolColBit); } - public function testBooleanWithValueInteger() + public function testBooleanWithValueInteger(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -125,7 +125,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCastBoolColBit); } - public function testBooleanWithValueNegative() + public function testBooleanWithValueNegative(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -166,7 +166,7 @@ class BooleanTest extends DatabaseTestCase $this->assertTrue($phpTypeCastBoolColBit); } - public function testBooleanWithValueNull() + public function testBooleanWithValueNull(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); @@ -207,7 +207,7 @@ class BooleanTest extends DatabaseTestCase $this->assertNull($phpTypeCastBoolColBit); } - public function testBooleanWithValueOverflow() + public function testBooleanWithValueOverflow(): void { $db = $this->getConnection(true); $schema = $db->getSchema(); diff --git a/tests/framework/db/testBatchInsertWithYield.php b/tests/framework/db/testBatchInsertWithYield.php index 26548156a0..840ea2f8d8 100644 --- a/tests/framework/db/testBatchInsertWithYield.php +++ b/tests/framework/db/testBatchInsertWithYield.php @@ -1,13 +1,14 @@ assertEquals(4, $qux->a); } - public function testInvoke() + public function testInvoke(): void { $this->mockApplication([ 'components' => [ @@ -160,21 +165,21 @@ class ContainerTest extends TestCase ]); // use component of application - $callback = function ($param, stubs\QuxInterface $qux, Bar $bar) { + $callback = function ($param, QuxInterface $qux, Bar $bar) { return [$param, $qux instanceof Qux, $qux->a, $bar->qux->a]; }; $result = Yii::$container->invoke($callback, ['D426']); $this->assertEquals(['D426', true, 'belongApp', 'independent'], $result); // another component of application - $callback = function ($param, stubs\QuxInterface $qux2, $other = 'default') { + $callback = function ($param, QuxInterface $qux2, $other = 'default') { return [$param, $qux2 instanceof Qux, $qux2->a, $other]; }; $result = Yii::$container->invoke($callback, ['M2792684']); $this->assertEquals(['M2792684', true, 'belongAppQux2', 'default'], $result); // component not belong application - $callback = function ($param, stubs\QuxInterface $notBelongApp, $other) { + $callback = function ($param, QuxInterface $notBelongApp, $other) { return [$param, $notBelongApp instanceof Qux, $notBelongApp->a, $other]; }; $result = Yii::$container->invoke($callback, ['MDM', 'not_default']); @@ -198,7 +203,7 @@ class ContainerTest extends TestCase $this->assertFalse(Yii::$container->invoke(['yii\helpers\ArrayHelper', 'isAssociative'], [$array])); - $myFunc = function (\yii\console\Request $request, \yii\console\Response $response) { + $myFunc = function (Request $request, Response $response) { return [$request, $response]; }; list($request, $response) = Yii::$container->invoke($myFunc); @@ -206,7 +211,7 @@ class ContainerTest extends TestCase $this->assertEquals($response, Yii::$app->response); } - public function testAssociativeInvoke() + public function testAssociativeInvoke(): void { $this->mockApplication([ 'components' => [ @@ -227,7 +232,7 @@ class ContainerTest extends TestCase $this->assertTrue(Yii::$container->invoke($closure, ['b' => 1, 'a' => 5])); } - public function testResolveCallableDependencies() + public function testResolveCallableDependencies(): void { $this->mockApplication([ 'components' => [ @@ -249,7 +254,7 @@ class ContainerTest extends TestCase $this->assertEquals([1, 5], Yii::$container->resolveCallableDependencies($closure, [1, 5])); } - public function testOptionalDependencies() + public function testOptionalDependencies(): void { $container = new Container(); // Test optional unresolvable dependency. @@ -259,7 +264,7 @@ class ContainerTest extends TestCase $this->assertNull($container->invoke($closure)); } - public function testSetDependencies() + public function testSetDependencies(): void { $container = new Container(); $container->setDefinitions([ @@ -289,12 +294,12 @@ class ContainerTest extends TestCase try { $container->get('rollbar'); $this->fail('InvalidConfigException was not thrown'); - } catch (\Exception $e) { + } catch (Exception $e) { $this->assertInstanceOf('yii\base\InvalidConfigException', $e); } } - public function testStaticCall() + public function testStaticCall(): void { $container = new Container(); $container->setDefinitions([ @@ -306,7 +311,7 @@ class ContainerTest extends TestCase $this->assertSame(42, $qux->a); } - public function testObject() + public function testObject(): void { $container = new Container(); $container->setDefinitions([ @@ -318,7 +323,7 @@ class ContainerTest extends TestCase $this->assertSame(42, $qux->a); } - public function testDi3Compatibility() + public function testDi3Compatibility(): void { $container = new Container(); $container->setDefinitions([ @@ -341,7 +346,7 @@ class ContainerTest extends TestCase $this->assertEquals('item1', $traversable->current()); } - public function testInstanceOf() + public function testInstanceOf(): void { $container = new Container(); $container->setDefinitions([ @@ -363,7 +368,7 @@ class ContainerTest extends TestCase $this->assertSame(42, $qux->a); } - public function testReferencesInArrayInDependencies() + public function testReferencesInArrayInDependencies(): void { $quxInterface = 'yiiunit\framework\di\stubs\QuxInterface'; $container = new Container(); @@ -401,7 +406,7 @@ class ContainerTest extends TestCase $this->assertSame(33, $q33->a); } - public function testGetByInstance() + public function testGetByInstance(): void { $container = new Container(); $container->setSingletons([ @@ -416,7 +421,7 @@ class ContainerTest extends TestCase $this->assertSame($one, $container->get('two')); } - public function testWithoutDefinition() + public function testWithoutDefinition(): void { $container = new Container(); @@ -429,7 +434,7 @@ class ContainerTest extends TestCase $this->assertNotSame($one, $two); } - public function testGetByClassIndirectly() + public function testGetByClassIndirectly(): void { $container = new Container(); $container->setSingletons([ @@ -444,15 +449,15 @@ class ContainerTest extends TestCase $this->assertSame(42, $qux->a); } - public function testThrowingNotFoundException() + public function testThrowingNotFoundException(): void { - $this->expectException(\yii\di\NotInstantiableException::class); + $this->expectException(NotInstantiableException::class); $container = new Container(); $container->get('non_existing'); } - public function testContainerSingletons() + public function testContainerSingletons(): void { $container = new Container(); $container->setSingletons([ @@ -480,7 +485,7 @@ class ContainerTest extends TestCase $this->assertSame($foo, $sameFoo); } - public function testVariadicConstructor() + public function testVariadicConstructor(): void { if (\defined('HHVM_VERSION')) { static::markTestSkipped('Can not test on HHVM because it does not support variadics.'); @@ -492,7 +497,7 @@ class ContainerTest extends TestCase $this->assertTrue(true); } - public function testVariadicCallable() + public function testVariadicCallable(): void { if (\defined('HHVM_VERSION')) { static::markTestSkipped('Can not test on HHVM because it does not support variadics.'); @@ -506,7 +511,7 @@ class ContainerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/18245 */ - public function testDelayedInitializationOfSubArray() + public function testDelayedInitializationOfSubArray(): void { $definitions = [ 'test' => [ @@ -518,7 +523,7 @@ class ContainerTest extends TestCase ]; $application = Yii::createObject([ - '__class' => \yii\web\Application::className(), + '__class' => Application::className(), 'basePath' => __DIR__, 'id' => 'test', 'components' => [ @@ -540,7 +545,7 @@ class ContainerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/18304 */ - public function testNulledConstructorParameters() + public function testNulledConstructorParameters(): void { $alpha = (new Container())->get(Alpha::className()); $this->assertInstanceOf(Beta::className(), $alpha->beta); @@ -564,7 +569,7 @@ class ContainerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/18284 */ - public function testNamedConstructorParameters() + public function testNamedConstructorParameters(): void { $test = (new Container())->get(Car::className(), [ 'name' => 'Hello', @@ -577,7 +582,7 @@ class ContainerTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/18284 */ - public function testInvalidConstructorParameters() + public function testInvalidConstructorParameters(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Dependencies indexed by name and by position in the same array are not allowed.'); @@ -602,13 +607,13 @@ class ContainerTest extends TestCase * * @param string $class */ - public function testNotInstantiableException($class) + public function testNotInstantiableException($class): void { $this->expectException('yii\di\NotInstantiableException'); (new Container())->get($class); } - public function testNullTypeConstructorParameters() + public function testNullTypeConstructorParameters(): void { $zeta = (new Container())->get(Zeta::className()); $this->assertInstanceOf(Beta::className(), $zeta->beta); @@ -621,7 +626,7 @@ class ContainerTest extends TestCase $this->assertNull($zeta->unknownNull); } - public function testUnionTypeWithNullConstructorParameters() + public function testUnionTypeWithNullConstructorParameters(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Can not be tested on PHP < 8.0'); @@ -632,7 +637,7 @@ class ContainerTest extends TestCase $this->assertInstanceOf(UnionTypeNull::className(), $unionType); } - public function testUnionTypeWithoutNullConstructorParameters() + public function testUnionTypeWithoutNullConstructorParameters(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Can not be tested on PHP < 8.0'); @@ -655,7 +660,7 @@ class ContainerTest extends TestCase (new Container())->get(UnionTypeNotNull::className()); } - public function testUnionTypeWithClassConstructorParameters() + public function testUnionTypeWithClassConstructorParameters(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Can not be tested on PHP < 8.0'); @@ -670,7 +675,7 @@ class ContainerTest extends TestCase (new Container())->get(UnionTypeNotNull::className()); } - public function testResolveCallableDependenciesUnionTypes() + public function testResolveCallableDependenciesUnionTypes(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Can not be tested on PHP < 8.0'); @@ -702,7 +707,7 @@ class ContainerTest extends TestCase $this->assertInstanceOf(Qux::classname(), $params[0]); } - public function testResolveCallableDependenciesIntersectionTypes() + public function testResolveCallableDependenciesIntersectionTypes(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Can not be tested on PHP < 8.1'); diff --git a/tests/framework/di/InstanceTest.php b/tests/framework/di/InstanceTest.php index 14483d922f..beb2574b93 100644 --- a/tests/framework/di/InstanceTest.php +++ b/tests/framework/di/InstanceTest.php @@ -28,7 +28,7 @@ class InstanceTest extends TestCase Yii::$container = new Container(); } - public function testOf() + public function testOf(): void { $container = new Container(); $className = Component::className(); @@ -40,7 +40,7 @@ class InstanceTest extends TestCase $this->assertNotSame($instance->get($container), Instance::ensure($instance, $className, $container)); } - public function testEnsure() + public function testEnsure(): void { $container = new Container(); $container->set('db', [ @@ -57,7 +57,7 @@ class InstanceTest extends TestCase /** * ensure an InvalidConfigException is thrown when a component does not exist. */ - public function testEnsure_NonExistingComponentException() + public function testEnsure_NonExistingComponentException(): void { $container = new Container(); $this->expectException('yii\base\InvalidConfigException'); @@ -68,7 +68,7 @@ class InstanceTest extends TestCase /** * ensure an InvalidConfigException is thrown when a class does not exist. */ - public function testEnsure_NonExistingClassException() + public function testEnsure_NonExistingClassException(): void { $container = new Container(); $this->expectException('yii\base\InvalidConfigException'); @@ -76,7 +76,7 @@ class InstanceTest extends TestCase Instance::ensure('yii\cache\DoesNotExist', 'yii\cache\Cache', $container); } - public function testEnsure_WithoutType() + public function testEnsure_WithoutType(): void { $container = new Container(); $container->set('db', [ @@ -89,7 +89,7 @@ class InstanceTest extends TestCase $this->assertInstanceOf('\\yii\\db\\Connection', Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'], null, $container)); } - public function testEnsure_MinimalSettings() + public function testEnsure_MinimalSettings(): void { Yii::$container->set('db', [ 'class' => 'yii\db\Connection', @@ -103,7 +103,7 @@ class InstanceTest extends TestCase Yii::$container = new Container(); } - public function testExceptionRefersTo() + public function testExceptionRefersTo(): void { $container = new Container(); $container->set('db', [ @@ -117,21 +117,21 @@ class InstanceTest extends TestCase Instance::ensure('db', 'yii\base\Widget', $container); } - public function testExceptionInvalidDataType() + public function testExceptionInvalidDataType(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Invalid data type: yii\db\Connection. yii\base\Widget is expected.'); Instance::ensure(new Connection(), 'yii\base\Widget'); } - public function testExceptionComponentIsNotSpecified() + public function testExceptionComponentIsNotSpecified(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('The required component is not specified.'); Instance::ensure(''); } - public function testGet() + public function testGet(): void { $this->mockApplication([ 'components' => [ @@ -152,7 +152,7 @@ class InstanceTest extends TestCase /** * This tests the usage example given in yii\di\Instance class PHPDoc. */ - public function testLazyInitializationExample() + public function testLazyInitializationExample(): void { Yii::$container = new Container(); Yii::$container->set('cache', [ @@ -169,7 +169,7 @@ class InstanceTest extends TestCase $this->assertEquals('sqlite:path/to/file.db', $db->dsn); } - public function testRestoreAfterVarExport() + public function testRestoreAfterVarExport(): void { $instance = Instance::of('something'); $export = var_export($instance, true); @@ -184,7 +184,7 @@ class InstanceTest extends TestCase ])); } - public function testRestoreAfterVarExportRequiresId() + public function testRestoreAfterVarExportRequiresId(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Failed to instantiate class "Instance". Required parameter "id" is missing'); @@ -192,7 +192,7 @@ class InstanceTest extends TestCase Instance::__set_state([]); } - public function testExceptionInvalidDataTypeInArray() + public function testExceptionInvalidDataTypeInArray(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Invalid data type: yii\db\Connection. yii\base\Widget is expected.'); diff --git a/tests/framework/di/ServiceLocatorTest.php b/tests/framework/di/ServiceLocatorTest.php index f3c1fdfb00..5e70ddee35 100644 --- a/tests/framework/di/ServiceLocatorTest.php +++ b/tests/framework/di/ServiceLocatorTest.php @@ -37,7 +37,7 @@ class TestSubclass extends TestClass */ class ServiceLocatorTest extends TestCase { - public function testCallable() + public function testCallable(): void { // anonymous function $container = new ServiceLocator(); @@ -63,7 +63,7 @@ class ServiceLocatorTest extends TestCase $this->assertNull($object->prop2); } - public function testObject() + public function testObject(): void { $object = new TestClass(); $className = TestClass::className(); @@ -72,7 +72,7 @@ class ServiceLocatorTest extends TestCase $this->assertSame($container->get($className), $object); } - public function testDi3Compatibility() + public function testDi3Compatibility(): void { $config = [ 'components' => [ @@ -89,7 +89,7 @@ class ServiceLocatorTest extends TestCase $this->assertInstanceOf(TestSubclass::className(), $app->get('test')); } - public function testShared() + public function testShared(): void { // with configuration: shared $container = new ServiceLocator(); @@ -112,7 +112,7 @@ class ServiceLocatorTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/11771 */ - public function testModulePropertyIsset() + public function testModulePropertyIsset(): void { $config = [ 'components' => [ diff --git a/tests/framework/di/stubs/BarSetter.php b/tests/framework/di/stubs/BarSetter.php index c45b3b3cf8..858b943141 100644 --- a/tests/framework/di/stubs/BarSetter.php +++ b/tests/framework/di/stubs/BarSetter.php @@ -34,7 +34,7 @@ class BarSetter extends BaseObject /** * @param mixed $qux */ - public function setQux(QuxInterface $qux) + public function setQux(QuxInterface $qux): void { $this->qux = $qux; } diff --git a/tests/framework/di/stubs/FooBaz.php b/tests/framework/di/stubs/FooBaz.php index cc4426f511..ab1312de1e 100644 --- a/tests/framework/di/stubs/FooBaz.php +++ b/tests/framework/di/stubs/FooBaz.php @@ -8,23 +8,26 @@ namespace yiiunit\framework\di\stubs; +use yii\base\BaseObject; +use Yii; + /** * @author Yusup Hambali * @since 2.0.31 */ -class FooBaz extends \yii\base\BaseObject +class FooBaz extends BaseObject { public $fooDependent = []; - public function init() + public function init(): void { // default config usually used by Yii $dependentConfig = array_merge(['class' => FooDependent::className()], $this->fooDependent); - $this->fooDependent = \Yii::createObject($dependentConfig); + $this->fooDependent = Yii::createObject($dependentConfig); } } -class FooDependent extends \yii\base\BaseObject +class FooDependent extends BaseObject { } diff --git a/tests/framework/di/stubs/QuxFactory.php b/tests/framework/di/stubs/QuxFactory.php index 1cee9798cf..43d377fe8d 100644 --- a/tests/framework/di/stubs/QuxFactory.php +++ b/tests/framework/di/stubs/QuxFactory.php @@ -8,9 +8,10 @@ namespace yiiunit\framework\di\stubs; +use yii\base\BaseObject; use yii\di\Container; -class QuxFactory extends \yii\base\BaseObject +class QuxFactory extends BaseObject { public static function create(Container $container) { diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index 243db417f6..ac1ae38d3f 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\filters; +use yiiunit\TestCase; +use yii\rbac\BaseManager; use Closure; use Yii; use yii\base\Action; @@ -22,7 +24,7 @@ use yiiunit\framework\rbac\AuthorRule; /** * @group filters */ -class AccessRuleTest extends \yiiunit\TestCase +class AccessRuleTest extends TestCase { protected function setUp(): void { @@ -76,7 +78,7 @@ class AccessRuleTest extends \yiiunit\TestCase } /** - * @return \yii\rbac\BaseManager + * @return BaseManager */ protected function mockAuthManager() { @@ -121,7 +123,7 @@ class AccessRuleTest extends \yiiunit\TestCase return $auth; } - public function testMatchAction() + public function testMatchAction(): void { $action = $this->mockAction(); $user = false; @@ -149,7 +151,7 @@ class AccessRuleTest extends \yiiunit\TestCase $this->assertNull($rule->allows($action, $user, $request)); } - public function testMatchController() + public function testMatchController(): void { $action = $this->mockAction(); $user = false; @@ -181,7 +183,7 @@ class AccessRuleTest extends \yiiunit\TestCase /** * @depends testMatchController */ - public function testMatchControllerWildcard() + public function testMatchControllerWildcard(): void { $action = $this->mockAction(); $user = false; @@ -310,7 +312,7 @@ class AccessRuleTest extends \yiiunit\TestCase * @param array|Closure $roleParams params for $roleParams * @param bool $expected the expected result or null */ - public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected) + public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected): void { $action = $this->mockAction(); $auth = $this->mockAuthManager(); @@ -335,7 +337,7 @@ class AccessRuleTest extends \yiiunit\TestCase * * @see https://github.com/yiisoft/yii2/issues/4793 */ - public function testMatchRoleWithoutUser() + public function testMatchRoleWithoutUser(): void { $action = $this->mockAction(); $request = $this->mockRequest(); @@ -349,7 +351,7 @@ class AccessRuleTest extends \yiiunit\TestCase $rule->allows($action, false, $request); } - public function testMatchRoleSpecial() + public function testMatchRoleSpecial(): void { $action = $this->mockAction(); $request = $this->mockRequest(); @@ -375,7 +377,7 @@ class AccessRuleTest extends \yiiunit\TestCase $this->assertTrue($rule->allows($action, $guest, $request)); } - public function testMatchRolesAndPermissions() + public function testMatchRolesAndPermissions(): void { $action = $this->mockAction(); $user = $this->getMockBuilder('\yii\web\User')->getMock(); @@ -415,7 +417,7 @@ class AccessRuleTest extends \yiiunit\TestCase /** * Test that callable object can be used as roleParams values */ - public function testMatchRoleWithRoleParamsCallable() + public function testMatchRoleWithRoleParamsCallable(): void { $action = $this->mockAction(); $action->id = 'update'; @@ -436,7 +438,7 @@ class AccessRuleTest extends \yiiunit\TestCase $this->assertEquals(true, $rule->allows($action, $user, $request)); } - public function testMatchVerb() + public function testMatchVerb(): void { $action = $this->mockAction(); $user = false; @@ -467,7 +469,7 @@ class AccessRuleTest extends \yiiunit\TestCase // TODO test match custom callback - public function testMatchIP() + public function testMatchIP(): void { $action = $this->mockAction(); $user = false; @@ -567,7 +569,7 @@ class AccessRuleTest extends \yiiunit\TestCase $this->assertNull($rule->allows($action, $user, $request)); } - public function testMatchIPWildcard() + public function testMatchIPWildcard(): void { $action = $this->mockAction(); $user = false; @@ -611,7 +613,7 @@ class AccessRuleTest extends \yiiunit\TestCase $this->assertNull($rule->allows($action, $user, $request)); } - public function testMatchIPMask() + public function testMatchIPMask(): void { $action = $this->mockAction(); $user = false; diff --git a/tests/framework/filters/AjaxFilterTest.php b/tests/framework/filters/AjaxFilterTest.php index b15efe59d6..19fb045d0d 100644 --- a/tests/framework/filters/AjaxFilterTest.php +++ b/tests/framework/filters/AjaxFilterTest.php @@ -35,7 +35,7 @@ class AjaxFilterTest extends TestCase return $request; } - public function testFilter() + public function testFilter(): void { $this->mockWebApplication(); $controller = new Controller('id', Yii::$app); diff --git a/tests/framework/filters/ContentNegotiatorTest.php b/tests/framework/filters/ContentNegotiatorTest.php index 3365e78292..79df9402ce 100644 --- a/tests/framework/filters/ContentNegotiatorTest.php +++ b/tests/framework/filters/ContentNegotiatorTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\filters; +use yii\web\BadRequestHttpException; use Yii; use yii\base\Action; use yii\filters\ContentNegotiator; @@ -39,7 +40,7 @@ class ContentNegotiatorTest extends TestCase return [$action, $filter]; } - public function testWhenLanguageGETParamIsArray() + public function testWhenLanguageGETParamIsArray(): void { list($action, $filter) = $this->mockActionAndFilter(); @@ -56,7 +57,7 @@ class ContentNegotiatorTest extends TestCase $this->assertEquals($targetLanguage, Yii::$app->language); } - public function testWhenFormatGETParamIsArray() + public function testWhenFormatGETParamIsArray(): void { list($action, $filter) = $this->mockActionAndFilter(); @@ -71,13 +72,13 @@ class ContentNegotiatorTest extends TestCase 'application/xml' => Response::FORMAT_XML, ]; - $this->expectException(\yii\web\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('Invalid data received for GET parameter'); $filter->beforeAction($action); } - public function testVaryHeader() + public function testVaryHeader(): void { list($action, $filter) = $this->mockActionAndFilter(); $filter->formats = []; @@ -118,7 +119,7 @@ class ContentNegotiatorTest extends TestCase $this->assertContains('Accept-Language', $varyHeader); } - public function testNegotiateContentType() + public function testNegotiateContentType(): void { $filter = new ContentNegotiator([ 'formats' => [ diff --git a/tests/framework/filters/CorsTest.php b/tests/framework/filters/CorsTest.php index 6e73d01508..67c714b552 100644 --- a/tests/framework/filters/CorsTest.php +++ b/tests/framework/filters/CorsTest.php @@ -20,7 +20,7 @@ use yiiunit\TestCase; */ class CorsTest extends TestCase { - public function testPreflight() + public function testPreflight(): void { $this->mockWebApplication(); $controller = new Controller('id', Yii::$app); @@ -43,7 +43,7 @@ class CorsTest extends TestCase $this->assertTrue($cors->beforeAction($action)); } - public function testWildcardOrigin() + public function testWildcardOrigin(): void { $this->mockWebApplication(); $controller = new Controller('id', Yii::$app); @@ -64,7 +64,7 @@ class CorsTest extends TestCase $this->assertEquals('*', $cors->response->getHeaders()->get('access-control-allow-origin')); } - public function testAccessControlAllowHeadersPreflight() + public function testAccessControlAllowHeadersPreflight(): void { $this->mockWebApplication(); $controller = new Controller('id', Yii::$app); diff --git a/tests/framework/filters/HostControlTest.php b/tests/framework/filters/HostControlTest.php index 9ae7a8207a..9435f51e73 100644 --- a/tests/framework/filters/HostControlTest.php +++ b/tests/framework/filters/HostControlTest.php @@ -90,7 +90,7 @@ class HostControlTest extends TestCase * @param string $host * @param bool $allowed */ - public function testFilter($allowedHosts, $host, $allowed) + public function testFilter($allowedHosts, $host, $allowed): void { $_SERVER['HTTP_HOST'] = $host; @@ -123,7 +123,7 @@ class HostControlTest extends TestCase public $denyCallBackCalled = false; - public function testDenyCallback() + public function testDenyCallback(): void { $filter = new HostControl(); $filter->allowedHosts = ['example.com']; @@ -138,7 +138,7 @@ class HostControlTest extends TestCase $this->assertTrue($this->denyCallBackCalled, 'denyCallback should have been called.'); } - public function testDefaultHost() + public function testDefaultHost(): void { $filter = new HostControl(); $filter->allowedHosts = ['example.com']; @@ -153,7 +153,7 @@ class HostControlTest extends TestCase $this->assertSame('yiiframework.com', Yii::$app->getRequest()->getHostName()); } - public function testErrorHandlerWithDefaultHost() + public function testErrorHandlerWithDefaultHost(): void { $this->expectException('yii\web\NotFoundHttpException'); $this->expectExceptionMessage('Page not found.'); diff --git a/tests/framework/filters/HttpCacheTest.php b/tests/framework/filters/HttpCacheTest.php index 20a235be49..93cf492591 100644 --- a/tests/framework/filters/HttpCacheTest.php +++ b/tests/framework/filters/HttpCacheTest.php @@ -8,13 +8,15 @@ namespace yiiunit\framework\filters; +use yiiunit\TestCase; +use ReflectionMethod; use Yii; use yii\filters\HttpCache; /** * @group filters */ -class HttpCacheTest extends \yiiunit\TestCase +class HttpCacheTest extends TestCase { protected function setUp(): void { @@ -26,7 +28,7 @@ class HttpCacheTest extends \yiiunit\TestCase $this->mockWebApplication(); } - public function testDisabled() + public function testDisabled(): void { $httpCache = new HttpCache(); $this->assertTrue($httpCache->beforeAction(null)); @@ -34,7 +36,7 @@ class HttpCacheTest extends \yiiunit\TestCase $this->assertTrue($httpCache->beforeAction(null)); } - public function testEmptyPragma() + public function testEmptyPragma(): void { $httpCache = new HttpCache(); $httpCache->etagSeed = function ($action, $params) { @@ -49,11 +51,11 @@ class HttpCacheTest extends \yiiunit\TestCase /** * @covers \yii\filters\HttpCache::validateCache */ - public function testValidateCache() + public function testValidateCache(): void { $httpCache = new HttpCache(); $request = Yii::$app->getRequest(); - $method = new \ReflectionMethod($httpCache, 'validateCache'); + $method = new ReflectionMethod($httpCache, 'validateCache'); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible // @link https://wiki.php.net/rfc/make-reflection-setaccessible-no-op @@ -86,7 +88,7 @@ class HttpCacheTest extends \yiiunit\TestCase /** * @covers \yii\filters\HttpCache::generateEtag */ - public function testGenerateEtag() + public function testGenerateEtag(): void { $httpCache = new HttpCache(); $httpCache->weakEtag = false; diff --git a/tests/framework/filters/PageCacheTest.php b/tests/framework/filters/PageCacheTest.php index df281366ab..ea4f5f0c12 100644 --- a/tests/framework/filters/PageCacheTest.php +++ b/tests/framework/filters/PageCacheTest.php @@ -151,7 +151,7 @@ class PageCacheTest extends TestCase * @dataProvider cacheTestCaseProvider * @param array $testCase */ - public function testCache($testCase) + public function testCache($testCase): void { $testCase = ArrayHelper::merge([ 'properties' => [], @@ -255,7 +255,7 @@ class PageCacheTest extends TestCase } } - public function testExpired() + public function testExpired(): void { CacheTestCase::$time = time(); CacheTestCase::$microtime = microtime(true); @@ -300,7 +300,7 @@ class PageCacheTest extends TestCase ob_end_clean(); } - public function testVaryByRoute() + public function testVaryByRoute(): void { $testCases = [ false, @@ -351,7 +351,7 @@ class PageCacheTest extends TestCase } } - public function testVariations() + public function testVariations(): void { $testCases = [ [true, 'name' => 'value'], @@ -403,7 +403,7 @@ class PageCacheTest extends TestCase } } - public function testDependency() + public function testDependency(): void { $testCases = [ false, @@ -460,7 +460,7 @@ class PageCacheTest extends TestCase } } - public function testCalculateCacheKey() + public function testCalculateCacheKey(): void { $expected = ['yii\filters\PageCache', 'test', 'ru']; Yii::$app->requestedRoute = 'test'; @@ -474,7 +474,7 @@ class PageCacheTest extends TestCase $this->assertEquals(['yii\filters\PageCache', 'test'], $keys); } - public function testClosureVariations() + public function testClosureVariations(): void { $keys = $this->invokeMethod(new PageCache([ 'variations' => function () { diff --git a/tests/framework/filters/RateLimiterTest.php b/tests/framework/filters/RateLimiterTest.php index 47c7e6eead..dd10204d23 100644 --- a/tests/framework/filters/RateLimiterTest.php +++ b/tests/framework/filters/RateLimiterTest.php @@ -37,35 +37,35 @@ class RateLimiterTest extends TestCase Yii::setLogger(null); } - public function testInitFilledRequest() + public function testInitFilledRequest(): void { $rateLimiter = new RateLimiter(['request' => 'Request']); $this->assertEquals('Request', $rateLimiter->request); } - public function testInitNotFilledRequest() + public function testInitNotFilledRequest(): void { $rateLimiter = new RateLimiter(); $this->assertInstanceOf(Request::className(), $rateLimiter->request); } - public function testInitFilledResponse() + public function testInitFilledResponse(): void { $rateLimiter = new RateLimiter(['response' => 'Response']); $this->assertEquals('Response', $rateLimiter->response); } - public function testInitNotFilledResponse() + public function testInitNotFilledResponse(): void { $rateLimiter = new RateLimiter(); $this->assertInstanceOf(Response::className(), $rateLimiter->response); } - public function testBeforeActionUserInstanceOfRateLimitInterface() + public function testBeforeActionUserInstanceOfRateLimitInterface(): void { $rateLimiter = new RateLimiter(); $rateLimit = new RateLimit(); @@ -79,7 +79,7 @@ class RateLimiterTest extends TestCase $this->assertTrue($result); } - public function testBeforeActionUserNotInstanceOfRateLimitInterface() + public function testBeforeActionUserNotInstanceOfRateLimitInterface(): void { $rateLimiter = new RateLimiter(['user' => 'User']); @@ -92,7 +92,7 @@ class RateLimiterTest extends TestCase $this->assertTrue($result); } - public function testBeforeActionEmptyUser() + public function testBeforeActionEmptyUser(): void { $user = new User(['identityClass' => RateLimit::className()]); Yii::$app->set('user', $user); @@ -104,7 +104,7 @@ class RateLimiterTest extends TestCase $this->assertTrue($result); } - public function testCheckRateLimitTooManyRequests() + public function testCheckRateLimitTooManyRequests(): void { $rateLimit = new RateLimit(); $rateLimit @@ -116,7 +116,7 @@ class RateLimiterTest extends TestCase $rateLimiter->checkRateLimit($rateLimit, Yii::$app->request, Yii::$app->response, 'testAction'); } - public function testCheckRateaddRateLimitHeaders() + public function testCheckRateaddRateLimitHeaders(): void { $rateLimit = new RateLimit(); $rateLimit @@ -132,7 +132,7 @@ class RateLimiterTest extends TestCase $this->assertEquals(5, $headers->get('X-Rate-Limit-Reset')); } - public function testAddRateLimitHeadersDisabledRateLimitHeaders() + public function testAddRateLimitHeadersDisabledRateLimitHeaders(): void { $rateLimiter = new RateLimiter(); $rateLimiter->enableRateLimitHeaders = false; @@ -142,7 +142,7 @@ class RateLimiterTest extends TestCase $this->assertCount(0, $response->getHeaders()); } - public function testAddRateLimitHeadersEnabledRateLimitHeaders() + public function testAddRateLimitHeadersEnabledRateLimitHeaders(): void { $rateLimiter = new RateLimiter(); $rateLimiter->enableRateLimitHeaders = true; @@ -155,7 +155,7 @@ class RateLimiterTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/18236 */ - public function testUserWithClosureFunction() + public function testUserWithClosureFunction(): void { $rateLimiter = new RateLimiter(); $rateLimiter->user = function ($action) { diff --git a/tests/framework/filters/auth/AuthMethodTest.php b/tests/framework/filters/auth/AuthMethodTest.php index 7c8e32cf81..8882c31ce4 100644 --- a/tests/framework/filters/auth/AuthMethodTest.php +++ b/tests/framework/filters/auth/AuthMethodTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\filters\auth; +use stdClass; +use ReflectionClass; use Yii; use yii\base\Action; use yii\filters\auth\AuthMethod; @@ -58,12 +60,12 @@ class AuthMethodTest extends TestCase // Tests : - public function testBeforeAction() + public function testBeforeAction(): void { $action = $this->createAction(); $filter = $this->createFilter(function () { - return new \stdClass(); + return new stdClass(); }); $this->assertTrue($filter->beforeAction($action)); @@ -74,9 +76,9 @@ class AuthMethodTest extends TestCase $this->assertTrue($filter->beforeAction($action)); } - public function testIsOptional() + public function testIsOptional(): void { - $reflection = new \ReflectionClass(AuthMethod::className()); + $reflection = new ReflectionClass(AuthMethod::className()); $method = $reflection->getMethod('isOptional'); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible @@ -86,7 +88,7 @@ class AuthMethodTest extends TestCase } $filter = $this->createFilter(function () { - return new \stdClass(); + return new stdClass(); }); $filter->optional = ['some']; diff --git a/tests/framework/filters/auth/AuthTest.php b/tests/framework/filters/auth/AuthTest.php index b5498d87bb..0330bcda7c 100644 --- a/tests/framework/filters/auth/AuthTest.php +++ b/tests/framework/filters/auth/AuthTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\filters\auth; +use yiiunit\TestCase; +use ReflectionClass; use Yii; use yii\base\Action; use yii\filters\auth\AuthMethod; @@ -24,7 +26,7 @@ use yiiunit\framework\filters\stubs\UserIdentity; * @author Dmitry Naumenko * @since 2.0.7 */ -class AuthTest extends \yiiunit\TestCase +class AuthTest extends TestCase { protected function setUp(): void { @@ -58,7 +60,7 @@ class AuthTest extends \yiiunit\TestCase ]; } - public function authOnly($token, $login, $filter) + public function authOnly($token, $login, $filter): void { /** @var TestAuthController $controller */ $controller = Yii::$app->createController('test-auth')[0]; @@ -69,7 +71,7 @@ class AuthTest extends \yiiunit\TestCase } } - public function authOptional($token, $login, $filter) + public function authOptional($token, $login, $filter): void { /** @var TestAuthController $controller */ $controller = Yii::$app->createController('test-auth')[0]; @@ -80,7 +82,7 @@ class AuthTest extends \yiiunit\TestCase } } - public function authExcept($token, $login, $filter) + public function authExcept($token, $login, $filter): void { /** @var TestAuthController $controller */ $controller = Yii::$app->createController('test-auth')[0]; @@ -91,7 +93,7 @@ class AuthTest extends \yiiunit\TestCase } } - public function ensureFilterApplies($token, $login, $filter) + public function ensureFilterApplies($token, $login, $filter): void { $this->authOnly($token, $login, $filter); $this->authOptional($token, $login, $filter); @@ -103,7 +105,7 @@ class AuthTest extends \yiiunit\TestCase * @param string|null $token * @param string|null $login */ - public function testQueryParamAuth($token, $login) + public function testQueryParamAuth($token, $login): void { $_GET['access-token'] = $token; $filter = ['class' => QueryParamAuth::className()]; @@ -115,7 +117,7 @@ class AuthTest extends \yiiunit\TestCase * @param string|null $token * @param string|null $login */ - public function testHttpHeaderAuth($token, $login) + public function testHttpHeaderAuth($token, $login): void { Yii::$app->request->headers->set('X-Api-Key', $token); $filter = ['class' => HttpHeaderAuth::className()]; @@ -127,7 +129,7 @@ class AuthTest extends \yiiunit\TestCase * @param string|null $token * @param string|null $login */ - public function testHttpBearerAuth($token, $login) + public function testHttpBearerAuth($token, $login): void { Yii::$app->request->headers->set('Authorization', "Bearer $token"); $filter = ['class' => HttpBearerAuth::className()]; @@ -148,11 +150,11 @@ class AuthTest extends \yiiunit\TestCase * @dataProvider authMethodProvider * @param string $authClass */ - public function testActive($authClass) + public function testActive($authClass): void { /** @var AuthMethod $filter */ $filter = new $authClass(); - $reflection = new \ReflectionClass($filter); + $reflection = new ReflectionClass($filter); $method = $reflection->getMethod('isActive'); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible @@ -198,7 +200,7 @@ class AuthTest extends \yiiunit\TestCase $this->assertFalse($method->invokeArgs($filter, [new Action('view', $controller)])); } - public function testHeaders() + public function testHeaders(): void { Yii::$app->request->headers->set('Authorization', 'Bearer wrong_token'); $filter = ['class' => HttpBearerAuth::className()]; diff --git a/tests/framework/filters/auth/BasicAuthTest.php b/tests/framework/filters/auth/BasicAuthTest.php index 7f0967c029..20a51a9c6a 100644 --- a/tests/framework/filters/auth/BasicAuthTest.php +++ b/tests/framework/filters/auth/BasicAuthTest.php @@ -26,7 +26,7 @@ class BasicAuthTest extends AuthTest * @param string|null $token * @param string|null $login */ - public function testHttpBasicAuth($token, $login) + public function testHttpBasicAuth($token, $login): void { $original = $_SERVER; @@ -42,7 +42,7 @@ class BasicAuthTest extends AuthTest * @param string|null $token * @param string|null $login */ - public function testHttpBasicAuthWithHttpAuthorizationHeader($token, $login) + public function testHttpBasicAuthWithHttpAuthorizationHeader($token, $login): void { $original = $_SERVER; @@ -57,7 +57,7 @@ class BasicAuthTest extends AuthTest * @param string|null $token * @param string|null $login */ - public function testHttpBasicAuthWithRedirectHttpAuthorizationHeader($token, $login) + public function testHttpBasicAuthWithRedirectHttpAuthorizationHeader($token, $login): void { $original = $_SERVER; @@ -72,7 +72,7 @@ class BasicAuthTest extends AuthTest * @param string|null $token * @param string|null $login */ - public function testHttpBasicAuthCustom($token, $login) + public function testHttpBasicAuthCustom($token, $login): void { $_SERVER['PHP_AUTH_USER'] = $login; $_SERVER['PHP_AUTH_PW'] = 'whatever, we are testers'; @@ -98,7 +98,7 @@ class BasicAuthTest extends AuthTest * @param string|null $token * @param string|null $login */ - public function testHttpBasicAuthIssue15658($token, $login) + public function testHttpBasicAuthIssue15658($token, $login): void { $_SERVER['PHP_AUTH_USER'] = $login; $_SERVER['PHP_AUTH_PW'] = 'y0u7h1nk175r34l?'; @@ -134,7 +134,7 @@ class BasicAuthTest extends AuthTest * @param string|null $token * @param string|null $login */ - public function testAfterLoginEventIsTriggered18031($token, $login) + public function testAfterLoginEventIsTriggered18031($token, $login): void { $triggered = false; Event::on('\yii\web\User', User::EVENT_AFTER_LOGIN, function ($event) use (&$triggered) { diff --git a/tests/framework/filters/auth/CompositeAuthTest.php b/tests/framework/filters/auth/CompositeAuthTest.php index ee63ac1493..c3a030fe1d 100644 --- a/tests/framework/filters/auth/CompositeAuthTest.php +++ b/tests/framework/filters/auth/CompositeAuthTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\filters\auth; +use yiiunit\TestCase; use Yii; use yii\filters\auth\CompositeAuth; use yii\filters\auth\HttpBearerAuth; @@ -102,7 +103,7 @@ class TestController extends Controller /** * @group filters */ -class CompositeAuthTest extends \yiiunit\TestCase +class CompositeAuthTest extends TestCase { protected function setUp(): void { @@ -125,7 +126,7 @@ class CompositeAuthTest extends \yiiunit\TestCase $this->mockWebApplication($appConfig); } - public function testCallingRunWithCompleteRoute() + public function testCallingRunWithCompleteRoute(): void { /** @var TestController $controller */ Yii::$app->request->headers->set('X-Api-Key', 'user1'); @@ -136,7 +137,7 @@ class CompositeAuthTest extends \yiiunit\TestCase /** * @see https://github.com/yiisoft/yii2/issues/7409 */ - public function testRunAction() + public function testRunAction(): void { /** @var TestController $controller */ Yii::$app->request->headers->set('X-Api-Key', 'user1'); @@ -144,7 +145,7 @@ class CompositeAuthTest extends \yiiunit\TestCase $this->assertEquals('success', $controller->run('b')); } - public function testRunButWithActionIdOnly() + public function testRunButWithActionIdOnly(): void { /** @var TestController $controller */ Yii::$app->request->headers->set('X-Api-Key', 'user1'); @@ -152,7 +153,7 @@ class CompositeAuthTest extends \yiiunit\TestCase $this->assertEquals('success', $controller->run('c')); } - public function testRunWithWrongToken() + public function testRunWithWrongToken(): void { /** @var TestController $controller */ Yii::$app->request->headers->set('X-Api-Key', 'wrong-user'); @@ -161,7 +162,7 @@ class CompositeAuthTest extends \yiiunit\TestCase $controller->run('a'); } - public function testRunWithoutAuthHeader() + public function testRunWithoutAuthHeader(): void { /** @var TestController $controller */ $controller = Yii::$app->createController('test')[0]; @@ -169,7 +170,7 @@ class CompositeAuthTest extends \yiiunit\TestCase $controller->run('a'); } - public function testRunWithOptionalAction() + public function testRunWithOptionalAction(): void { /** @var TestController $controller */ $controller = Yii::$app->createController('test')[0]; @@ -253,7 +254,7 @@ class CompositeAuthTest extends \yiiunit\TestCase * * @dataProvider compositeAuthDataProvider */ - public function testCompositeAuth($authMethods, $actionId, $expectedAuth) + public function testCompositeAuth($authMethods, $actionId, $expectedAuth): void { Yii::$app->request->headers->set('X-Api-Key', 'user1'); $controller = new TestController('test', Yii::$app, ['authMethods' => $authMethods]); diff --git a/tests/framework/filters/stubs/ExposedLogger.php b/tests/framework/filters/stubs/ExposedLogger.php index 5fecfbe2de..a172e1e298 100644 --- a/tests/framework/filters/stubs/ExposedLogger.php +++ b/tests/framework/filters/stubs/ExposedLogger.php @@ -12,7 +12,7 @@ use yii\log\Logger; class ExposedLogger extends Logger { - public function log($message, $level, $category = 'application') + public function log($message, $level, $category = 'application'): void { $this->messages[] = $message; } diff --git a/tests/framework/grid/ActionColumnTest.php b/tests/framework/grid/ActionColumnTest.php index a986159b4d..2b653566cf 100644 --- a/tests/framework/grid/ActionColumnTest.php +++ b/tests/framework/grid/ActionColumnTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\grid; +use yiiunit\TestCase; use yii\grid\ActionColumn; use yii\helpers\Html; @@ -16,9 +17,9 @@ use yii\helpers\Html; * * @group grid */ -class ActionColumnTest extends \yiiunit\TestCase +class ActionColumnTest extends TestCase { - public function testInit() + public function testInit(): void { $column = new ActionColumn(); $this->assertEquals(['view', 'update', 'delete'], array_keys($column->buttons)); @@ -36,7 +37,7 @@ class ActionColumnTest extends \yiiunit\TestCase $this->assertEquals(['view'], array_keys($column->buttons)); } - public function testRenderDataCell() + public function testRenderDataCell(): void { $column = new ActionColumn(); $column->urlCreator = function ($model, $key, $index) { diff --git a/tests/framework/grid/CheckboxColumnTest.php b/tests/framework/grid/CheckboxColumnTest.php index 070d08cb9b..a711fbfcb7 100644 --- a/tests/framework/grid/CheckboxColumnTest.php +++ b/tests/framework/grid/CheckboxColumnTest.php @@ -33,7 +33,7 @@ class CheckboxColumnTest extends TestCase Yii::$app->assetManager->bundles['yii\web\JqueryAsset'] = false; } - public function testInputName() + public function testInputName(): void { $column = new CheckboxColumn(['name' => 'selection', 'grid' => $this->getGrid()]); $this->assertStringContainsString('name="selection_all"', $column->renderHeaderCell()); @@ -54,7 +54,7 @@ class CheckboxColumnTest extends TestCase $this->assertStringContainsString('name="MyForm[grid1][key_all]"', $column->renderHeaderCell()); } - public function testInputValue() + public function testInputValue(): void { $column = new CheckboxColumn(['grid' => $this->getGrid()]); $this->assertStringContainsString('value="1"', $column->renderDataCell([], 1, 0)); @@ -85,7 +85,7 @@ class CheckboxColumnTest extends TestCase $this->assertStringContainsString('value="42"', $column->renderDataCell([], 1, 0)); } - public function testContent() + public function testContent(): void { $column = new CheckboxColumn([ 'content' => function ($model, $key, $index, $column) { diff --git a/tests/framework/grid/DataColumnTest.php b/tests/framework/grid/DataColumnTest.php index 5fe977d805..0da1a29be7 100644 --- a/tests/framework/grid/DataColumnTest.php +++ b/tests/framework/grid/DataColumnTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\grid; +use yiiunit\TestCase; +use yiiunit\data\base\RulesModel; use Yii; use yii\data\ActiveDataProvider; use yii\data\ArrayDataProvider; @@ -22,12 +24,12 @@ use yiiunit\data\base\Singer; * * @group grid */ -class DataColumnTest extends \yiiunit\TestCase +class DataColumnTest extends TestCase { /** * @see DataColumn::getHeaderCellLabel() */ - public function testColumnLabels_OnEmpty_ArrayProvider() + public function testColumnLabels_OnEmpty_ArrayProvider(): void { $this->mockApplication(); $grid = new GridView([ @@ -48,7 +50,7 @@ class DataColumnTest extends \yiiunit\TestCase /** * @see DataColumn::getHeaderCellLabel() */ - public function testColumnLabels_OnEmpty_ArrayProvider_WithFilterModel() + public function testColumnLabels_OnEmpty_ArrayProvider_WithFilterModel(): void { $this->mockApplication(); $grid = new GridView([ @@ -70,7 +72,7 @@ class DataColumnTest extends \yiiunit\TestCase * @see DataColumn::$filter * @see DataColumn::renderFilterCellContent() */ - public function testFilterInput_String() + public function testFilterInput_String(): void { $this->mockApplication(); $filterInput = ''; @@ -96,7 +98,7 @@ class DataColumnTest extends \yiiunit\TestCase * @see DataColumn::$filter * @see DataColumn::renderFilterCellContent() */ - public function testFilterHasMaxLengthWhenIsAnActiveTextInput() + public function testFilterHasMaxLengthWhenIsAnActiveTextInput(): void { $this->mockApplication([ 'components' => [ @@ -131,7 +133,7 @@ class DataColumnTest extends \yiiunit\TestCase * @see DataColumn::$filter * @see DataColumn::renderFilterCellContent() */ - public function testFilterInput_Array() + public function testFilterInput_Array(): void { $this->mockApplication([ 'components' => [ @@ -182,7 +184,7 @@ HTML * @see DataColumn::$filter * @see DataColumn::renderFilterCellContent() */ - public function testFilterInput_FormatBoolean() + public function testFilterInput_FormatBoolean(): void { $this->mockApplication([ 'components' => [ @@ -232,7 +234,7 @@ HTML * @see DataColumn::$filterAttribute * @see DataColumn::renderFilterCellContent() */ - public function testFilterInputWithFilterAttribute() + public function testFilterInputWithFilterAttribute(): void { $this->mockApplication(); @@ -246,7 +248,7 @@ HTML 'filterAttribute' => 'user_id', ], ], - 'filterModel' => new \yiiunit\data\base\RulesModel(['rules' => [['user_id', 'safe']]]), + 'filterModel' => new RulesModel(['rules' => [['user_id', 'safe']]]), ]); $dataColumn = $grid->columns[0]; diff --git a/tests/framework/grid/GridViewTest.php b/tests/framework/grid/GridViewTest.php index e9ab08045e..0f08d557b8 100644 --- a/tests/framework/grid/GridViewTest.php +++ b/tests/framework/grid/GridViewTest.php @@ -8,6 +8,11 @@ namespace yiiunit\framework\grid; +use yiiunit\TestCase; +use yii\db\Connection; +use yii\web\UrlManager; +use yii\data\ActiveDataProvider; +use Exception; use Yii; use yii\data\ArrayDataProvider; use yii\grid\DataColumn; @@ -19,7 +24,7 @@ use yiiunit\data\ar\NoAutoLabels; * @author Evgeniy Tkachenko * @group grid */ -class GridViewTest extends \yiiunit\TestCase +class GridViewTest extends TestCase { protected function setUp(): void { @@ -53,9 +58,9 @@ class GridViewTest extends \yiiunit\TestCase * @dataProvider emptyDataProvider * @param mixed $emptyText * @param string $expectedText - * @throws \Exception + * @throws Exception */ - public function testEmpty($emptyText, $expectedText) + public function testEmpty($emptyText, $expectedText): void { $html = GridView::widget([ 'id' => 'grid', @@ -79,7 +84,7 @@ class GridViewTest extends \yiiunit\TestCase $this->assertEquals($expectedHtml, $html); } - public function testGuessColumns() + public function testGuessColumns(): void { $row = ['id' => 1, 'name' => 'Name1', 'value' => 'Value1', 'description' => 'Description1']; @@ -126,9 +131,9 @@ class GridViewTest extends \yiiunit\TestCase } /** - * @throws \Exception + * @throws Exception */ - public function testFooter() + public function testFooter(): void { $config = [ 'id' => 'grid', @@ -155,13 +160,13 @@ class GridViewTest extends \yiiunit\TestCase $this->assertTrue(preg_match('/<\/tbody>/', $html) === 1); } - public function testHeaderLabels() + public function testHeaderLabels(): void { // Ensure GridView does not call Model::generateAttributeLabel() to generate labels unless the labels are explicitly used. $this->mockApplication([ 'components' => [ 'db' => [ - 'class' => \yii\db\Connection::className(), + 'class' => Connection::className(), 'dsn' => 'sqlite::memory:', ], ], @@ -170,13 +175,13 @@ class GridViewTest extends \yiiunit\TestCase NoAutoLabels::$db = Yii::$app->getDb(); Yii::$app->getDb()->createCommand()->createTable(NoAutoLabels::tableName(), ['attr1' => 'int', 'attr2' => 'int'])->execute(); - $urlManager = new \yii\web\UrlManager([ + $urlManager = new UrlManager([ 'baseUrl' => '/', 'scriptUrl' => '/index.php', ]); $grid = new GridView([ - 'dataProvider' => new \yii\data\ActiveDataProvider([ + 'dataProvider' => new ActiveDataProvider([ 'query' => NoAutoLabels::find(), ]), 'columns' => [ diff --git a/tests/framework/grid/RadiobuttonColumnTest.php b/tests/framework/grid/RadiobuttonColumnTest.php index 958a441450..4de1bd4ecc 100644 --- a/tests/framework/grid/RadiobuttonColumnTest.php +++ b/tests/framework/grid/RadiobuttonColumnTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\grid; +use yii\base\InvalidConfigException; use Yii; use yii\data\ArrayDataProvider; use yii\grid\GridView; @@ -23,9 +24,9 @@ use yiiunit\TestCase; */ class RadiobuttonColumnTest extends TestCase { - public function testException() + public function testException(): void { - $this->expectException(\yii\base\InvalidConfigException::class); + $this->expectException(InvalidConfigException::class); $this->expectExceptionMessage('The "name" property must be set.'); new RadioButtonColumn([ @@ -33,7 +34,7 @@ class RadiobuttonColumnTest extends TestCase ]); } - public function testOptionsByArray() + public function testOptionsByArray(): void { $column = new RadioButtonColumn([ 'radioOptions' => [ @@ -43,7 +44,7 @@ class RadiobuttonColumnTest extends TestCase $this->assertEquals('', $column->renderDataCell([], 1, 0)); } - public function testOptionsByCallback() + public function testOptionsByCallback(): void { $model = [ 'label' => 'label', @@ -60,7 +61,7 @@ class RadiobuttonColumnTest extends TestCase $this->assertEquals('', $actual); } - public function testContent() + public function testContent(): void { $column = new RadioButtonColumn([ 'content' => function ($model, $key, $index, $column) { @@ -77,7 +78,7 @@ class RadiobuttonColumnTest extends TestCase $this->assertStringContainsString(Html::radio('radioButtonInput', false), $column->renderDataCell([], 1, 0)); } - public function testMultipleInGrid() + public function testMultipleInGrid(): void { $this->mockApplication(); Yii::setAlias('@webroot', '@yiiunit/runtime'); diff --git a/tests/framework/helpers/ArrayHelperTest.php b/tests/framework/helpers/ArrayHelperTest.php index eb89c1d98c..68e2b33fa9 100644 --- a/tests/framework/helpers/ArrayHelperTest.php +++ b/tests/framework/helpers/ArrayHelperTest.php @@ -8,6 +8,14 @@ namespace yiiunit\framework\helpers; +use DateTime; +use DateTimeZone; +use stdClass; +use yii\helpers\UnsetArrayValue; +use yii\helpers\ReplaceArrayValue; +use ArrayObject; +use Throwable; +use ReturnTypeWillChange; use ArrayAccess; use Iterator; use yii\base\BaseObject; @@ -29,7 +37,7 @@ class ArrayHelperTest extends TestCase $this->destroyApplication(); } - public function testToArray() + public function testToArray(): void { $dataArrayable = $this->getMockBuilder('yii\\base\\Arrayable')->getMock(); $dataArrayable->method('toArray')->willReturn([]); @@ -121,10 +129,10 @@ class ArrayHelperTest extends TestCase 'date' => '2021-09-13 15:16:17.000000', 'timezone_type' => 3, 'timezone' => 'UTC', - ], ArrayHelper::toArray(new \DateTime('2021-09-13 15:16:17', new \DateTimeZone('UTC')))); + ], ArrayHelper::toArray(new DateTime('2021-09-13 15:16:17', new DateTimeZone('UTC')))); } - public function testRemove() + public function testRemove(): void { $array = ['name' => 'b', 'age' => 3]; $name = ArrayHelper::remove($array, 'name'); @@ -139,7 +147,7 @@ class ArrayHelperTest extends TestCase /** * @return void */ - public function testRemoveWithFloat() + public function testRemoveWithFloat(): void { if (version_compare(PHP_VERSION, '8.1.0', '>=')) { $this->markTestSkipped('Using floats as array key is deprecated.'); @@ -159,7 +167,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals('defaultValue', $default); } - public function testRemoveValueMultiple() + public function testRemoveValueMultiple(): void { $array = [ 'Bob' => 'Dylan', @@ -180,7 +188,7 @@ class ArrayHelperTest extends TestCase ], $removed); } - public function testRemoveValueNotExisting() + public function testRemoveValueNotExisting(): void { $array = [ 'Bob' => 'Dylan', @@ -200,7 +208,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals([], $removed); } - public function testMultisort() + public function testMultisort(): void { // empty key $dataEmpty = []; @@ -250,17 +258,17 @@ class ArrayHelperTest extends TestCase $this->assertEquals(['name' => 'B', 'age' => 4], $array[3]); } - public function testMultisortNestedObjects() + public function testMultisortNestedObjects(): void { - $obj1 = new \stdClass(); + $obj1 = new stdClass(); $obj1->type = 'def'; $obj1->owner = $obj1; - $obj2 = new \stdClass(); + $obj2 = new stdClass(); $obj2->type = 'abc'; $obj2->owner = $obj2; - $obj3 = new \stdClass(); + $obj3 = new stdClass(); $obj3->type = 'abc'; $obj3->owner = $obj3; @@ -283,7 +291,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($obj3, $models[2]); } - public function testMultisortUseSort() + public function testMultisortUseSort(): void { // single key $sort = new Sort([ @@ -322,7 +330,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals(['name' => 'b', 'age' => 3], $array[2]); } - public function testMultisortClosure() + public function testMultisortClosure(): void { $changelog = [ '- Enh #123: test1', @@ -349,21 +357,21 @@ class ArrayHelperTest extends TestCase ], $changelog); } - public function testMultisortInvalidParamExceptionDirection() + public function testMultisortInvalidParamExceptionDirection(): void { $this->expectException('yii\base\InvalidParamException'); $data = ['foo' => 'bar']; ArrayHelper::multisort($data, ['foo'], []); } - public function testMultisortInvalidParamExceptionSortFlag() + public function testMultisortInvalidParamExceptionSortFlag(): void { $this->expectException('yii\base\InvalidParamException'); $data = ['foo' => 'bar']; ArrayHelper::multisort($data, ['foo'], ['foo'], []); } - public function testMerge() + public function testMerge(): void { $a = [ 'name' => 'Yii', @@ -415,7 +423,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, $result); } - public function testMergeWithNumericKeys() + public function testMergeWithNumericKeys(): void { $a = [10 => [1]]; $b = [10 => [2]]; @@ -426,7 +434,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, $result); } - public function testMergeWithUnset() + public function testMergeWithUnset(): void { $a = [ 'name' => 'Yii', @@ -441,7 +449,7 @@ class ArrayHelperTest extends TestCase ]; $b = [ 'version' => '1.1', - 'options' => new \yii\helpers\UnsetArrayValue(), + 'options' => new UnsetArrayValue(), 'features' => [ 'gii', ], @@ -460,7 +468,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, $result); } - public function testMergeWithReplace() + public function testMergeWithReplace(): void { $a = [ 'name' => 'Yii', @@ -478,7 +486,7 @@ class ArrayHelperTest extends TestCase 'options' => [ 'unittest' => true, ], - 'features' => new \yii\helpers\ReplaceArrayValue([ + 'features' => new ReplaceArrayValue([ 'gii', ]), ]; @@ -499,7 +507,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, $result); } - public function testMergeWithNullValues() + public function testMergeWithNullValues(): void { $a = [ 'firstValue', @@ -521,7 +529,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, $result); } - public function testMergeEmpty() + public function testMergeEmpty(): void { $this->assertEquals([], ArrayHelper::merge([], [])); $this->assertEquals([], ArrayHelper::merge([], [], [])); @@ -530,7 +538,7 @@ class ArrayHelperTest extends TestCase /** * @see https://github.com/yiisoft/yii2/pull/11549 */ - public function testGetValueWithFloatKeys() + public function testGetValueWithFloatKeys(): void { if (version_compare(PHP_VERSION, '8.1.0', '>=')) { $this->markTestSkipped('Using floats as array key is deprecated.'); @@ -547,7 +555,7 @@ class ArrayHelperTest extends TestCase $this->assertNull($result); } - public function testIndex() + public function testIndex(): void { $array = [ ['id' => '123', 'data' => 'abc'], @@ -585,7 +593,7 @@ class ArrayHelperTest extends TestCase ], $result); } - public function testIndexGroupBy() + public function testIndexGroupBy(): void { $array = [ ['id' => '123', 'data' => 'abc'], @@ -668,7 +676,7 @@ class ArrayHelperTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/11739 */ - public function testIndexFloat() + public function testIndexFloat(): void { $array = [ ['id' => 1e6], @@ -689,7 +697,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, $result); } - public function testGetColumn() + public function testGetColumn(): void { $array = [ 'a' => ['id' => '123', 'data' => 'abc'], @@ -710,7 +718,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals(['abc', 'def'], $result); } - public function testMap() + public function testMap(): void { $array = [ ['id' => '123', 'name' => 'aaa', 'class' => 'x'], @@ -790,7 +798,7 @@ class ArrayHelperTest extends TestCase ], $result); } - public function testKeyExists() + public function testKeyExists(): void { $array = [ 'a' => 1, @@ -808,7 +816,7 @@ class ArrayHelperTest extends TestCase $this->assertFalse(ArrayHelper::keyExists('c', $array, false)); } - public function testKeyExistsWithFloat() + public function testKeyExistsWithFloat(): void { if (version_compare(PHP_VERSION, '8.1.0', '>=')) { $this->markTestSkipped('Using floats as array key is deprecated.'); @@ -829,7 +837,7 @@ class ArrayHelperTest extends TestCase $this->assertTrue(ArrayHelper::keyExists(3.3, $array)); } - public function testKeyExistsArrayAccess() + public function testKeyExistsArrayAccess(): void { $array = new TraversableArrayAccessibleObject([ 'a' => 1, @@ -842,7 +850,7 @@ class ArrayHelperTest extends TestCase $this->assertFalse(ArrayHelper::keyExists('c', $array)); } - public function testKeyExistsArrayAccessCaseInsensitiveThrowsError() + public function testKeyExistsArrayAccessCaseInsensitiveThrowsError(): void { $this->expectException('yii\base\InvalidArgumentException'); $this->expectExceptionMessage('Second parameter($array) cannot be ArrayAccess in case insensitive mode'); @@ -890,7 +898,7 @@ class ArrayHelperTest extends TestCase * @param $expected * @param null $default */ - public function testGetValue($key, $expected, $default = null) + public function testGetValue($key, $expected, $default = null): void { $array = [ 'name' => 'test', @@ -919,32 +927,32 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, ArrayHelper::getValue($array, $key, $default)); } - public function testGetValueObjects() + public function testGetValueObjects(): void { - $arrayObject = new \ArrayObject(['id' => 23], \ArrayObject::ARRAY_AS_PROPS); + $arrayObject = new ArrayObject(['id' => 23], ArrayObject::ARRAY_AS_PROPS); $this->assertEquals(23, ArrayHelper::getValue($arrayObject, 'id')); $object = new Post1(); $this->assertEquals(23, ArrayHelper::getValue($object, 'id')); } - public function testGetValueNonexistingProperties1() + public function testGetValueNonexistingProperties1(): void { try { $object = new Post1(); ArrayHelper::getValue($object, 'nonExisting'); - } catch (\Throwable $th) { + } catch (Throwable $th) { $this->assertEquals('Undefined property: yiiunit\framework\helpers\Post1::$nonExisting', $th->getMessage()); } } - public function testGetValueNonexistingPropertiesForArrayObject() + public function testGetValueNonexistingPropertiesForArrayObject(): void { - $arrayObject = new \ArrayObject(['id' => 23], \ArrayObject::ARRAY_AS_PROPS); + $arrayObject = new ArrayObject(['id' => 23], ArrayObject::ARRAY_AS_PROPS); $this->assertNull(ArrayHelper::getValue($arrayObject, 'nonExisting')); } - public function testGetValueFromArrayAccess() + public function testGetValueFromArrayAccess(): void { $arrayAccessibleObject = new ArrayAccessibleObject([ 'one' => 1, @@ -957,7 +965,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals(1, ArrayHelper::getValue($arrayAccessibleObject, 'one')); } - public function testGetValueWithDotsFromArrayAccess() + public function testGetValueWithDotsFromArrayAccess(): void { $arrayAccessibleObject = new ArrayAccessibleObject([ 'one' => 1, @@ -970,7 +978,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals('dot', ArrayHelper::getValue($arrayAccessibleObject, 'key.with.dot')); } - public function testGetValueNonexistingArrayAccess() + public function testGetValueNonexistingArrayAccess(): void { $arrayAccessibleObject = new ArrayAccessibleObject([ 'one' => 1, @@ -1217,13 +1225,13 @@ class ArrayHelperTest extends TestCase * @param mixed $value * @param mixed $expected */ - public function testSetValue($array_input, $key, $value, $expected) + public function testSetValue($array_input, $key, $value, $expected): void { ArrayHelper::setValue($array_input, $key, $value); $this->assertEquals($expected, $array_input); } - public function testIsAssociative() + public function testIsAssociative(): void { $this->assertFalse(ArrayHelper::isAssociative('test')); $this->assertFalse(ArrayHelper::isAssociative([])); @@ -1234,7 +1242,7 @@ class ArrayHelperTest extends TestCase $this->assertTrue(ArrayHelper::isAssociative(['name' => 1, 'value' => 'test', 3], false)); } - public function testIsIndexed() + public function testIsIndexed(): void { $this->assertFalse(ArrayHelper::isIndexed('test')); $this->assertTrue(ArrayHelper::isIndexed([])); @@ -1244,7 +1252,7 @@ class ArrayHelperTest extends TestCase $this->assertFalse(ArrayHelper::isIndexed(['a' => 'b'], false)); } - public function testHtmlEncode() + public function testHtmlEncode(): void { $array = [ 'abc' => '123', @@ -1281,7 +1289,7 @@ class ArrayHelperTest extends TestCase ], ArrayHelper::htmlEncode($array, false)); } - public function testHtmlDecode() + public function testHtmlDecode(): void { $array = [ 'abc' => '123', @@ -1321,70 +1329,70 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, ArrayHelper::htmlDecode($array, false)); } - public function testIsIn() + public function testIsIn(): void { - $this->assertTrue(ArrayHelper::isIn('a', new \ArrayObject(['a', 'b']))); + $this->assertTrue(ArrayHelper::isIn('a', new ArrayObject(['a', 'b']))); $this->assertTrue(ArrayHelper::isIn('a', ['a', 'b'])); - $this->assertTrue(ArrayHelper::isIn('1', new \ArrayObject([1, 'b']))); + $this->assertTrue(ArrayHelper::isIn('1', new ArrayObject([1, 'b']))); $this->assertTrue(ArrayHelper::isIn('1', [1, 'b'])); - $this->assertFalse(ArrayHelper::isIn('1', new \ArrayObject([1, 'b']), true)); + $this->assertFalse(ArrayHelper::isIn('1', new ArrayObject([1, 'b']), true)); $this->assertFalse(ArrayHelper::isIn('1', [1, 'b'], true)); - $this->assertTrue(ArrayHelper::isIn(['a'], new \ArrayObject([['a'], 'b']))); - $this->assertFalse(ArrayHelper::isIn('a', new \ArrayObject([['a'], 'b']))); + $this->assertTrue(ArrayHelper::isIn(['a'], new ArrayObject([['a'], 'b']))); + $this->assertFalse(ArrayHelper::isIn('a', new ArrayObject([['a'], 'b']))); $this->assertFalse(ArrayHelper::isIn('a', [['a'], 'b'])); } - public function testIsInStrict() + public function testIsInStrict(): void { // strict comparison - $this->assertTrue(ArrayHelper::isIn(1, new \ArrayObject([1, 'a']), true)); + $this->assertTrue(ArrayHelper::isIn(1, new ArrayObject([1, 'a']), true)); $this->assertTrue(ArrayHelper::isIn(1, [1, 'a'], true)); - $this->assertFalse(ArrayHelper::isIn('1', new \ArrayObject([1, 'a']), true)); + $this->assertFalse(ArrayHelper::isIn('1', new ArrayObject([1, 'a']), true)); $this->assertFalse(ArrayHelper::isIn('1', [1, 'a'], true)); } - public function testInException() + public function testInException(): void { $this->expectException('yii\base\InvalidParamException'); $this->expectExceptionMessage('Argument $haystack must be an array or implement Traversable'); ArrayHelper::isIn('value', null); } - public function testIsSubset() + public function testIsSubset(): void { - $this->assertTrue(ArrayHelper::isSubset(['a'], new \ArrayObject(['a', 'b']))); - $this->assertTrue(ArrayHelper::isSubset(new \ArrayObject(['a']), ['a', 'b'])); + $this->assertTrue(ArrayHelper::isSubset(['a'], new ArrayObject(['a', 'b']))); + $this->assertTrue(ArrayHelper::isSubset(new ArrayObject(['a']), ['a', 'b'])); - $this->assertTrue(ArrayHelper::isSubset([1], new \ArrayObject(['1', 'b']))); - $this->assertTrue(ArrayHelper::isSubset(new \ArrayObject([1]), ['1', 'b'])); + $this->assertTrue(ArrayHelper::isSubset([1], new ArrayObject(['1', 'b']))); + $this->assertTrue(ArrayHelper::isSubset(new ArrayObject([1]), ['1', 'b'])); - $this->assertFalse(ArrayHelper::isSubset([1], new \ArrayObject(['1', 'b']), true)); - $this->assertFalse(ArrayHelper::isSubset(new \ArrayObject([1]), ['1', 'b'], true)); + $this->assertFalse(ArrayHelper::isSubset([1], new ArrayObject(['1', 'b']), true)); + $this->assertFalse(ArrayHelper::isSubset(new ArrayObject([1]), ['1', 'b'], true)); } - public function testIsSubsetException() + public function testIsSubsetException(): void { $this->expectException('yii\base\InvalidParamException'); $this->expectExceptionMessage('Argument $needles must be an array or implement Traversable'); - ArrayHelper::isSubset('a', new \ArrayObject(['a', 'b'])); + ArrayHelper::isSubset('a', new ArrayObject(['a', 'b'])); } - public function testIsArray() + public function testIsArray(): void { $this->assertTrue(ArrayHelper::isTraversable(['a'])); - $this->assertTrue(ArrayHelper::isTraversable(new \ArrayObject(['1']))); - $this->assertFalse(ArrayHelper::isTraversable(new \stdClass())); + $this->assertTrue(ArrayHelper::isTraversable(new ArrayObject(['1']))); + $this->assertFalse(ArrayHelper::isTraversable(new stdClass())); $this->assertFalse(ArrayHelper::isTraversable('A,B,C')); $this->assertFalse(ArrayHelper::isTraversable(12)); $this->assertFalse(ArrayHelper::isTraversable(false)); $this->assertFalse(ArrayHelper::isTraversable(null)); } - public function testFilter() + public function testFilter(): void { $array = [ 'A' => [ @@ -1508,7 +1516,7 @@ class ArrayHelperTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/18395 */ - public function testFilterForIntegerKeys() + public function testFilterForIntegerKeys(): void { $array = ['a', 'b', ['c', 'd']]; @@ -1518,18 +1526,18 @@ class ArrayHelperTest extends TestCase $this->assertEquals([2 => [1 => 'd']], ArrayHelper::filter($array, [2, '!2.0'])); } - public function testFilterWithInvalidValues() + public function testFilterWithInvalidValues(): void { $array = ['a' => 'b']; - $this->assertEquals([], ArrayHelper::filter($array, [new \stdClass()])); + $this->assertEquals([], ArrayHelper::filter($array, [new stdClass()])); $this->assertEquals([], ArrayHelper::filter($array, [['a']])); } /** * @see https://github.com/yiisoft/yii2/issues/18086 */ - public function testArrayAccessWithPublicProperty() + public function testArrayAccessWithPublicProperty(): void { $data = new ArrayAccessibleObject(['value' => 123]); @@ -1541,7 +1549,7 @@ class ArrayHelperTest extends TestCase * https://github.com/yiisoft/yii2/commit/35fb9c624893855317e5fe52e6a21f6518a9a31c changed the way * ArrayHelper works with existing object properties in case of ArrayAccess. */ - public function testArrayAccessWithMagicProperty() + public function testArrayAccessWithMagicProperty(): void { $model = new MagicModel(); $this->assertEquals(42, ArrayHelper::getValue($model, 'magic')); @@ -1553,7 +1561,7 @@ class ArrayHelperTest extends TestCase * * @return void */ - public function testRecursiveSort($expected_result, $input_array) + public function testRecursiveSort($expected_result, $input_array): void { $actual = ArrayHelper::recursiveSort($input_array); $this->assertEquals($expected_result, $actual); @@ -1614,7 +1622,7 @@ class ArrayHelperTest extends TestCase ]; } - public function testFlatten() + public function testFlatten(): void { // Test with deeply nested arrays $array = [ @@ -1703,7 +1711,7 @@ class ArrayHelperTest extends TestCase $this->assertEquals($expected, $result); } - public function testFlattenEdgeCases() + public function testFlattenEdgeCases(): void { // Empty array $array = []; @@ -1758,7 +1766,7 @@ class Post3 extends BaseObject /** @var BaseObject */ public $subObject; - public function init() + public function init(): void { $this->subObject = new Post2(); } @@ -1774,8 +1782,8 @@ class ArrayAccessibleObject implements ArrayAccess $this->container = $container; } - #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + #[ReturnTypeWillChange] + public function offsetSet($offset, $value): void { if (is_null($offset)) { $this->container[] = $value; @@ -1784,19 +1792,19 @@ class ArrayAccessibleObject implements ArrayAccess } } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetExists($offset) { return array_key_exists($offset, $this->container); } - #[\ReturnTypeWillChange] - public function offsetUnset($offset) + #[ReturnTypeWillChange] + public function offsetUnset($offset): void { unset($this->container[$offset]); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetGet($offset) { return $this->offsetExists($offset) ? $this->container[$offset] : null; @@ -1820,31 +1828,31 @@ class TraversableArrayAccessibleObject extends ArrayAccessibleObject implements return array_key_exists($keyIndex, $keys) ? $keys[$keyIndex] : false; } - #[\ReturnTypeWillChange] - public function rewind() + #[ReturnTypeWillChange] + public function rewind(): void { $this->position = 0; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function current() { return $this->offsetGet($this->getContainerKey($this->position)); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function key() { return $this->getContainerKey($this->position); } - #[\ReturnTypeWillChange] - public function next() + #[ReturnTypeWillChange] + public function next(): void { ++$this->position; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function valid() { $key = $this->getContainerKey($this->position); diff --git a/tests/framework/helpers/BaseConsoleTest.php b/tests/framework/helpers/BaseConsoleTest.php index d6e432ad79..8ccaee812a 100644 --- a/tests/framework/helpers/BaseConsoleTest.php +++ b/tests/framework/helpers/BaseConsoleTest.php @@ -22,7 +22,7 @@ class BaseConsoleTest extends TestCase /** * @test */ - public function renderColoredString() + public function renderColoredString(): void { $data = '%yfoo'; $actual = BaseConsole::renderColoredString($data); @@ -37,7 +37,7 @@ class BaseConsoleTest extends TestCase /** * @test */ - public function ansiColorizedSubstr_withoutColors() + public function ansiColorizedSubstr_withoutColors(): void { $str = 'FooBar'; @@ -62,7 +62,7 @@ class BaseConsoleTest extends TestCase * @param $length * @param $expected */ - public function ansiColorizedSubstr_withColors($str, $start, $length, $expected) + public function ansiColorizedSubstr_withColors($str, $start, $length, $expected): void { $ansiStr = BaseConsole::renderColoredString($str); @@ -82,7 +82,7 @@ class BaseConsoleTest extends TestCase ]; } - public function testAnsiStrlen() + public function testAnsiStrlen(): void { $this->assertSame(3, BaseConsole::ansiStrlen('Foo')); $this->assertSame(3, BaseConsole::ansiStrlen(BaseConsole::renderColoredString('Bar%y'))); diff --git a/tests/framework/helpers/BaseUrlTest.php b/tests/framework/helpers/BaseUrlTest.php index 9bcd39ef98..28d1ca7358 100644 --- a/tests/framework/helpers/BaseUrlTest.php +++ b/tests/framework/helpers/BaseUrlTest.php @@ -11,19 +11,19 @@ use yii\helpers\BaseUrl; class BaseUrlTest extends TestCase { /** @dataProvider relativeTrueUrlProvider */ - public function testIsRelativeWillReturnTrue($url) + public function testIsRelativeWillReturnTrue($url): void { $this->assertTrue(BaseUrl::isRelative($url)); } /** @dataProvider relativeFalseUrlProvider */ - public function testIsRelativeWillReturnFalse($url) + public function testIsRelativeWillReturnFalse($url): void { $this->assertFalse(BaseUrl::isRelative($url)); } /** @dataProvider ensureSchemeUrlProvider */ - public function testEnsureScheme($url, $scheme, $expected) + public function testEnsureScheme($url, $scheme, $expected): void { $this->assertEquals($expected, BaseUrl::ensureScheme($url, $scheme)); } diff --git a/tests/framework/helpers/ConsoleTest.php b/tests/framework/helpers/ConsoleTest.php index 9e6f956fdf..51698ab405 100644 --- a/tests/framework/helpers/ConsoleTest.php +++ b/tests/framework/helpers/ConsoleTest.php @@ -86,7 +86,7 @@ class ConsoleTest extends TestCase rewind(ConsoleStub::$inputStream); } - public function testStripAnsiFormat() + public function testStripAnsiFormat(): void { ob_start(); ob_implicit_flush(false); @@ -201,12 +201,12 @@ class ConsoleTest extends TestCase * @param string $ansi * @param string $html */ - public function testAnsi2Html($ansi, $html) + public function testAnsi2Html($ansi, $html): void { $this->assertEquals($html, Console::ansiToHtml($ansi)); } - public function testErrorSummary() + public function testErrorSummary(): void { $model = new TestConsoleModel(); $model->name = 'not_an_integer'; @@ -221,7 +221,7 @@ class ConsoleTest extends TestCase /** * @covers \yii\helpers\BaseConsole::input() */ - public function testInput() + public function testInput(): void { $this->sendInput('test1'); $result = ConsoleStub::input(); @@ -239,7 +239,7 @@ class ConsoleTest extends TestCase /** * @covers \yii\helpers\BaseConsole::output() */ - public function testOutput() + public function testOutput(): void { $result = ConsoleStub::output('Smth'); $this->assertEquals('Smth' . PHP_EOL, $this->readOutput()); @@ -249,7 +249,7 @@ class ConsoleTest extends TestCase /** * @covers \yii\helpers\BaseConsole::error() */ - public function testError() + public function testError(): void { $result = ConsoleStub::error('SomeError'); $this->assertEquals('SomeError' . PHP_EOL, $this->readOutput(ConsoleStub::$errorStream)); @@ -259,7 +259,7 @@ class ConsoleTest extends TestCase /** * @covers \yii\helpers\BaseConsole::prompt() */ - public function testPrompt() + public function testPrompt(): void { // testing output variations @@ -350,7 +350,7 @@ class ConsoleTest extends TestCase /** * @covers \yii\helpers\BaseConsole::confirm() */ - public function testConfirm() + public function testConfirm(): void { $this->sendInput('y'); ConsoleStub::confirm('Are you sure?'); @@ -392,7 +392,7 @@ class ConsoleTest extends TestCase /** * @covers \yii\helpers\BaseConsole::select() */ - public function testSelect() + public function testSelect(): void { $options = [ 'c' => 'cat', @@ -457,7 +457,7 @@ class TestConsoleModel extends DynamicModel ]; } - public function init() + public function init(): void { $this->defineAttribute('name'); } diff --git a/tests/framework/helpers/FileHelperTest.php b/tests/framework/helpers/FileHelperTest.php index 88f01bba4b..7df3c08d05 100644 --- a/tests/framework/helpers/FileHelperTest.php +++ b/tests/framework/helpers/FileHelperTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\helpers; +use Exception; use stdClass; use Yii; use yii\helpers\FileHelper; @@ -150,7 +151,7 @@ class FileHelperTest extends TestCase // Tests : - public function testCreateDirectory() + public function testCreateDirectory(): void { $basePath = $this->testFilePath; $dirName = $basePath . DIRECTORY_SEPARATOR . 'test_dir_level_1' . DIRECTORY_SEPARATOR . 'test_dir_level_2'; @@ -166,7 +167,7 @@ class FileHelperTest extends TestCase /** * @depends testCreateDirectory */ - public function testCopyDirectory() + public function testCopyDirectory(): void { $srcDirName = 'test_src_dir'; $files = [ @@ -191,7 +192,7 @@ class FileHelperTest extends TestCase } } - public function testCopyDirectoryRecursive() + public function testCopyDirectoryRecursive(): void { $srcDirName = 'test_src_dir_rec'; $structure = [ @@ -232,7 +233,7 @@ class FileHelperTest extends TestCase $checker($structure, $dstDirName); } - public function testCopyDirectoryNotRecursive() + public function testCopyDirectoryNotRecursive(): void { $srcDirName = 'test_src_dir_not_rec'; $structure = [ @@ -273,7 +274,7 @@ class FileHelperTest extends TestCase /** * @depends testCopyDirectory */ - public function testCopyDirectoryPermissions() + public function testCopyDirectoryPermissions(): void { if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped("Can't reliably test it on Windows because fileperms() always return 0777."); @@ -309,7 +310,7 @@ class FileHelperTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/10710 */ - public function testCopyDirectoryToItself() + public function testCopyDirectoryToItself(): void { $dirName = 'test_dir'; @@ -326,7 +327,7 @@ class FileHelperTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/10710 */ - public function testCopyDirToSubdirOfItself() + public function testCopyDirToSubdirOfItself(): void { $this->createFileStructure([ 'data' => [], @@ -344,7 +345,7 @@ class FileHelperTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/10710 */ - public function testCopyDirToAnotherWithSameName() + public function testCopyDirToAnotherWithSameName(): void { $this->createFileStructure([ 'data' => [], @@ -361,7 +362,7 @@ class FileHelperTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/10710 */ - public function testCopyDirWithSameName() + public function testCopyDirWithSameName(): void { $this->createFileStructure([ 'data' => [], @@ -376,7 +377,7 @@ class FileHelperTest extends TestCase $this->assertTrue(true); } - public function testRemoveDirectory() + public function testRemoveDirectory(): void { $dirName = 'test_dir_for_remove'; $this->createFileStructure([ @@ -401,7 +402,7 @@ class FileHelperTest extends TestCase FileHelper::removeDirectory($basePath . DIRECTORY_SEPARATOR . 'nonExisting'); } - public function testRemoveDirectorySymlinks1() + public function testRemoveDirectorySymlinks1(): void { if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Cannot test this on MS Windows since symlinks are uncommon for it.'); @@ -444,7 +445,7 @@ class FileHelperTest extends TestCase $this->assertFileDoesNotExist($basePath . 'symlinks' . DIRECTORY_SEPARATOR . 'symlinked-directory' . DIRECTORY_SEPARATOR . 'standard-file-1'); } - public function testRemoveDirectorySymlinks2() + public function testRemoveDirectorySymlinks2(): void { if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Cannot test this on MS Windows since symlinks are uncommon for it.'); @@ -487,7 +488,7 @@ class FileHelperTest extends TestCase $this->assertFileDoesNotExist($basePath . 'symlinks' . DIRECTORY_SEPARATOR . 'symlinked-directory' . DIRECTORY_SEPARATOR . 'standard-file-1'); } - public function testFindFiles() + public function testFindFiles(): void { $dirName = 'test_dir'; $this->createFileStructure([ @@ -518,7 +519,7 @@ class FileHelperTest extends TestCase /** * @depends testFindFiles */ - public function testFindFileFilter() + public function testFindFileFilter(): void { $dirName = 'test_dir'; $passedFileName = 'passed.txt'; @@ -543,7 +544,7 @@ class FileHelperTest extends TestCase /** * @depends testFindFiles */ - public function testFindFilesRecursiveWithSymLink() + public function testFindFilesRecursiveWithSymLink(): void { $dirName = 'test_dir'; $this->createFileStructure([ @@ -571,7 +572,7 @@ class FileHelperTest extends TestCase /** * @depends testFindFiles */ - public function testFindFilesNotRecursive() + public function testFindFilesNotRecursive(): void { $dirName = 'test_dir'; $this->createFileStructure([ @@ -595,7 +596,7 @@ class FileHelperTest extends TestCase /** * @depends testFindFiles */ - public function testFindFilesExclude() + public function testFindFilesExclude(): void { $basePath = $this->testFilePath . DIRECTORY_SEPARATOR; $dirs = ['', 'one', 'one' . DIRECTORY_SEPARATOR . 'two', 'three']; @@ -673,7 +674,7 @@ class FileHelperTest extends TestCase /** * @depends testFindFilesExclude */ - public function testFindFilesCaseSensitive() + public function testFindFilesCaseSensitive(): void { $dirName = 'test_dir'; $this->createFileStructure([ @@ -700,7 +701,7 @@ class FileHelperTest extends TestCase $this->assertCount(2, $foundFiles); } - public function testGetMimeTypeByExtension() + public function testGetMimeTypeByExtension(): void { $magicFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type.php'; $mimeTypeMap = [ @@ -717,7 +718,7 @@ class FileHelperTest extends TestCase } } - public function testGetMimeType() + public function testGetMimeType(): void { $file = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type_test.txt'; file_put_contents($file, 'some text'); @@ -732,7 +733,7 @@ class FileHelperTest extends TestCase $this->assertTrue(in_array(FileHelper::getMimeType($file), ['application/json', 'text/plain'])); } - public function testGetUploadedImageMimeTypes() + public function testGetUploadedImageMimeTypes(): void { $ds = DIRECTORY_SEPARATOR; $phpunitPath = Yii::getAlias('@yiiunit'); @@ -750,7 +751,7 @@ class FileHelperTest extends TestCase $this->assertEquals('image/jpeg', FileHelper::getMimeType($jpgFile)); } - public function testNormalizePath() + public function testNormalizePath(): void { $ds = DIRECTORY_SEPARATOR; $this->assertEquals("{$ds}a{$ds}b", FileHelper::normalizePath('//a\b/')); @@ -784,7 +785,7 @@ class FileHelperTest extends TestCase $this->assertEquals('ftp://192.168.1.100/test', FileHelper::normalizePath('ftp://192.168.1.100/test/')); } - public function testLocalizedDirectory() + public function testLocalizedDirectory(): void { $this->createFileStructure([ 'views' => [ @@ -815,7 +816,7 @@ class FileHelperTest extends TestCase * @depends testCopyDirectory * @depends testFindFiles */ - public function testCopyDirectoryExclude() + public function testCopyDirectoryExclude(): void { $srcDirName = 'test_src_dir'; $textFiles = [ @@ -876,7 +877,7 @@ class FileHelperTest extends TestCase * @depends testCopyDirectory * @depends testFindFiles */ - public function testCopyDirectoryEmptyDirectories() + public function testCopyDirectoryEmptyDirectories(): void { list($basePath, $srcDirName) = $this->setupCopyEmptyDirectoriesTest(); @@ -901,7 +902,7 @@ class FileHelperTest extends TestCase * @depends testCopyDirectory * @depends testFindFiles */ - public function testCopyDirectoryNoEmptyDirectories() + public function testCopyDirectoryNoEmptyDirectories(): void { list($basePath, $srcDirName) = $this->setupCopyEmptyDirectoriesTest(); @@ -920,7 +921,7 @@ class FileHelperTest extends TestCase $this->assertFileDoesNotExist($dstDirName . DIRECTORY_SEPARATOR . 'dir3'); } - public function testFindDirectories() + public function testFindDirectories(): void { $dirName = 'test_dir'; $this->createFileStructure([ @@ -972,7 +973,7 @@ class FileHelperTest extends TestCase $this->assertEquals($expectedFiles, $foundFiles); } - public function testChangeOwnership() + public function testChangeOwnership(): void { if (DIRECTORY_SEPARATOR !== '/') { $this->markTestSkipped('FileHelper::changeOwnership() fails silently on Windows, nothing to test.'); @@ -1221,7 +1222,7 @@ class FileHelperTest extends TestCase $this->assertEquals('0' . decoct($fileMode), substr(decoct(fileperms($testFile)), -4), 'Expected created test file mode to be changed.'); } - public function testChangeOwnershipNonExistingUser() + public function testChangeOwnershipNonExistingUser(): void { $dirName = 'change_ownership_non_existing_user'; $fileName = 'file_1.txt'; @@ -1237,8 +1238,8 @@ class FileHelperTest extends TestCase $ownership = 'non_existing_user'; try { FileHelper::changeOwnership($testFile, $ownership); - throw new \Exception('FileHelper::changeOwnership() should have thrown error for non existing user.'); - } catch (\Exception $e) { + throw new Exception('FileHelper::changeOwnership() should have thrown error for non existing user.'); + } catch (Exception $e) { $this->assertEquals('chown(): Unable to find uid for non_existing_user', $e->getMessage()); } } @@ -1249,7 +1250,7 @@ class FileHelperTest extends TestCase * @param mixed $ownership * @param mixed $mode */ - public function testChangeOwnershipInvalidArguments($useFile, $ownership, $mode) + public function testChangeOwnershipInvalidArguments($useFile, $ownership, $mode): void { $dirName = 'change_ownership_invalid_arguments'; $fileName = 'file_1.txt'; @@ -1282,7 +1283,7 @@ class FileHelperTest extends TestCase * @param array $extensions * @return void */ - public function testGetExtensionsByMimeType($mimeType, $extensions) + public function testGetExtensionsByMimeType($mimeType, $extensions): void { $this->assertEquals($extensions, FileHelper::getExtensionsByMimeType($mimeType)); } @@ -1317,7 +1318,7 @@ class FileHelperTest extends TestCase * @param array $extension * @return void */ - public function testGetExtensionByMimeType($mimeType, $preferShort, $extension) + public function testGetExtensionByMimeType($mimeType, $preferShort, $extension): void { $this->assertEquals($extension, FileHelper::getExtensionByMimeType($mimeType, $preferShort)); } diff --git a/tests/framework/helpers/FormatConverterTest.php b/tests/framework/helpers/FormatConverterTest.php index b18bf50c58..728dbc239d 100644 --- a/tests/framework/helpers/FormatConverterTest.php +++ b/tests/framework/helpers/FormatConverterTest.php @@ -38,13 +38,13 @@ class FormatConverterTest extends TestCase IntlTestHelper::resetIntlStatus(); } - public function testIntlIcuToPhpShortForm() + public function testIntlIcuToPhpShortForm(): void { $this->assertEqualsAnyWhitespace('n/j/y', FormatConverter::convertDateIcuToPhp('short', 'date', 'en-US')); $this->assertEqualsAnyWhitespace('d.m.y', FormatConverter::convertDateIcuToPhp('short', 'date', 'de-DE')); } - public function testIntlIcuToPhpShortFormDefaultLang() + public function testIntlIcuToPhpShortFormDefaultLang(): void { Yii::$app->language = 'en'; $this->assertEquals('n/j/y', FormatConverter::convertDateIcuToPhp('short', 'date')); @@ -52,13 +52,13 @@ class FormatConverterTest extends TestCase $this->assertEquals('d.m.y', FormatConverter::convertDateIcuToPhp('short', 'date')); } - public function testIntlIcuToPhpShortFormTime() + public function testIntlIcuToPhpShortFormTime(): void { $this->assertEqualsAnyWhitespace('g:i A', FormatConverter::convertDateIcuToPhp('short', 'time', 'en-US')); $this->assertEqualsAnyWhitespace('H:i', FormatConverter::convertDateIcuToPhp('short', 'time', 'de-DE')); } - public function testIntlIcuToPhpShortFormDateTime() + public function testIntlIcuToPhpShortFormDateTime(): void { $this->assertEqualsAnyWhitespace('n/j/y, g:i A', FormatConverter::convertDateIcuToPhp('short', 'datetime', 'en-US')); $this->assertEquals( @@ -67,7 +67,7 @@ class FormatConverterTest extends TestCase ); } - public function testEscapedIcuToPhpMixedPatterns() + public function testEscapedIcuToPhpMixedPatterns(): void { $this->assertEquals('l, F j, Y \\a\\t g:i:s A T', FormatConverter::convertDateIcuToPhp('EEEE, MMMM d, y \'at\' h:mm:ss a zzzz')); $this->assertEquals('\\o\\\'\\c\\l\\o\\c\\k', FormatConverter::convertDateIcuToPhp('\'o\'\'clock\'')); @@ -182,24 +182,24 @@ class FormatConverterTest extends TestCase /** * @dataProvider providerForICU2PHPPatterns */ - public function testEscapedIcuToPhpSinglePattern($pattern, $expected) + public function testEscapedIcuToPhpSinglePattern($pattern, $expected): void { $this->assertEquals($expected, FormatConverter::convertDateIcuToPhp($pattern)); } - public function testEscapedIcuToJui() + public function testEscapedIcuToJui(): void { $this->assertEquals('DD, MM d, yy \'at\' ', FormatConverter::convertDateIcuToJui('EEEE, MMMM d, y \'at\' zzzz')); $this->assertEquals('\'o\'\'clock\'', FormatConverter::convertDateIcuToJui('\'o\'\'clock\'')); } - public function testIntlIcuToJuiShortForm() + public function testIntlIcuToJuiShortForm(): void { $this->assertEquals('m/d/y', FormatConverter::convertDateIcuToJui('short', 'date', 'en-US')); $this->assertEquals('dd.mm.y', FormatConverter::convertDateIcuToJui('short', 'date', 'de-DE')); } - public function testIntlIcuToJuiShortFormDefaultLang() + public function testIntlIcuToJuiShortFormDefaultLang(): void { Yii::$app->language = 'en'; $this->assertEquals('m/d/y', FormatConverter::convertDateIcuToJui('short', 'date')); @@ -207,13 +207,13 @@ class FormatConverterTest extends TestCase $this->assertEquals('dd.mm.y', FormatConverter::convertDateIcuToJui('short', 'date')); } - public function testIntlIcuToJuiShortFormTime() + public function testIntlIcuToJuiShortFormTime(): void { $this->assertEqualsAnyWhitespace(': ', FormatConverter::convertDateIcuToJui('short', 'time', 'en-US')); $this->assertEqualsAnyWhitespace(':', FormatConverter::convertDateIcuToJui('short', 'time', 'de-DE')); } - public function testIntlIcuToJuiShortFormDateTime() + public function testIntlIcuToJuiShortFormDateTime(): void { $this->assertEqualsAnyWhitespace('m/d/y, : ', FormatConverter::convertDateIcuToJui('short', 'datetime', 'en-US')); $this->assertEquals( @@ -330,12 +330,12 @@ class FormatConverterTest extends TestCase /** * @dataProvider providerForICU2JUIPatterns */ - public function testEscapedIcuToJuiSinglePattern($pattern, $expected) + public function testEscapedIcuToJuiSinglePattern($pattern, $expected): void { $this->assertEquals($expected, FormatConverter::convertDateIcuToJui($pattern)); } - public function testIntlOneDigitIcu() + public function testIntlOneDigitIcu(): void { $formatter = new Formatter(['locale' => 'en-US']); $this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'php:d.n.Y')); @@ -343,7 +343,7 @@ class FormatConverterTest extends TestCase $this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'd.L.yyyy')); } - public function testOneDigitIcu() + public function testOneDigitIcu(): void { $formatter = new Formatter(['locale' => 'en-US']); $this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'php:d.n.Y')); @@ -351,7 +351,7 @@ class FormatConverterTest extends TestCase $this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'd.L.yyyy')); } - public function testIntlUtf8Ru() + public function testIntlUtf8Ru(): void { $this->assertEquals('d M Y \г.', FormatConverter::convertDateIcuToPhp("dd MMM y 'г'.", 'date', 'ru-RU')); $this->assertEquals("dd M yy 'г'.", FormatConverter::convertDateIcuToJui("dd MMM y 'г'.", 'date', 'ru-RU')); @@ -362,7 +362,7 @@ class FormatConverterTest extends TestCase $this->assertMatchesRegularExpression('/24 авг\.? 2014 г\./', $formatter->asDate('2014-8-24', "dd MMM y 'г'.")); } - public function testPhpToICUMixedPatterns() + public function testPhpToICUMixedPatterns(): void { $expected = "yyyy-MM-dd'T'HH:mm:ssxxx"; $actual = FormatConverter::convertDatePhpToIcu('Y-m-d\TH:i:sP'); @@ -475,12 +475,12 @@ class FormatConverterTest extends TestCase /** * @dataProvider providerForPHP2ICUPatterns */ - public function testPhpToICUSinglePattern($pattern, $expected) + public function testPhpToICUSinglePattern($pattern, $expected): void { $this->assertEquals($expected, FormatConverter::convertDatePhpToIcu($pattern)); } - public function testPhpFormatC() + public function testPhpFormatC(): void { $time = time(); @@ -492,7 +492,7 @@ class FormatConverterTest extends TestCase $this->assertEquals(date('c', $time), $formatter->asDatetime($time, 'php:c')); } - public function testEscapedPhpToJuiMixedPatterns() + public function testEscapedPhpToJuiMixedPatterns(): void { $this->assertEquals('dd-mm-yy', FormatConverter::convertDatePhpToJui('d-m-Y')); } @@ -543,7 +543,7 @@ class FormatConverterTest extends TestCase /** * @dataProvider providerForPHP2JUIPatterns */ - public function testEscapedPhpToJuiSinglePattern($pattern, $expected) + public function testEscapedPhpToJuiSinglePattern($pattern, $expected): void { $this->assertEquals($expected, FormatConverter::convertDatePhpToJui($pattern)); } diff --git a/tests/framework/helpers/HtmlTest.php b/tests/framework/helpers/HtmlTest.php index 440f9f156d..0b1fe156a5 100644 --- a/tests/framework/helpers/HtmlTest.php +++ b/tests/framework/helpers/HtmlTest.php @@ -8,6 +8,10 @@ namespace yiiunit\framework\helpers; +use ArrayObject; +use yii\base\InvalidArgumentException; +use Closure; +use yii\base\Model; use Yii; use yii\base\DynamicModel; use yii\db\ArrayExpression; @@ -39,18 +43,18 @@ class HtmlTest extends TestCase ]); } - public function testEncode() + public function testEncode(): void { $this->assertEquals('a<>&"'�', Html::encode("a<>&\"'\x80")); $this->assertEquals('Sam & Dark', Html::encode('Sam & Dark')); } - public function testDecode() + public function testDecode(): void { $this->assertEquals("a<>&\"'", Html::decode('a<>&"'')); } - public function testTag() + public function testTag(): void { $this->assertEquals('
', Html::tag('br')); $this->assertEquals('', Html::tag('span')); @@ -61,7 +65,7 @@ class HtmlTest extends TestCase $this->assertEquals('test', Html::tag(null, 'test')); } - public function testBeginTag() + public function testBeginTag(): void { $this->assertEquals('
', Html::beginTag('br')); $this->assertEquals('', Html::beginTag('span', ['id' => 'test', 'class' => 'title'])); @@ -69,7 +73,7 @@ class HtmlTest extends TestCase $this->assertEquals('', Html::beginTag(false)); } - public function testEndTag() + public function testEndTag(): void { $this->assertEquals('
', Html::endTag('br')); $this->assertEquals('
', Html::endTag('span')); @@ -77,14 +81,14 @@ class HtmlTest extends TestCase $this->assertEquals('', Html::endTag(false)); } - public function testStyle() + public function testStyle(): void { $content = 'a <>'; $this->assertEquals("", Html::style($content)); $this->assertEquals("", Html::style($content, ['type' => 'text/less'])); } - public function testStyleCustomAttribute() + public function testStyleCustomAttribute(): void { $nonce = Yii::$app->security->generateRandomString(); $this->mockApplication([ @@ -99,14 +103,14 @@ class HtmlTest extends TestCase $this->assertEquals("", Html::style($content)); } - public function testScript() + public function testScript(): void { $content = 'a <>'; $this->assertEquals("", Html::script($content)); $this->assertEquals("", Html::script($content, ['type' => 'text/js'])); } - public function testScriptCustomAttribute() + public function testScriptCustomAttribute(): void { $nonce = Yii::$app->security->generateRandomString(); $this->mockApplication([ @@ -121,7 +125,7 @@ class HtmlTest extends TestCase $this->assertEquals("", Html::script($content)); } - public function testCssFile() + public function testCssFile(): void { $this->assertEquals('', Html::cssFile('http://example.com')); $this->assertEquals('', Html::cssFile('')); @@ -130,7 +134,7 @@ class HtmlTest extends TestCase $this->assertEquals('', Html::cssFile('http://example.com', ['noscript' => true])); } - public function testJsFile() + public function testJsFile(): void { $this->assertEquals('', Html::jsFile('http://example.com')); $this->assertEquals('', Html::jsFile('')); @@ -138,7 +142,7 @@ class HtmlTest extends TestCase $this->assertEquals("\n" . '' . "\n", Html::jsFile('http://example.com', ['condition' => '(gte IE 9)|(!IE)'])); } - public function testCsrfMetaTagsDisableCsrfValidation() + public function testCsrfMetaTagsDisableCsrfValidation(): void { $this->mockApplication([ 'components' => [ @@ -151,7 +155,7 @@ class HtmlTest extends TestCase $this->assertEquals('', Html::csrfMetaTags()); } - public function testCsrfMetaTagsEnableCsrfValidation() + public function testCsrfMetaTagsEnableCsrfValidation(): void { $this->mockApplication([ 'components' => [ @@ -170,7 +174,7 @@ class HtmlTest extends TestCase $this->assertStringMatchesFormat($pattern, $actual); } - public function testCsrfMetaTagsEnableCsrfValidationWithoutCookieValidationKey() + public function testCsrfMetaTagsEnableCsrfValidationWithoutCookieValidationKey(): void { $this->mockApplication([ 'components' => [ @@ -191,7 +195,7 @@ class HtmlTest extends TestCase * @param string $expected * @param string $method */ - public function testBeginFormSimulateViaPost($expected, $method) + public function testBeginFormSimulateViaPost($expected, $method): void { $actual = Html::beginForm('/foo', $method); $this->assertStringMatchesFormat($expected, $actual); @@ -213,7 +217,7 @@ class HtmlTest extends TestCase ]; } - public function testBeginForm() + public function testBeginForm(): void { $this->assertEquals('
', Html::beginForm()); $this->assertEquals('', Html::beginForm('/example', 'get')); @@ -228,12 +232,12 @@ class HtmlTest extends TestCase $this->assertStringMatchesFormat($expected, $actual); } - public function testEndForm() + public function testEndForm(): void { $this->assertEquals('
', Html::endForm()); } - public function testA() + public function testA(): void { $this->assertEquals('something<>', Html::a('something<>')); $this->assertEquals('something', Html::a('something', '/example')); @@ -242,7 +246,7 @@ class HtmlTest extends TestCase $this->assertEquals('Test page', Html::a('Test page', Url::to(['/site/test'], 'https'))); } - public function testMailto() + public function testMailto(): void { $this->assertEquals('test<>', Html::mailto('test<>')); $this->assertEquals('test<>', Html::mailto('test<>', 'test>')); @@ -340,80 +344,80 @@ class HtmlTest extends TestCase * @param string $src * @param array $options */ - public function testImg($expected, $src, $options) + public function testImg($expected, $src, $options): void { $this->assertEquals($expected, Html::img($src, $options)); } - public function testLabel() + public function testLabel(): void { $this->assertEquals('', Html::label('something<>')); $this->assertEquals('', Html::label('something<>', 'a')); $this->assertEquals('', Html::label('something<>', 'a', ['class' => 'test'])); } - public function testButton() + public function testButton(): void { $this->assertEquals('', Html::button()); $this->assertEquals('', Html::button('content<>', ['name' => 'test', 'value' => 'value'])); $this->assertEquals('', Html::button('content<>', ['type' => 'submit', 'name' => 'test', 'value' => 'value', 'class' => 't'])); } - public function testSubmitButton() + public function testSubmitButton(): void { $this->assertEquals('', Html::submitButton()); $this->assertEquals('', Html::submitButton('content<>', ['name' => 'test', 'value' => 'value', 'class' => 't'])); } - public function testResetButton() + public function testResetButton(): void { $this->assertEquals('', Html::resetButton()); $this->assertEquals('', Html::resetButton('content<>', ['name' => 'test', 'value' => 'value', 'class' => 't'])); } - public function testInput() + public function testInput(): void { $this->assertEquals('', Html::input('text')); $this->assertEquals('', Html::input('text', 'test', 'value', ['class' => 't'])); } - public function testButtonInput() + public function testButtonInput(): void { $this->assertEquals('', Html::buttonInput()); $this->assertEquals('', Html::buttonInput('text', ['name' => 'test', 'class' => 'a'])); } - public function testSubmitInput() + public function testSubmitInput(): void { $this->assertEquals('', Html::submitInput()); $this->assertEquals('', Html::submitInput('text', ['name' => 'test', 'class' => 'a'])); } - public function testResetInput() + public function testResetInput(): void { $this->assertEquals('', Html::resetInput()); $this->assertEquals('', Html::resetInput('text', ['name' => 'test', 'class' => 'a'])); } - public function testTextInput() + public function testTextInput(): void { $this->assertEquals('', Html::textInput('test')); $this->assertEquals('', Html::textInput('test', 'value', ['class' => 't'])); } - public function testHiddenInput() + public function testHiddenInput(): void { $this->assertEquals('', Html::hiddenInput('test')); $this->assertEquals('', Html::hiddenInput('test', 'value', ['class' => 't'])); } - public function testPasswordInput() + public function testPasswordInput(): void { $this->assertEquals('', Html::passwordInput('test')); $this->assertEquals('', Html::passwordInput('test', 'value', ['class' => 't'])); } - public function testFileInput() + public function testFileInput(): void { $this->assertEquals('', Html::fileInput('test')); $this->assertEquals('', Html::fileInput('test', 'value', ['class' => 't'])); @@ -459,12 +463,12 @@ class HtmlTest extends TestCase * @param string $value * @param array $options */ - public function testTextarea($expected, $name, $value, $options) + public function testTextarea($expected, $name, $value, $options): void { $this->assertEquals($expected, Html::textarea($name, $value, $options)); } - public function testRadio() + public function testRadio(): void { $this->assertEquals('', Html::radio('test')); $this->assertEquals('', Html::radio('test', true, ['class' => 'a', 'value' => null])); @@ -493,7 +497,7 @@ class HtmlTest extends TestCase ])); } - public function testCheckbox() + public function testCheckbox(): void { $this->assertEquals('', Html::checkbox('test')); $this->assertEquals('', Html::checkbox('test', true, ['class' => 'a', 'value' => null])); @@ -536,7 +540,7 @@ class HtmlTest extends TestCase ])); } - public function testDropDownList() + public function testDropDownList(): void { $expected = <<<'EOD' @@ -770,7 +774,7 @@ EOD; EOD; - $this->assertEqualsWithoutLE($expected, Html::listBox('test', new \ArrayObject(['value1', 'value2']), $this->getDataItems())); + $this->assertEqualsWithoutLE($expected, Html::listBox('test', new ArrayObject(['value1', 'value2']), $this->getDataItems())); $expected = <<<'EOD' EOD; $this->assertEqualsWithoutLE($expected, Html::listBox('test', [0], $this->getDataItems3())); - $this->assertEqualsWithoutLE($expected, Html::listBox('test', new \ArrayObject([0]), $this->getDataItems3())); + $this->assertEqualsWithoutLE($expected, Html::listBox('test', new ArrayObject([0]), $this->getDataItems3())); $expected = <<<'EOD' EOD; $this->assertEqualsWithoutLE($expected, Html::listBox('test', ['1', 'value3'], $this->getDataItems3())); - $this->assertEqualsWithoutLE($expected, Html::listBox('test', new \ArrayObject(['1', 'value3']), $this->getDataItems3())); + $this->assertEqualsWithoutLE($expected, Html::listBox('test', new ArrayObject(['1', 'value3']), $this->getDataItems3())); } - public function testCheckboxList() + public function testCheckboxList(): void { $this->assertEquals('
', Html::checkboxList('test')); @@ -851,7 +855,7 @@ EOD; ])); - $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', new \ArrayObject(['value2']), $this->getDataItems(), [ + $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', new ArrayObject(['value2']), $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); }, @@ -864,7 +868,7 @@ EOD; EOD; $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', [0], $this->getDataItems3())); - $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', new \ArrayObject([0]), $this->getDataItems3())); + $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', new ArrayObject([0]), $this->getDataItems3())); $expected = <<<'EOD'
@@ -872,7 +876,7 @@ EOD;
EOD; $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', ['1', 'value3'], $this->getDataItems3())); - $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', new \ArrayObject(['1', 'value3']), $this->getDataItems3())); + $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', new ArrayObject(['1', 'value3']), $this->getDataItems3())); $expected = <<<'EOD'
@@ -901,7 +905,7 @@ EOD; $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', [1.1], ['1' => '1', '1.1' => '1.1', '1.10' => '1.10'])); } - public function testRadioListWithArrayExpression() + public function testRadioListWithArrayExpression(): void { $selection = new ArrayExpression(['first']); @@ -918,7 +922,7 @@ EOD;
', $output); } - public function testCheckboxListWithArrayExpression() + public function testCheckboxListWithArrayExpression(): void { $selection = new ArrayExpression(['first']); @@ -935,7 +939,7 @@ EOD; ', $output); } - public function testRenderSelectOptionsWithArrayExpression() + public function testRenderSelectOptionsWithArrayExpression(): void { $selection = new ArrayExpression(['first']); @@ -951,7 +955,7 @@ EOD; ', $output); } - public function testRadioList() + public function testRadioList(): void { $this->assertEquals('
', Html::radioList('test')); @@ -1007,7 +1011,7 @@ EOD; 'tag' => false, ])); - $this->assertEqualsWithoutLE($expected, Html::radioList('test', new \ArrayObject(['value2']), $this->getDataItems(), [ + $this->assertEqualsWithoutLE($expected, Html::radioList('test', new ArrayObject(['value2']), $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); }, @@ -1020,7 +1024,7 @@ EOD; EOD; $this->assertEqualsWithoutLE($expected, Html::radioList('test', [0], $this->getDataItems3())); - $this->assertEqualsWithoutLE($expected, Html::radioList('test', new \ArrayObject([0]), $this->getDataItems3())); + $this->assertEqualsWithoutLE($expected, Html::radioList('test', new ArrayObject([0]), $this->getDataItems3())); $expected = <<<'EOD'
@@ -1028,7 +1032,7 @@ EOD;
EOD; $this->assertEqualsWithoutLE($expected, Html::radioList('test', ['value3'], $this->getDataItems3())); - $this->assertEqualsWithoutLE($expected, Html::radioList('test', new \ArrayObject(['value3']), $this->getDataItems3())); + $this->assertEqualsWithoutLE($expected, Html::radioList('test', new ArrayObject(['value3']), $this->getDataItems3())); $expected = <<<'EOD'
@@ -1057,7 +1061,7 @@ EOD; $this->assertEqualsWithoutLE($expected, Html::radioList('test', ['1.1'], ['1' => '1', '1.1' => '1.1', '1.10' => '1.10'])); } - public function testUl() + public function testUl(): void { $data = [ 1, 'abc', '<>', @@ -1089,7 +1093,7 @@ EOD; $this->assertStringMatchesFormat('%A', Html::ul([], ['tag' => 'foo'])); } - public function testOl() + public function testOl(): void { $data = [ 1, 'abc', '<>', @@ -1121,7 +1125,7 @@ EOD; $this->assertEquals('
    ', Html::ol([], ['class' => 'test'])); } - public function testRenderOptions() + public function testRenderOptions(): void { $data = [ 'value1' => 'label1', @@ -1239,7 +1243,7 @@ EOD; $this->assertEqualsWithoutLE($expected, Html::renderSelectOptions([false], $data, $attributes)); } - public function testRenderTagAttributes() + public function testRenderTagAttributes(): void { $this->assertEquals('', Html::renderTagAttributes([])); $this->assertEquals(' name="test" value="1<>"', Html::renderTagAttributes(['name' => 'test', 'empty' => null, 'value' => '1<>'])); @@ -1282,7 +1286,7 @@ EOD; $this->assertEquals('', Html::renderTagAttributes($attributes)); } - public function testAddCssClass() + public function testAddCssClass(): void { $options = []; Html::addCssClass($options, 'test'); @@ -1320,7 +1324,7 @@ EOD; /** * @depends testAddCssClass */ - public function testMergeCssClass() + public function testMergeCssClass(): void { $options = [ 'class' => [ @@ -1333,7 +1337,7 @@ EOD; $this->assertEquals(['persistent' => 'test1', 'additional' => 'test2'], $options['class']); } - public function testRemoveCssClass() + public function testRemoveCssClass(): void { $options = ['class' => 'test test2 test3']; Html::removeCssClass($options, 'test2'); @@ -1359,7 +1363,7 @@ EOD; $this->assertEquals(['class' => 'test'], $options); } - public function testCssStyleFromArray() + public function testCssStyleFromArray(): void { $this->assertEquals('width: 100px; height: 200px;', Html::cssStyleFromArray([ 'width' => '100px', @@ -1368,7 +1372,7 @@ EOD; $this->assertNull(Html::cssStyleFromArray([])); } - public function testCssStyleToArray() + public function testCssStyleToArray(): void { $this->assertEquals([ 'width' => '100px', @@ -1377,7 +1381,7 @@ EOD; $this->assertEquals([], Html::cssStyleToArray(' ')); } - public function testAddCssStyle() + public function testAddCssStyle(): void { $options = ['style' => 'width: 100px; height: 200px;']; Html::addCssStyle($options, 'width: 110px; color: red;'); @@ -1408,7 +1412,7 @@ EOD; $this->assertEquals('width: 100px; color: red;', $options['style']); } - public function testRemoveCssStyle() + public function testRemoveCssStyle(): void { $options = ['style' => 'width: 110px; height: 200px; color: red;']; Html::removeCssStyle($options, 'width'); @@ -1431,14 +1435,14 @@ EOD; $this->assertEquals('width: 100px;', $options['style']); } - public function testBooleanAttributes() + public function testBooleanAttributes(): void { $this->assertEquals('', Html::input('email', 'mail', null, ['required' => false])); $this->assertEquals('', Html::input('email', 'mail', null, ['required' => true])); $this->assertEquals('', Html::input('email', 'mail', null, ['required' => 'hi'])); } - public function testDataAttributes() + public function testDataAttributes(): void { $this->assertEquals('', Html::tag('link', '', ['src' => 'xyz', 'aria' => ['a' => 1, 'b' => 'c']])); $this->assertEquals('', Html::tag('link', '', ['src' => 'xyz', 'data' => ['a' => 1, 'b' => 'c']])); @@ -1508,7 +1512,7 @@ EOD; * @param array $options * @param string $expectedHtml */ - public function testActiveTextInput($value, array $options, $expectedHtml) + public function testActiveTextInput($value, array $options, $expectedHtml): void { $model = new HtmlTestModel(); $model->name = $value; @@ -1555,7 +1559,7 @@ EOD; * @param string $expectedHtmlForTitle * @param string $expectedHtmlForAlias */ - public function testActiveTextInputMaxLength($value, array $options, $expectedHtmlForTitle, $expectedHtmlForAlias) + public function testActiveTextInputMaxLength($value, array $options, $expectedHtmlForTitle, $expectedHtmlForAlias): void { $model = new HtmlTestModel(); $model->title = $value; @@ -1600,7 +1604,7 @@ EOD; * @param array $options * @param string $expectedHtml */ - public function testActivePasswordInput($value, array $options, $expectedHtml) + public function testActivePasswordInput($value, array $options, $expectedHtml): void { $model = new HtmlTestModel(); $model->name = $value; @@ -1643,7 +1647,7 @@ EOD; * @param array $options * @param string $expectedHtml */ - public function testActiveInput_TypeText($value, array $options, $expectedHtml) + public function testActiveInput_TypeText($value, array $options, $expectedHtml): void { $model = new HtmlTestModel(); $model->name = $value; @@ -1716,9 +1720,9 @@ EOD; * @param string $value * @param array $options * @param string $expectedHtml - * @param \Closure $beforeValidate + * @param Closure $beforeValidate */ - public function testErrorSummary($value, array $options, $expectedHtml, $beforeValidate = null) + public function testErrorSummary($value, array $options, $expectedHtml, $beforeValidate = null): void { $model = new HtmlTestModel(); $model->name = $value; @@ -1730,7 +1734,7 @@ EOD; $this->assertEqualsWithoutLE($expectedHtml, Html::errorSummary($model, $options)); } - public function testError() + public function testError(): void { $model = new HtmlTestModel(); $model->validate(); @@ -1758,7 +1762,7 @@ EOD; * Test that attributes that output same errors, return unique message error * @see https://github.com/yiisoft/yii2/pull/15859 */ - public function testCollectError() + public function testCollectError(): void { $model = new DynamicModel(['attr1', 'attr2']); @@ -1816,7 +1820,7 @@ EOD; * @param array $options * @param string $expectedHtml */ - public function testActiveTextArea($value, array $options, $expectedHtml) + public function testActiveTextArea($value, array $options, $expectedHtml): void { $model = new HtmlTestModel(); $model->description = $value; @@ -1826,7 +1830,7 @@ EOD; /** * @see https://github.com/yiisoft/yii2/issues/10078 */ - public function testCsrfDisable() + public function testCsrfDisable(): void { Yii::$app->request->enableCsrfValidation = true; Yii::$app->request->cookieValidationKey = 'foobar'; @@ -1879,7 +1883,7 @@ EOD; * @param array $options * @param string $expectedHtml */ - public function testActiveRadio($value, array $options, $expectedHtml) + public function testActiveRadio($value, array $options, $expectedHtml): void { $model = new HtmlTestModel(); $model->radio = $value; @@ -1923,7 +1927,7 @@ EOD; * @param array $options * @param string $expectedHtml */ - public function testActiveCheckbox($value, array $options, $expectedHtml) + public function testActiveCheckbox($value, array $options, $expectedHtml): void { $model = new HtmlTestModel(); $model->checkbox = $value; @@ -1975,7 +1979,7 @@ EOD; * @param string $name * @param string $expected */ - public function testAttributeNameValidation($name, $expected) + public function testAttributeNameValidation($name, $expected): void { $this->assertEquals($expected, Html::getAttributeName($name)); } @@ -1985,14 +1989,14 @@ EOD; * * @param string $name */ - public function testAttributeNameException($name) + public function testAttributeNameException($name): void { $this->expectException('yii\base\InvalidArgumentException'); Html::getAttributeName($name); } - public function testActiveFileInput() + public function testActiveFileInput(): void { $expected = ''; $model = new HtmlTestModel(); @@ -2025,16 +2029,16 @@ EOD; $this->assertEqualsWithoutLE($expected, $actual); } - public function testGetAttributeValueInvalidArgumentException() + public function testGetAttributeValueInvalidArgumentException(): void { - $this->expectException(\yii\base\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Attribute name must contain word characters only.'); $model = new HtmlTestModel(); Html::getAttributeValue($model, '-'); } - public function testGetAttributeValue() + public function testGetAttributeValue(): void { $model = new HtmlTestModel(); @@ -2059,28 +2063,28 @@ EOD; $this->assertSame($expected, $actual); } - public function testGetInputNameInvalidArgumentExceptionAttribute() + public function testGetInputNameInvalidArgumentExceptionAttribute(): void { $model = new HtmlTestModel(); - $this->expectException(\yii\base\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Attribute name must contain word characters only.'); Html::getInputName($model, '-'); } - public function testGetInputNameInvalidArgumentExceptionFormName() + public function testGetInputNameInvalidArgumentExceptionFormName(): void { $model = $this->getMockBuilder('yii\\base\\Model')->getMock(); $model->method('formName')->willReturn(''); - $this->expectException(\yii\base\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('cannot be empty for tabular inputs.'); Html::getInputName($model, '[foo]bar'); } - public function testGetInputName() + public function testGetInputName(): void { $model = $this->getMockBuilder('yii\\base\\Model')->getMock(); $model->method('formName')->willReturn(''); @@ -2092,7 +2096,7 @@ EOD; /** * @dataProvider getInputIdDataProvider */ - public function testGetInputId($attributeName, $inputIdExpected) + public function testGetInputId($attributeName, $inputIdExpected): void { $model = new DynamicModel(); $model->defineAttribute($attributeName); @@ -2105,7 +2109,7 @@ EOD; /** * @dataProvider getInputIdByNameDataProvider */ - public function testGetInputIdByName($attributeName, $inputIdExpected) + public function testGetInputIdByName($attributeName, $inputIdExpected): void { $model = new DynamicModel(); $model->defineAttribute($attributeName); @@ -2115,7 +2119,7 @@ EOD; $this->assertSame($inputIdExpected, $inputIdActual); } - public function testEscapeJsRegularExpression() + public function testEscapeJsRegularExpression(): void { $expected = '/[a-z0-9-]+/'; $actual = Html::escapeJsRegularExpression('([a-z0-9-]+)'); @@ -2131,7 +2135,7 @@ EOD; $this->assertSame($expected, $actual); } - public function testActiveDropDownList() + public function testActiveDropDownList(): void { $expected = <<<'HTML' @@ -302,7 +305,7 @@ EOD; $this->assertEquals($expectedValue, $this->activeField->parts['{input}']); } - public function testTextInput() + public function testTextInput(): void { $expectedValue = <<<'EOD' @@ -311,7 +314,7 @@ EOD; $this->assertEquals($expectedValue, $this->activeField->parts['{input}']); } - public function testHiddenInput() + public function testHiddenInput(): void { $expectedValue = <<<'EOD' @@ -320,7 +323,7 @@ EOD; $this->assertEquals($expectedValue, $this->activeField->parts['{input}']); } - public function testListBox() + public function testListBox(): void { $expectedValue = <<<'EOD' '; @@ -598,7 +601,7 @@ EOD; $this->assertEqualsWithoutLE($expectedValue, trim($actualValue)); } - public function testWidget() + public function testWidget(): void { $this->activeField->widget(TestInputWidget::className()); $this->assertEquals('Render: ' . TestInputWidget::className(), $this->activeField->parts['{input}']); @@ -613,7 +616,7 @@ EOD; $this->assertEquals('test-id', $this->activeField->labelOptions['for']); } - public function testWidgetOptions() + public function testWidgetOptions(): void { $this->activeField->form->validationStateOn = ActiveForm::VALIDATION_STATE_ON_INPUT; $this->activeField->model->addError('attributeName', 'error'); @@ -643,7 +646,7 @@ EOD; * * @see https://github.com/yiisoft/yii2/issues/14773 */ - public function testOptionsClass() + public function testOptionsClass(): void { $this->activeField->options = ['class' => 'test-wrapper']; $expectedValue = <<<'HTML' @@ -670,7 +673,7 @@ HTML; $this->assertEqualsWithoutLE($expectedValue, trim($actualValue)); } - public function testInputOptionsTransferToWidget() + public function testInputOptionsTransferToWidget(): void { $widget = $this->activeField->widget(TestMaskedInput::className(), [ 'mask' => '999-999-9999', @@ -701,7 +704,7 @@ HTML; $this->assertStringContainsString('placeholder="pholder_both_direct"', (string) $widget); } - public function testExceptionToString() + public function testExceptionToString(): void { if (PHP_VERSION_ID < 70400) { $this->markTestSkipped('This test is for PHP 7.4+ only'); @@ -709,13 +712,13 @@ HTML; $field = new TestActiveFieldWithException(); - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('Test exception in toString.'); (string) $field; } - public function testExceptionToStringLegacy() + public function testExceptionToStringLegacy(): void { if (PHP_VERSION_ID >= 70400) { $this->markTestSkipped('This test is for PHP < 7.4 only'); @@ -786,7 +789,7 @@ class ActiveFieldExtend extends ActiveField $this->getClientOptionsEmpty = $getClientOptionsEmpty; } - public function setClientOptionsEmpty($value) + public function setClientOptionsEmpty($value): void { $this->getClientOptionsEmpty = (bool) $value; } @@ -801,14 +804,14 @@ class ActiveFieldExtend extends ActiveField } } -class TestValidator extends \yii\validators\Validator +class TestValidator extends Validator { public function clientValidateAttribute($object, $attribute, $view) { return 'return true;'; } - public function setWhenClient($js) + public function setWhenClient($js): void { $this->whenClient = $js; } @@ -821,7 +824,7 @@ class TestInputWidget extends InputWidget */ public static $lastInstance; - public function init() + public function init(): void { parent::init(); self::$lastInstance = $this; @@ -840,7 +843,7 @@ class TestMaskedInput extends MaskedInput */ public static $lastInstance; - public function init() + public function init(): void { parent::init(); self::$lastInstance = $this; @@ -867,6 +870,6 @@ class TestActiveFieldWithException extends ActiveField { public function render($content = null) { - throw new \Exception('Test exception in toString.'); + throw new Exception('Test exception in toString.'); } } diff --git a/tests/framework/widgets/ActiveFormTest.php b/tests/framework/widgets/ActiveFormTest.php index d017f286a3..b5df5feb1d 100644 --- a/tests/framework/widgets/ActiveFormTest.php +++ b/tests/framework/widgets/ActiveFormTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use yii\base\DynamicModel; use yii\base\Widget; use yii\web\View; @@ -16,7 +17,7 @@ use yii\widgets\ActiveForm; /** * @group widgets */ -class ActiveFormTest extends \yiiunit\TestCase +class ActiveFormTest extends TestCase { protected function setUp(): void { @@ -24,7 +25,7 @@ class ActiveFormTest extends \yiiunit\TestCase $this->mockApplication(); } - public function testBooleanAttributes() + public function testBooleanAttributes(): void { $o = ['template' => '{input}']; @@ -63,7 +64,7 @@ EOF, ); } - public function testIssue5356() + public function testIssue5356(): void { $o = ['template' => '{input}']; @@ -89,7 +90,7 @@ EOF, ); } - public function testOutputBuffering() + public function testOutputBuffering(): void { $obLevel = ob_get_level(); ob_start(); @@ -119,7 +120,7 @@ HTML, ); } - public function testRegisterClientScript() + public function testRegisterClientScript(): void { $this->mockWebApplication(); $_SERVER['REQUEST_URI'] = 'http://example.com/'; @@ -151,7 +152,7 @@ HTML, /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; ob_start(); @@ -173,7 +174,7 @@ HTML, * @see https://github.com/yiisoft/yii2/issues/15476 * @see https://github.com/yiisoft/yii2/issues/16892 */ - public function testValidationStateOnInput() + public function testValidationStateOnInput(): void { $model = new DynamicModel(['name']); $model->addError('name', 'I have an error!'); diff --git a/tests/framework/widgets/BlockTest.php b/tests/framework/widgets/BlockTest.php index 50ed5fceb7..ffc65f5c96 100644 --- a/tests/framework/widgets/BlockTest.php +++ b/tests/framework/widgets/BlockTest.php @@ -8,12 +8,13 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use yii\widgets\Block; /** * @group widgets */ -class BlockTest extends \yiiunit\TestCase +class BlockTest extends TestCase { protected function setUp(): void { @@ -25,7 +26,7 @@ class BlockTest extends \yiiunit\TestCase /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; diff --git a/tests/framework/widgets/BreadcrumbsTest.php b/tests/framework/widgets/BreadcrumbsTest.php index 6651600a2e..e898da02f2 100644 --- a/tests/framework/widgets/BreadcrumbsTest.php +++ b/tests/framework/widgets/BreadcrumbsTest.php @@ -8,6 +8,8 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; +use ReflectionMethod; use yii\widgets\Breadcrumbs; /** @@ -15,7 +17,7 @@ use yii\widgets\Breadcrumbs; * * @group widgets */ -class BreadcrumbsTest extends \yiiunit\TestCase +class BreadcrumbsTest extends TestCase { private $breadcrumbs; @@ -30,7 +32,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->breadcrumbs = new Breadcrumbs(); } - public function testHomeLinkNull() + public function testHomeLinkNull(): void { $this->breadcrumbs->homeLink = null; $this->breadcrumbs->links = ['label' => 'My Home Page', 'url' => 'http://my.example.com/yii2/link/page']; @@ -48,12 +50,12 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals($expectedHtml, $actualHtml); } - public function testEmptyLinks() + public function testEmptyLinks(): void { $this->assertNull($this->breadcrumbs->run()); } - public function testHomeLinkFalse() + public function testHomeLinkFalse(): void { $this->breadcrumbs->homeLink = false; $this->breadcrumbs->links = ['label' => 'My Home Page', 'url' => 'http://my.example.com/yii2/link/page']; @@ -70,7 +72,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals($expectedHtml, $actualHtml); } - public function testHomeLink() + public function testHomeLink(): void { $this->breadcrumbs->homeLink = ['label' => 'home-link']; $this->breadcrumbs->links = ['label' => 'My Home Page', 'url' => 'http://my.example.com/yii2/link/page']; @@ -88,7 +90,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals($expectedHtml, $actualHtml); } - public function testRenderItemException() + public function testRenderItemException(): void { $link = ['url' => 'http://localhost/yii2']; $method = $this->reflectMethod(); @@ -96,7 +98,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $method->invoke($this->breadcrumbs, $link, $this->breadcrumbs->itemTemplate); } - public function testRenderItemLabelOnly() + public function testRenderItemLabelOnly(): void { $link = ['label' => 'My-
    Test-Label']; $method = $this->reflectMethod(); @@ -111,7 +113,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals("
  1. My-
    Test-Label
  2. \n", $unencodedValue); } - public function testEncodeOverride() + public function testEncodeOverride(): void { $link = ['label' => 'My-
    Test-Label', 'encode' => false]; $method = $this->reflectMethod(); @@ -126,7 +128,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals("
  3. My-
    Test-Label
  4. \n", $unencodedValue); } - public function testRenderItemWithLabelAndUrl() + public function testRenderItemWithLabelAndUrl(): void { $link = ['label' => 'My-
    Test-Label', 'url' => 'http://localhost/yii2']; $method = $this->reflectMethod(); @@ -140,7 +142,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals("
  5. My-
    Test-Label
  6. \n", $unencodedValue); } - public function testRenderItemTemplate() + public function testRenderItemTemplate(): void { $link = ['label' => 'My-
    Test-Label', 'url' => 'http://localhost/yii2', 'template' => "{link}\n"]; $method = $this->reflectMethod(); @@ -154,7 +156,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals("My-
    Test-Label
    \n", $unencodedValue); } - public function testExtraOptions() + public function testExtraOptions(): void { $link = [ 'label' => 'demo', @@ -166,7 +168,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $this->assertEquals('
  7. demo
  8. ' . "\n", $result); } - public function testTag() + public function testTag(): void { $this->breadcrumbs->homeLink = ['label' => 'home-link']; $this->breadcrumbs->links = ['label' => 'My Home Page', 'url' => 'http://my.example.com/yii2/link/page']; @@ -193,7 +195,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase */ protected function reflectMethod($class = '\yii\widgets\Breadcrumbs', $method = 'renderItem') { - $value = new \ReflectionMethod($class, $method); + $value = new ReflectionMethod($class, $method); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible // @link https://wiki.php.net/rfc/make-reflection-setaccessible-no-op diff --git a/tests/framework/widgets/ContentDecoratorTest.php b/tests/framework/widgets/ContentDecoratorTest.php index 5af53edcbc..7ccb68da29 100644 --- a/tests/framework/widgets/ContentDecoratorTest.php +++ b/tests/framework/widgets/ContentDecoratorTest.php @@ -8,12 +8,13 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use yii\widgets\ContentDecorator; /** * @group widgets */ -class ContentDecoratorTest extends \yiiunit\TestCase +class ContentDecoratorTest extends TestCase { protected function setUp(): void { @@ -25,7 +26,7 @@ class ContentDecoratorTest extends \yiiunit\TestCase /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; diff --git a/tests/framework/widgets/DetailViewTest.php b/tests/framework/widgets/DetailViewTest.php index beb11d3c84..1ecc72376c 100644 --- a/tests/framework/widgets/DetailViewTest.php +++ b/tests/framework/widgets/DetailViewTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use yii\base\Arrayable; use yii\base\ArrayableTrait; use yii\base\Model; @@ -16,7 +17,7 @@ use yii\widgets\DetailView; /** * @group widgets */ -class DetailViewTest extends \yiiunit\TestCase +class DetailViewTest extends TestCase { /** @var DetailView */ public $detailView; @@ -28,7 +29,7 @@ class DetailViewTest extends \yiiunit\TestCase $this->mockWebApplication(); } - public function testAttributeValue() + public function testAttributeValue(): void { $model = new ModelMock(); $model->id = 'id'; @@ -70,7 +71,7 @@ class DetailViewTest extends \yiiunit\TestCase /** * @see https://github.com/yiisoft/yii2/issues/13243 */ - public function testUnicodeAttributeNames() + public function testUnicodeAttributeNames(): void { $model = new UnicodeAttributesModelMock(); $model->ИдентификаторТовара = 'A00001'; @@ -95,7 +96,7 @@ class DetailViewTest extends \yiiunit\TestCase ); } - public function testAttributeVisible() + public function testAttributeVisible(): void { $model = new ModelMock(); $model->id = 'id'; @@ -172,7 +173,7 @@ class DetailViewTest extends \yiiunit\TestCase $this->assertEquals(5, $model->getDisplayedIdCallCount()); } - public function testRelationAttribute() + public function testRelationAttribute(): void { $model = new ModelMock(); $model->id = 'model'; @@ -207,7 +208,7 @@ class DetailViewTest extends \yiiunit\TestCase $this->assertEquals('Related Id:(not set)', $this->detailView->renderAttribute($this->detailView->attributes[1], 1)); } - public function testArrayableModel() + public function testArrayableModel(): void { $expectedValue = [ [ @@ -235,7 +236,7 @@ class DetailViewTest extends \yiiunit\TestCase $this->assertEquals($expectedValue, $this->detailView->attributes); } - public function testObjectModel() + public function testObjectModel(): void { $expectedValue = [ [ @@ -263,7 +264,7 @@ class DetailViewTest extends \yiiunit\TestCase $this->assertEquals($expectedValue, $this->detailView->attributes); } - public function testArrayModel() + public function testArrayModel(): void { $expectedValue = [ [ @@ -292,7 +293,7 @@ class DetailViewTest extends \yiiunit\TestCase $this->assertEquals($expectedValue, $this->detailView->attributes); } - public function testOptionsTags() + public function testOptionsTags(): void { $expectedValue = 'TextI`m an array'; @@ -319,7 +320,7 @@ class DetailViewTest extends \yiiunit\TestCase /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; $model = new ModelMock(); @@ -365,7 +366,7 @@ class ModelMock extends Model return $this->_related; } - public function setRelated($related) + public function setRelated($related): void { $this->_related = $related; } diff --git a/tests/framework/widgets/FragmentCacheTest.php b/tests/framework/widgets/FragmentCacheTest.php index db099d43db..b81ee21c43 100644 --- a/tests/framework/widgets/FragmentCacheTest.php +++ b/tests/framework/widgets/FragmentCacheTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use Yii; use yii\base\View; use yii\caching\ArrayCache; @@ -16,7 +17,7 @@ use yii\caching\ArrayCache; * @group widgets * @group caching */ -class FragmentCacheTest extends \yiiunit\TestCase +class FragmentCacheTest extends TestCase { protected function setUp(): void { @@ -27,7 +28,7 @@ class FragmentCacheTest extends \yiiunit\TestCase ]); } - public function testCacheEnabled() + public function testCacheEnabled(): void { $expectedLevel = ob_get_level(); ob_start(); @@ -47,7 +48,7 @@ class FragmentCacheTest extends \yiiunit\TestCase $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); } - public function testCacheDisabled1() + public function testCacheDisabled1(): void { $expectedLevel = ob_get_level(); ob_start(); @@ -69,7 +70,7 @@ class FragmentCacheTest extends \yiiunit\TestCase $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); } - public function testCacheDisabled2() + public function testCacheDisabled2(): void { $expectedLevel = ob_get_level(); ob_start(); @@ -91,7 +92,7 @@ class FragmentCacheTest extends \yiiunit\TestCase $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); } - public function testSingleDynamicFragment() + public function testSingleDynamicFragment(): void { Yii::$app->params['counter'] = 0; @@ -122,7 +123,7 @@ class FragmentCacheTest extends \yiiunit\TestCase } } - public function testMultipleDynamicFragments() + public function testMultipleDynamicFragments(): void { Yii::$app->params['counter'] = 0; @@ -155,7 +156,7 @@ class FragmentCacheTest extends \yiiunit\TestCase } } - public function testNestedDynamicFragments() + public function testNestedDynamicFragments(): void { Yii::$app->params['counter'] = 0; @@ -195,7 +196,7 @@ class FragmentCacheTest extends \yiiunit\TestCase } } - public function testVariations() + public function testVariations(): void { $this->setOutputCallback(function ($output) { return null; diff --git a/tests/framework/widgets/LinkPagerTest.php b/tests/framework/widgets/LinkPagerTest.php index 43efb8c39c..98f010c30e 100644 --- a/tests/framework/widgets/LinkPagerTest.php +++ b/tests/framework/widgets/LinkPagerTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use yii\data\Pagination; use yii\helpers\StringHelper; use yii\widgets\LinkPager; @@ -15,7 +16,7 @@ use yii\widgets\LinkPager; /** * @group widgets */ -class LinkPagerTest extends \yiiunit\TestCase +class LinkPagerTest extends TestCase { protected function setUp(): void { @@ -44,7 +45,7 @@ class LinkPagerTest extends \yiiunit\TestCase return $pagination; } - public function testFirstLastPageLabels() + public function testFirstLastPageLabels(): void { $pagination = $this->getPagination(5); $output = LinkPager::widget([ @@ -87,7 +88,7 @@ class LinkPagerTest extends \yiiunit\TestCase $this->assertStringNotContainsString('
  9. ', $output); } - public function testDisabledPageElementOptions() + public function testDisabledPageElementOptions(): void { $output = LinkPager::widget([ 'pagination' => $this->getPagination(0), @@ -97,7 +98,7 @@ class LinkPagerTest extends \yiiunit\TestCase $this->assertStringContainsString('«', $output); } - public function testDisabledPageElementOptionsWithTagOption() + public function testDisabledPageElementOptionsWithTagOption(): void { $output = LinkPager::widget([ 'pagination' => $this->getPagination(0), @@ -107,7 +108,7 @@ class LinkPagerTest extends \yiiunit\TestCase $this->assertStringContainsString('
    «
    ', $output); } - public function testDisableCurrentPageButton() + public function testDisableCurrentPageButton(): void { $pagination = $this->getPagination(5); $output = LinkPager::widget([ @@ -128,7 +129,7 @@ class LinkPagerTest extends \yiiunit\TestCase $this->assertStringContainsString('
  10. 6
  11. ', $output); } - public function testOptionsWithTagOption() + public function testOptionsWithTagOption(): void { $output = LinkPager::widget([ 'pagination' => $this->getPagination(5), @@ -141,7 +142,7 @@ class LinkPagerTest extends \yiiunit\TestCase $this->assertTrue(StringHelper::endsWith($output, '
    ')); } - public function testLinkWrapOptions() + public function testLinkWrapOptions(): void { $output = LinkPager::widget([ 'pagination' => $this->getPagination(1), @@ -161,7 +162,7 @@ class LinkPagerTest extends \yiiunit\TestCase ); } - public function testWithTwoButtons() + public function testWithTwoButtons(): void { $output = LinkPager::widget([ 'pagination' => $this->getPagination(0), @@ -194,7 +195,7 @@ class LinkPagerTest extends \yiiunit\TestCase ); } - public function testWithOneButton() + public function testWithOneButton(): void { $output = LinkPager::widget([ 'pagination' => $this->getPagination(0), @@ -225,7 +226,7 @@ class LinkPagerTest extends \yiiunit\TestCase ); } - public function testWithNoButtons() + public function testWithNoButtons(): void { $output = LinkPager::widget([ 'pagination' => $this->getPagination(0), @@ -257,7 +258,7 @@ class LinkPagerTest extends \yiiunit\TestCase /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; $output = LinkPager::widget([ diff --git a/tests/framework/widgets/LinkSorterTest.php b/tests/framework/widgets/LinkSorterTest.php index 28da0170be..8f0718ebc8 100644 --- a/tests/framework/widgets/LinkSorterTest.php +++ b/tests/framework/widgets/LinkSorterTest.php @@ -30,7 +30,7 @@ class LinkSorterTest extends DatabaseTestCase $this->mockWebApplication(); } - public function testLabelsSimple() + public function testLabelsSimple(): void { $dataProvider = new ActiveDataProvider([ 'query' => Order::find(), @@ -58,7 +58,7 @@ class LinkSorterTest extends DatabaseTestCase )); } - public function testLabelsExplicit() + public function testLabelsExplicit(): void { $dataProvider = new ActiveDataProvider([ 'query' => Order::find(), @@ -90,7 +90,7 @@ class LinkSorterTest extends DatabaseTestCase /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; new LinkSorter( diff --git a/tests/framework/widgets/ListViewTest.php b/tests/framework/widgets/ListViewTest.php index a00caede36..fc057f0295 100644 --- a/tests/framework/widgets/ListViewTest.php +++ b/tests/framework/widgets/ListViewTest.php @@ -8,6 +8,7 @@ namespace yiiunit\framework\widgets; +use Yii; use yii\web\Request; use yii\data\ArrayDataProvider; use yii\data\DataProviderInterface; @@ -25,7 +26,7 @@ class ListViewTest extends TestCase $this->mockApplication(); } - public function testEmptyListShown() + public function testEmptyListShown(): void { ob_start(); $this->getListView([ @@ -37,7 +38,7 @@ class ListViewTest extends TestCase $this->assertEqualsWithoutLE('
    Nothing at all
    ', $out); } - public function testEmpty() + public function testEmpty(): void { ob_start(); $this->getListView([ @@ -49,7 +50,7 @@ class ListViewTest extends TestCase $this->assertEqualsWithoutLE('
    ', $out); } - public function testEmptyListNotShown() + public function testEmptyListNotShown(): void { ob_start(); $this->getListView([ @@ -94,7 +95,7 @@ HTML, ], $additionalConfig)); } - public function testSimplyListView() + public function testSimplyListView(): void { ob_start(); $this->getListView()->run(); @@ -112,7 +113,7 @@ HTML, ); } - public function testWidgetOptions() + public function testWidgetOptions(): void { ob_start(); $this->getListView(['options' => ['class' => 'test-passed'], 'separator' => ''])->run(); @@ -165,7 +166,7 @@ HTML, * @param mixed $itemView * @param string $expected */ - public function testItemViewOptions($itemView, $expected) + public function testItemViewOptions($itemView, $expected): void { ob_start(); $this->getListView(['itemView' => $itemView])->run(); @@ -211,7 +212,7 @@ HTML, * @param mixed $itemOptions * @param string $expected */ - public function testItemOptions($itemOptions, $expected) + public function testItemOptions($itemOptions, $expected): void { ob_start(); $this->getListView(['itemOptions' => $itemOptions])->run(); @@ -220,7 +221,7 @@ HTML, $this->assertEqualsWithoutLE($expected, $out); } - public function testBeforeAndAfterItem() + public function testBeforeAndAfterItem(): void { $before = function ($model, $key, $index, $widget) { $widget = get_class($widget); @@ -261,7 +262,7 @@ HTML, /** * @see https://github.com/yiisoft/yii2/pull/14596 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; $this->getListView([ @@ -273,7 +274,7 @@ HTML, $this->assertTrue($initTriggered); } - public function testNoDataProvider() + public function testNoDataProvider(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('The "dataProvider" property must be set.'); @@ -291,7 +292,7 @@ HTML, /** * @dataProvider providerForNoSorter */ - public function testRenderNoSorter($additionalConfig) + public function testRenderNoSorter($additionalConfig): void { $config = array_merge(['layout' => '{sorter}'], $additionalConfig); @@ -302,7 +303,7 @@ HTML, $this->assertEqualsWithoutLE('
    ', $out); } - public function testRenderSorterOnlyWithNoItems() + public function testRenderSorterOnlyWithNoItems(): void { // by default sorter is skipped when there are no items during run() $out = (new ListView([ @@ -313,9 +314,9 @@ HTML, $this->assertEquals('', $out); } - public function testRenderSorter() + public function testRenderSorter(): void { - \Yii::$app->set('request', new Request(['scriptUrl' => '/'])); + Yii::$app->set('request', new Request(['scriptUrl' => '/'])); ob_start(); $this->getListView([ @@ -334,7 +335,7 @@ HTML, ', $out); } - public function testRenderSummaryWhenPaginationIsFalseAndSummaryIsNull() + public function testRenderSummaryWhenPaginationIsFalseAndSummaryIsNull(): void { ob_start(); $this->getListView(['dataProvider' => $this->getDataProvider(['pagination' => false])])->run(); @@ -366,7 +367,7 @@ HTML, /** * @dataProvider providerForSummary */ - public function testRenderSummaryWhenSummaryIsCustom($summary, $result) + public function testRenderSummaryWhenSummaryIsCustom($summary, $result): void { ob_start(); $this->getListView(['summary' => $summary])->run(); diff --git a/tests/framework/widgets/MenuTest.php b/tests/framework/widgets/MenuTest.php index b59a1773b7..18a66b208e 100644 --- a/tests/framework/widgets/MenuTest.php +++ b/tests/framework/widgets/MenuTest.php @@ -8,12 +8,13 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use yii\widgets\Menu; /** * @group widgets */ -class MenuTest extends \yiiunit\TestCase +class MenuTest extends TestCase { protected function setUp(): void { @@ -28,7 +29,7 @@ class MenuTest extends \yiiunit\TestCase ]); } - public function testEncodeLabel() + public function testEncodeLabel(): void { $output = Menu::widget([ 'route' => 'test/test', @@ -82,7 +83,7 @@ HTML; /** * @see https://github.com/yiisoft/yii2/issues/8064 */ - public function testTagOption() + public function testTagOption(): void { $output = Menu::widget([ 'route' => 'test/test', @@ -139,7 +140,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testItemTemplate() + public function testItemTemplate(): void { $output = Menu::widget([ 'route' => 'test/test', @@ -171,7 +172,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testActiveItemClosure() + public function testActiveItemClosure(): void { $output = Menu::widget([ 'route' => 'test/test', @@ -208,7 +209,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testActiveItemClosureWithLogic() + public function testActiveItemClosureWithLogic(): void { $output = Menu::widget([ 'route' => 'test/logic', @@ -240,7 +241,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testActiveItemClosureWithLogicParent() + public function testActiveItemClosureWithLogicParent(): void { $output = Menu::widget([ 'route' => 'test/logic', @@ -294,7 +295,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testActiveItemClosureParentAnotherItem() + public function testActiveItemClosureParentAnotherItem(): void { /** @see https://github.com/yiisoft/yii2/issues/19060 */ $output = Menu::widget([ @@ -351,7 +352,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testItemClassAsArray() + public function testItemClassAsArray(): void { $output = Menu::widget([ 'route' => 'test/test', @@ -406,7 +407,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testItemClassAsString() + public function testItemClassAsString(): void { $output = Menu::widget([ 'route' => 'test/test', @@ -452,7 +453,7 @@ HTML; $this->assertEqualsWithoutLE($expected, $output); } - public function testIsItemActive() + public function testIsItemActive(): void { $output = Menu::widget([ 'route' => 'test/item2', diff --git a/tests/framework/widgets/PjaxTest.php b/tests/framework/widgets/PjaxTest.php index adab82eee9..a1e303c7af 100644 --- a/tests/framework/widgets/PjaxTest.php +++ b/tests/framework/widgets/PjaxTest.php @@ -15,7 +15,7 @@ use yiiunit\TestCase; class PjaxTest extends TestCase { - public function testGeneratedIdByPjaxWidget() + public function testGeneratedIdByPjaxWidget(): void { ListView::$counter = 0; Pjax::$counter = 0; @@ -43,7 +43,7 @@ class PjaxTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; ob_start(); diff --git a/tests/framework/widgets/SpacelessTest.php b/tests/framework/widgets/SpacelessTest.php index f4c40f0ad9..0483db5265 100644 --- a/tests/framework/widgets/SpacelessTest.php +++ b/tests/framework/widgets/SpacelessTest.php @@ -8,14 +8,15 @@ namespace yiiunit\framework\widgets; +use yiiunit\TestCase; use yii\widgets\Spaceless; /** * @group widgets */ -class SpacelessTest extends \yiiunit\TestCase +class SpacelessTest extends TestCase { - public function testWidget() + public function testWidget(): void { ob_start(); ob_implicit_flush(false); @@ -48,7 +49,7 @@ class SpacelessTest extends \yiiunit\TestCase /** * @see https://github.com/yiisoft/yii2/issues/15536 */ - public function testShouldTriggerInitEvent() + public function testShouldTriggerInitEvent(): void { $initTriggered = false; $spaceless = Spaceless::begin(