From 33cb05a002af5f8459ac9796d5d2a14adcecf911 Mon Sep 17 00:00:00 2001 From: Clemens Schwaighofer Date: Fri, 1 Sep 2023 08:37:15 +0900 Subject: [PATCH] Update to Exceptions: add codes, update phpunit tests DB Class throws Exception if on init it fails to connect to the DB, will not throw Exception if failed connection during execution but will do the normal retry and soft failure run DB\ArrayIO will throw Exception on missing table array and table name All Exceptions have a code set --- 4dev/tests/Check/CoreLibsCheckColorsTest.php | 5 ++ .../Combined/CoreLibsCombinedDateTimeTest.php | 82 ++++++++++++++++--- .../Create/CoreLibsCreateSessionTest.php | 14 +++- 4dev/tests/DB/CoreLibsDBIOTest.php | 11 +++ www/lib/CoreLibs/ACL/Login.php | 1 - www/lib/CoreLibs/Combined/DateTime.php | 12 +-- www/lib/CoreLibs/Convert/Colors.php | 22 ++--- www/lib/CoreLibs/Create/Session.php | 10 +-- www/lib/CoreLibs/DB/Extended/ArrayIO.php | 2 + www/lib/CoreLibs/DB/IO.php | 6 +- 10 files changed, 128 insertions(+), 37 deletions(-) diff --git a/4dev/tests/Check/CoreLibsCheckColorsTest.php b/4dev/tests/Check/CoreLibsCheckColorsTest.php index 7f0bc1c2..3eeb59c9 100644 --- a/4dev/tests/Check/CoreLibsCheckColorsTest.php +++ b/4dev/tests/Check/CoreLibsCheckColorsTest.php @@ -13,6 +13,11 @@ use PHPUnit\Framework\TestCase; */ final class CoreLibsCheckColorsTest extends TestCase { + /** + * Undocumented function + * + * @return array + */ public function validateColorProvider(): array { /* diff --git a/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php b/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php index e2174a41..7bd68d6a 100644 --- a/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php +++ b/4dev/tests/Combined/CoreLibsCombinedDateTimeTest.php @@ -310,52 +310,72 @@ final class CoreLibsCombinedDateTimeTest extends TestCase '2021-12-12', -1, null, + null, ], 'dates equal' => [ '2020-12-12', '2020-12-12', 0, null, + null, ], 'second date smaller' => [ '2021-12-12', '2020-12-12', 1, null, + null, ], 'dates equal with different time' => [ '2020-12-12 12:12:12', '2020-12-12 13:13:13', 0, null, + null, ], 'invalid dates --' => [ '--', '--', false, 'UnexpectedValueException', + 1, ], 'empty dates' => [ '', '', false, - 'UnexpectedValueException' + 'UnexpectedValueException', + 1 ], 'invalid dates' => [ 'not a date', 'not a date either', false, - 'UnexpectedValueException' + 'UnexpectedValueException', + 2 + ], + 'invalid end date' => [ + '1990-01-01', + 'not a date either', + false, + 'UnexpectedValueException', + 3 ], 'out of bound dates' => [ '1900-1-1', '9999-12-31', -1, null, + null, ] ]; } + /** + * Undocumented function + * + * @return array + */ public function dateTimeCompareProvider(): array { return [ @@ -364,60 +384,84 @@ final class CoreLibsCombinedDateTimeTest extends TestCase '2021-12-12', -1, null, + null, ], 'dates equal no timestamp' => [ '2020-12-12', '2020-12-12', 0, null, + null, ], 'second date smaller no timestamp' => [ '2021-12-12', '2020-12-12', 1, null, + null, ], 'date equal first time smaller' => [ '2020-12-12 12:12:12', '2020-12-12 13:13:13', -1, null, + null, ], 'date equal time equal' => [ '2020-12-12 12:12:12', '2020-12-12 12:12:12', 0, null, + null, ], 'date equal second time smaller' => [ '2020-12-12 13:13:13', '2020-12-12 12:12:12', 1, null, + null, ], 'valid date invalid time' => [ '2020-12-12 13:99:13', '2020-12-12 12:12:99', false, - 'UnexpectedValueException' + 'UnexpectedValueException', + 2 + ], + 'valid date invalid end time' => [ + '2020-12-12 13:12:13', + '2020-12-12 12:12:99', + false, + 'UnexpectedValueException', + 3 ], 'invalid datetimes --' => [ '--', '--', false, - 'UnexpectedValueException' + 'UnexpectedValueException', + 1 ], 'empty datetimess' => [ '', '', false, - 'UnexpectedValueException' + 'UnexpectedValueException', + 1 ], - 'invalid datetimes' => [ + 'invalid date times' => [ 'not a date', 'not a date either', false, - 'UnexpectedValueException' + 'UnexpectedValueException', + 2 + ], + 'invalid end date time' => [ + '1990-01-01 12:12:12', + 'not a date either', + false, + 'UnexpectedValueException', + 3 ], ]; } @@ -632,12 +676,20 @@ final class CoreLibsCombinedDateTimeTest extends TestCase * @param string $input_a * @param string $input_b * @param int|bool $expected + * @param string|null $exception + * @param int|null $exception_code * @return void */ - public function testCompareDate(string $input_a, string $input_b, int|bool $expected, ?string $exception): void - { + public function testCompareDate( + string $input_a, + string $input_b, + int|bool $expected, + ?string $exception, + ?int $exception_code + ): void { if ($expected === false) { $this->expectException($exception); + $this->expectExceptionCode($exception_code); } $this->assertEquals( $expected, @@ -655,12 +707,20 @@ final class CoreLibsCombinedDateTimeTest extends TestCase * @param string $input_a * @param string $input_b * @param int|bool $expected + * @param string|null $exception + * @param int|null $exception_code * @return void */ - public function testCompareDateTime(string $input_a, string $input_b, int|bool $expected, ?string $exception): void - { + public function testCompareDateTime( + string $input_a, + string $input_b, + int|bool $expected, + ?string $exception, + ?int $exception_code + ): void { if ($expected === false) { $this->expectException($exception); + $this->expectExceptionCode($exception_code); } $this->assertEquals( $expected, diff --git a/4dev/tests/Create/CoreLibsCreateSessionTest.php b/4dev/tests/Create/CoreLibsCreateSessionTest.php index 90c857ae..f9c89109 100644 --- a/4dev/tests/Create/CoreLibsCreateSessionTest.php +++ b/4dev/tests/Create/CoreLibsCreateSessionTest.php @@ -32,7 +32,8 @@ final class CoreLibsCreateSessionTest extends TestCase // getSessionId: string or false // 3: exepcted name (session)] // 4: Exception thrown on error - // 5: expected error string + // 5: exception code, null for none + // 6: expected error string return [ 'session parameter' => [ 'sessionNameParameter', @@ -46,6 +47,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], 'sessionNameParameter', null, + null, '', ], 'session globals' => [ @@ -60,6 +62,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], 'sessionNameGlobals', null, + null, '', ], 'session name default' => [ @@ -74,6 +77,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], '', null, + null, '', ], // error checks @@ -90,6 +94,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], '', 'RuntimeException', + 1, '[SESSION] No sessions in php cli' ], // 2: session disabled @@ -105,6 +110,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], '', 'RuntimeException', + 2, '[SESSION] Sessions are disabled' ], // 3: invalid session name: string @@ -120,6 +126,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], '', 'UnexpectedValueException', + 3, '[SESSION] Invalid session name: 1invalid$session#;' ], // 3: invalid session name: only numbers @@ -135,6 +142,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], '', 'UnexpectedValueException', + 3, '[SESSION] Invalid session name: 123' ], // 3: invalid session name: invalid name short @@ -152,6 +160,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], '', 'RuntimeException', + 4, '[SESSION] Failed to activate session' ], // 5: get session id return false @@ -167,6 +176,7 @@ final class CoreLibsCreateSessionTest extends TestCase ], '', 'UnexpectedValueException', + 5, '[SESSION] getSessionId did not return a session id' ], ]; @@ -193,6 +203,7 @@ final class CoreLibsCreateSessionTest extends TestCase array $mock_data, string $expected, ?string $exception, + ?int $exception_code, string $expected_error ): void { // override expected @@ -238,6 +249,7 @@ final class CoreLibsCreateSessionTest extends TestCase if ($exception !== null) { $this->expectException($exception); + $this->expectExceptionCode($exception_code); } unset($GLOBALS['SET_SESSION_NAME']); diff --git a/4dev/tests/DB/CoreLibsDBIOTest.php b/4dev/tests/DB/CoreLibsDBIOTest.php index bb24f270..46ec6709 100644 --- a/4dev/tests/DB/CoreLibsDBIOTest.php +++ b/4dev/tests/DB/CoreLibsDBIOTest.php @@ -445,12 +445,14 @@ final class CoreLibsDBIOTest extends TestCase { // 0: connection array // 1: status after connection + // 2: exception name // 2: info string // 3: ??? return [ 'invalid connection' => [ self::$db_config['invalid'], false, + 'RuntimeException', "-DB-info-> Connected to db '' with schema 'public' as user " . "'' at host '' on port '5432' with ssl mode 'allow' **** " . "-DB-info-> DB IO Class debug output: Yes **** ", @@ -459,6 +461,7 @@ final class CoreLibsDBIOTest extends TestCase 'valid connection' => [ self::$db_config['valid'], true, + '', "-DB-info-> Connected to db 'corelibs_db_io_test' with " . "schema 'public' as user 'corelibs_db_io_test' at host " . "'localhost' on port '5432' with ssl mode 'allow' **** " @@ -475,13 +478,21 @@ final class CoreLibsDBIOTest extends TestCase * @dataProvider connectionProvider * @testdox Connection will be $expected [$_dataName] * + * @param array $connection + * @param bool $expected_status + * @param string $exception + * @param string $expected_string * @return void */ public function testConnection( array $connection, bool $expected_status, + string $exception, string $expected_string ): void { + if ($expected_status === false) { + $this->expectException($exception); + } $db = new \CoreLibs\DB\IO( $connection, self::$log diff --git a/www/lib/CoreLibs/ACL/Login.php b/www/lib/CoreLibs/ACL/Login.php index 1b3b8fee..2a38c219 100644 --- a/www/lib/CoreLibs/ACL/Login.php +++ b/www/lib/CoreLibs/ACL/Login.php @@ -403,7 +403,6 @@ class Login $this->log->info($message, ['code' => $code]); } else { $this->log->critical($message, ['code' => $code]); - // throw new \Exception($message, $code); } exit($code); } diff --git a/www/lib/CoreLibs/Combined/DateTime.php b/www/lib/CoreLibs/Combined/DateTime.php index 286b8382..a807a39d 100644 --- a/www/lib/CoreLibs/Combined/DateTime.php +++ b/www/lib/CoreLibs/Combined/DateTime.php @@ -328,14 +328,14 @@ class DateTime { // pre check for empty or wrong if ($start_date == '--' || $end_date == '--' || empty($start_date) || empty($end_date)) { - throw new \UnexpectedValueException('Start or End date not set or are just "--"'); + throw new \UnexpectedValueException('Start or End date not set or are just "--"', 1); } // if invalid, quit if (($start_timestamp = strtotime($start_date)) === false) { - throw new \UnexpectedValueException("Error parsing start date through strtotime()"); + throw new \UnexpectedValueException("Error parsing start date through strtotime()", 2); } if (($end_timestamp = strtotime($end_date)) === false) { - throw new \UnexpectedValueException("Error parsing end date through strtotime()"); + throw new \UnexpectedValueException("Error parsing end date through strtotime()", 3); } $comp = 0; // convert anything to Y-m-d and then to timestamp @@ -371,14 +371,14 @@ class DateTime { // pre check for empty or wrong if ($start_datetime == '--' || $end_datetime == '--' || empty($start_datetime) || empty($end_datetime)) { - throw new \UnexpectedValueException('Start or end timestamp not set or are just "--"'); + throw new \UnexpectedValueException('Start or end timestamp not set or are just "--"', 1); } // quit if invalid timestamp if (($start_timestamp = strtotime($start_datetime)) === false) { - throw new \UnexpectedValueException("Error parsing start timestamp through strtotime()"); + throw new \UnexpectedValueException("Error parsing start timestamp through strtotime()", 2); } if (($end_timestamp = strtotime($end_datetime)) === false) { - throw new \UnexpectedValueException("Error parsing end timestamp through strtotime()"); + throw new \UnexpectedValueException("Error parsing end timestamp through strtotime()", 3); } $comp = 0; // compare, or return false diff --git a/www/lib/CoreLibs/Convert/Colors.php b/www/lib/CoreLibs/Convert/Colors.php index 851a846d..f9f56171 100644 --- a/www/lib/CoreLibs/Convert/Colors.php +++ b/www/lib/CoreLibs/Convert/Colors.php @@ -45,7 +45,7 @@ class Colors // if not valid, abort if ($$color < 0 || $$color > 255) { throw new \LengthException('Argument value ' . $$color . ' for color ' . $color - . ' is not in the range of 0 to 255'); + . ' is not in the range of 0 to 255', 1); } // pad left with 0 $hex_color .= str_pad(dechex($$color), 2, '0', STR_PAD_LEFT); @@ -71,7 +71,7 @@ class Colors ): string|array { $hex_string = preg_replace("/[^0-9A-Fa-f]/", '', $hex_string); // Gets a proper hex string if (!is_string($hex_string)) { - throw new \InvalidArgumentException('hex_string argument cannot be empty'); + throw new \InvalidArgumentException('hex_string argument cannot be empty', 1); } $rgbArray = []; if (strlen($hex_string) == 6) { @@ -88,7 +88,7 @@ class Colors $rgbArray['b'] = hexdec(str_repeat(substr($hex_string, 2, 1), 2)); } else { // Invalid hex color code - throw new \UnexpectedValueException('Invalid hex_string: ' . $hex_string); + throw new \UnexpectedValueException('Invalid hex_string: ' . $hex_string, 2); } // returns the rgb string or the associative array return $return_as_string ? implode($seperator, $rgbArray) : $rgbArray; @@ -112,7 +112,7 @@ class Colors foreach (['red', 'green', 'blue'] as $color) { if ($$color < 0 || $$color > 255) { throw new \LengthException('Argument value ' . $$color . ' for color ' . $color - . ' is not in the range of 0 to 255'); + . ' is not in the range of 0 to 255', 1); } $$color = $$color / 255; } @@ -162,13 +162,13 @@ class Colors $H = 0; } if ($H < 0 || $H > 359) { - throw new \LengthException('Argument value ' . $H . ' for hue is not in the range of 0 to 359'); + throw new \LengthException('Argument value ' . $H . ' for hue is not in the range of 0 to 359', 1); } if ($S < 0 || $S > 100) { - throw new \LengthException('Argument value ' . $S . ' for saturation is not in the range of 0 to 100'); + throw new \LengthException('Argument value ' . $S . ' for saturation is not in the range of 0 to 100', 2); } if ($V < 0 || $V > 100) { - throw new \LengthException('Argument value ' . $V . ' for brightness is not in the range of 0 to 100'); + throw new \LengthException('Argument value ' . $V . ' for brightness is not in the range of 0 to 100', 3); } // convert to internal 0-1 format $S /= 100; @@ -246,7 +246,7 @@ class Colors foreach (['red', 'green', 'blue'] as $color) { if ($$color < 0 || $$color > 255) { throw new \LengthException('Argument value ' . $$color . ' for color ' . $color - . ' is not in the range of 0 to 255'); + . ' is not in the range of 0 to 255', 1); } $$color = $$color / 255; } @@ -301,13 +301,13 @@ class Colors $hue = 0; } if ($hue < 0 || $hue > 359) { - throw new \LengthException('Argument value ' . $hue . ' for hue is not in the range of 0 to 359'); + throw new \LengthException('Argument value ' . $hue . ' for hue is not in the range of 0 to 359', 1); } if ($sat < 0 || $sat > 100) { - throw new \LengthException('Argument value ' . $sat . ' for saturation is not in the range of 0 to 100'); + throw new \LengthException('Argument value ' . $sat . ' for saturation is not in the range of 0 to 100', 2); } if ($lum < 0 || $lum > 100) { - throw new \LengthException('Argument value ' . $lum . ' for luminance is not in the range of 0 to 100'); + throw new \LengthException('Argument value ' . $lum . ' for luminance is not in the range of 0 to 100', 3); } // calc to internal convert value for hue $hue = (1 / 360) * $hue; diff --git a/www/lib/CoreLibs/Create/Session.php b/www/lib/CoreLibs/Create/Session.php index a5ad2309..ca3607e6 100644 --- a/www/lib/CoreLibs/Create/Session.php +++ b/www/lib/CoreLibs/Create/Session.php @@ -106,11 +106,11 @@ class Session { // we can't start sessions on command line if ($this->checkCliStatus()) { - throw new \RuntimeException('[SESSION] No sessions in php cli'); + throw new \RuntimeException('[SESSION] No sessions in php cli', 1); } // if session are OFF if ($this->getSessionStatus() === PHP_SESSION_DISABLED) { - throw new \RuntimeException('[SESSION] Sessions are disabled'); + throw new \RuntimeException('[SESSION] Sessions are disabled', 2); } // session_status // initial the session if there is no session running already @@ -123,7 +123,7 @@ class Session if (!empty($session_name)) { // invalid session name, abort if (!$this->checkValidSessionName($session_name)) { - throw new \UnexpectedValueException('[SESSION] Invalid session name: ' . $session_name); + throw new \UnexpectedValueException('[SESSION] Invalid session name: ' . $session_name, 3); } $this->setSessionName($session_name); } @@ -132,10 +132,10 @@ class Session } // if we still have no active session if (!$this->checkActiveSession()) { - throw new \RuntimeException('[SESSION] Failed to activate session'); + throw new \RuntimeException('[SESSION] Failed to activate session', 4); } if (false === ($session_id = $this->getSessionId())) { - throw new \UnexpectedValueException('[SESSION] getSessionId did not return a session id'); + throw new \UnexpectedValueException('[SESSION] getSessionId did not return a session id', 5); } return $session_id; } diff --git a/www/lib/CoreLibs/DB/Extended/ArrayIO.php b/www/lib/CoreLibs/DB/Extended/ArrayIO.php index 9b6b734c..7c2ed514 100644 --- a/www/lib/CoreLibs/DB/Extended/ArrayIO.php +++ b/www/lib/CoreLibs/DB/Extended/ArrayIO.php @@ -61,6 +61,7 @@ class ArrayIO extends \CoreLibs\DB\IO * @param \CoreLibs\Logging\Logging $log Logging class * @param int $base_acl_level Set base acl level, if needed * @param int $acl_admin Flag if this is an admin ACL access level + * @throws \RuntimeException Missing table array or table name entry */ public function __construct( array $db_config, @@ -83,6 +84,7 @@ class ArrayIO extends \CoreLibs\DB\IO // error abort if no table array or no table name if (empty($table_array) || empty($table_name)) { $this->__dbError(1999, false, 'MAJOR ERROR: Core settings missing'); + throw new \RuntimeException('MAJOR ERROR: Core settings missing', 1999); } // set primary key for given table_array diff --git a/www/lib/CoreLibs/DB/IO.php b/www/lib/CoreLibs/DB/IO.php index 59cad655..7988470e 100644 --- a/www/lib/CoreLibs/DB/IO.php +++ b/www/lib/CoreLibs/DB/IO.php @@ -414,6 +414,7 @@ class IO * phpcs:ignore * @param array{db_name:string,db_user:string,db_pass:string,db_host:string,db_port:int,db_schema:string,db_encoding:string,db_type:string,db_ssl:string,db_convert_type?:string[]} $db_config DB configuration array * @param \CoreLibs\Logging\Logging $log Logging class + * @throws \RuntimeException If no DB connection can be established on launch */ public function __construct( array $db_config, @@ -492,6 +493,7 @@ class IO if (!$this->__connectToDB()) { $this->__dbError(16); $this->db_connection_closed = true; + throw new \RuntimeException('INIT: No DB Handler found / connect or reconnect failed', 16); } } @@ -974,9 +976,9 @@ class IO /** * write an error * - * @param integer $error_id Any Error ID, used in debug message string + * @param integer $error_id Any Error ID, used in debug message string * @param \PgSql\Result|false $cursor Optional cursor, passed on to preprocessor - * @param string $msg optional message added to debug + * @param string $msg optional message added to debug * @return void */ protected function __dbError(