diff --git a/classes/local/au_helpers.php b/classes/local/au_helpers.php index 5f2dec0..82c1545 100644 --- a/classes/local/au_helpers.php +++ b/classes/local/au_helpers.php @@ -24,10 +24,10 @@ namespace mod_cmi5launch\local; use mod_cmi5launch\local\au; -use mod_cmi5launch\local\errorOver; +use mod_cmi5launch\local\errorover; -// include the errorOver funcs -require_once ($CFG->dirroot . '/mod/cmi5launch/classes/local/errorOver.php'); +// Include the errorover (error override) funcs. +require_once ($CFG->dirroot . '/mod/cmi5launch/classes/local/errorover.php'); defined('MOODLE_INTERNAL') || die(); @@ -51,48 +51,32 @@ public function get_cmi5launch_retrieve_aus_from_db() { * @return array */ public function cmi5launch_retrieve_aus($returnedinfo) { - // The results come back as nested array under more then just AUs. - // We only want the info pertaining to the AU. + $resultchunked = ""; + // Use our own more specific error handler, to give better info tto user. set_error_handler('mod_cmi5launch\local\array_chunk_warning', E_WARNING); - //Lets add a try catch, and see if it catches when fed wrong array info + // The results come back as nested array under more then just AUs. + // We only want the info pertaining to the AU. However, if the wrong info is passed array_chunk will through an exception. try { $resultchunked = array_chunk($returnedinfo["metadata"]["aus"], 1, ); } - // If this doesnt work catch the exception or erro and throw our own! catch (\Exception $e) { - - // It's nt bein thrown!! OMG it's not being throuwn!!!! - // lololololololol - // But it is bein thorw but the array chunk over ride, this is the problem - // So maybe catch the error? The warning huh - // We need to throw HERE for it to be cauht - // Whats happening is the ARRAY chunk is throwing trhe null exception - // not the code under test - // So, what does this mean? Do we want to just test output????? - // I think so, because the exception handling is anothe system under test - // What is happening here is the error is turned into exception, the exception is autothrown or thrown to be a null exception, - // If the null exception is thrown THEN the catch operates, but because catch is operiting the tests are picking up IT, not the thing that causedd it!!! - - //They problme is the try/catch syntax I think - - - // What is php unit is throwing ANOTHER exceptuion and thats what is - // being cauhy and thats why me invented one is missed - // The message returned is what I decded in erroverride, combined with below I can make it apecif for certain areas + echo "Cannot retrieve AUs. Error found when trying to parse them from course creation: " . "Please check the connection to player or course format and try again. \n" . $e->getMessage() . "\n"; //exit; - } - restore_error_handler(); - return $resultchunked; - + } + // Restore the error handler. + restore_error_handler(); + + return $resultchunked; } + /** * So it should be fed an array of statements that then assigns the values to * several aus, and then returns them as au objects. @@ -101,16 +85,15 @@ public function cmi5launch_retrieve_aus($returnedinfo) { */ public function cmi5launch_create_aus($austatements) { - // Needs to return our new AU objects. $newaus = array(); - // /SHould this be where the build in is? Or where this func is called? // We should not be able to get here but what if null is pulled from record and passed in? - // SO in case it is given null + // So in case it is given null. if ($austatements == null) { + throw new nullException('Cannot retrieve AU information. AU statements from DB are: ' . $austatements, 0); - exit; + } else { foreach ($austatements as $int => $info) { @@ -138,19 +121,24 @@ public function cmi5launch_save_aus($auobjectarray) { // Add userid to the record. global $DB, $USER, $cmi5launch; $table = "cmi5launch_aus"; - $newid = ""; - $newrecord = ""; + // An array to hold the created ids. $auids = array(); - // Array of all items in new record, this will be useful for - // troubleshooting. + + // Variables for error over and exception handling. + // Array of all items in new record, this will be useful for troubleshooting. $newrecorditems = array('id', 'attempt', 'auid', 'launchmethod', 'lmsid', 'url', 'type', 'title', 'moveon', 'auindex', 'parents', 'objectives', 'description', 'activitytype', 'masteryscore', 'completed', 'passed', 'inprogress', 'noattempt', 'satisfied', 'moodlecourseid'); + $currentrecord = 1; + $newid = ""; + $newrecord = ""; + // Set error and exception handler to catch and override the default PHP error messages, to make messages more user friendly. set_error_handler('mod_cmi5launch\local\sifting_data_warning', E_WARNING); set_exception_handler('mod_cmi5launch\local\exception_au'); - $currentrecord = 1; + //Check it's not null. if ($auobjectarray == null) { + throw new nullException('Cannot save AU information. AU object array is: null' , 0); } else { @@ -158,14 +146,12 @@ public function cmi5launch_save_aus($auobjectarray) { // Because of so many nested variables this needs to be done manually. foreach ($auobjectarray as $auobject) { - // I suppose another thing that could o wrong is the retrieval or subsequent encoding of these items. - // Sooo maybe wrap hte whole thing in a try/cath? -// Can we make an exception that points to whos is missing? Like title vs id? - // Now here we need an exception catchy thing, because theres no way to know WHAT wmight be good + // A try statement to catch any errors that may be thrown. try { // Make a newrecord to save. $newrecord = new \stdClass(); + // Assign the values to the new record. $newrecord->userid = $USER->id; $newrecord->attempt = $auobject->attempt; $newrecord->auid = $auobject->id; @@ -188,65 +174,51 @@ public function cmi5launch_save_aus($auobjectarray) { $newrecord->inprogress = $auobject->inprogress; $newrecord->noattempt = $auobject->noattempt; $newrecord->satisfied = $auobject->satisfied; - // And HERE we can add the moodlecourseid. $newrecord->moodlecourseid = $cmi5launch->id; - // echo" What are the newrecords? " . var_dump($auobject->moveOn) . "\n"; - - // What could go wrong here? The record is not saved? The record is not saved correctly? // Save the record and get the new id. $newid = $DB->insert_record($table, $newrecord, true); + // Save new id to list to pass back. $auids[] = $newid; + + // This is for troubleshooting, so we know where the error is. $currentrecord++; - // echo" What are the newrecords? " . print_r($newrecord) . "\n"; - - // Thats right, the error handler is throwing the exception, not the code under test, so catch ANY error - // A type error cn also be thrown here, throwable catches it, so we either need to set an exception handler as well - // or catch throwable - + // The set exception handler catches exceptionas that SLIP by, // so maybe DONT make it throwable and catch type errror } catch (\Throwable $e) { - // Maybe we can construct the new errors here. This would allow the error personalization? And keep main code clean - // maybe the catch is just what is suppossed to happen when the - //error is thrown, any additional stuff - //the current new record is - // echo "New idis "; - - // Its plus one because it would be the recor that couldnt save, so the last id would be the the previous one that went throuh + echo "Cannot save to DB. Stopped at record with ID number " . ($currentrecord) . "."; - // ok so what is e? - // echo"Error stirn --- " . $e->getMessage(); - // Typecast tp array to grab the list item + // This is the tricky part, we need to find out which field is missing. But because the error is thrown ON the field, we need to do some + // manuevering to find out which field is missing. + // Typecast to array to grab the list item. $items = (array) $newrecord; - // This will almost work but it is the NEXT one after, so maybe I should make array and then grab the one after it -// Get the last ley of array - $lastkey = array_key_last($items); - // Heres thhe tricky part, the lastkey here is somewhere in the array we earlier made and the NEXT one would be the one that thre th error - // So now we can grab the key after the last one + // Get the last ley of array + $lastkey = array_key_last($items); + + // Heres thhe tricky part, the lastkey here is somewhere in the array we earlier made and the NEXT one would be the one that threw the error. + // So now we can grab the key after the last one. $key = array_search($lastkey, $newrecorditems) + 1; - // Ok, NOW the missin element is key in newrecorditems + // Ok, NOW the missin element is key in newrecorditems. $missing = $newrecorditems[$key]; - // It worked! Now in the test we can make say three mock statements, each one with a bad field, and then make sure the - // error messae matches the bad output!!! Woot! - // yup I'm a dummy.... + // Now use the found missing value to give feedback to user. echo " One of the fields is incorrect. Check data for field '$missing'. " . $e->getMessage() . "\n"; - // exit; - } } + // Restore default hadlers. restore_exception_handler(); restore_error_handler(); + return $auids; } - } + } /** @@ -261,14 +233,12 @@ public function cmi5launch_retrieve_aus_from_db($auid) { $check = $DB->record_exists( 'cmi5launch_aus', ['id' => $auid], '*', IGNORE_MISSING); - // If check is negative, the record does not exist. It should so throw error. + // If check is negative, the record does not exist. It should also throw error. // Moodle will throw the error, but we want to pass this message back ot user. if (!$check) { throw new nullException("Error attempting to get AU data from DB. Check AU id. AU id is: " . $auid ."
", 0); - // echo "Error attempting to get AU data from DB. Check AU id. AU id is: " . $auid ."
"; - // return false; } else { $auitem = $DB->get_record('cmi5launch_aus', array('id' => $auid)); diff --git a/classes/local/errorOver.php b/classes/local/errorover.php similarity index 100% rename from classes/local/errorOver.php rename to classes/local/errorover.php diff --git a/cmi5PHP/tests/ausHelpersTest.php b/cmi5PHP/tests/ausHelpersTest.php index 7691feb..9ed7c3e 100644 --- a/cmi5PHP/tests/ausHelpersTest.php +++ b/cmi5PHP/tests/ausHelpersTest.php @@ -17,44 +17,14 @@ */ class ausHelpersTest extends TestCase { - private $auProperties, $emptyStatement, $mockStatementValues, $mockStatement2, $mockStatementExcept, $mockStatementExcept2, $returnedAUids; + private $mockstatementvalues, $mockStatement2, $mockStatementExcept, $mockStatementExcept2, $returnedAUids; public $auidForTest; protected function setUp(): void { - // All the properties in an AU object. - $this->auProperties = array( - 'id', - 'attempt', - 'url', - 'type', - 'lmsid', - 'grade', - 'scores', - 'title', - 'moveon', - 'auindex', - 'parents', - 'objectives', - 'description', - 'activitytype', - 'launchmethod', - 'masteryscore', - 'satisfied', - - 'sessionid', - 'sessions', - 'progress', - 'noattempt', - 'completed', - 'passed', - 'inprogress', - ); - - $this->emptyStatement = array(); - // Based on created AU in program, but with some values removed. + // Based on created AU in program. $this->mockStatement2 = array( "id" => "https://exampleau", "attempt" => NULL, @@ -66,20 +36,14 @@ protected function setUp(): void "title" => array( 0 => array( "lang" => "en-US", "text" => "Example AU") - ), - - "auIndex" => NULL, + ), "parents" => array(), "objectives" => NULL, "description" => array( 0 => array( "lang" => "en-US", "text" => "Example AU lesson description") ), - 'activitytype' => NULL, - 'launchmethod' => NULL, - 'masteryscore' => NULL, 'satisfied' => NULL, - 'sessions' => NULL, 'progress' => NULL, 'noattempt' => NULL, @@ -94,28 +58,23 @@ protected function setUp(): void 'masteryScore' => NULL ); - // Based on created AU in program, but with some values removed. + // Based on created AU in program, but with some values changed. // For instance title is an empty array $this->mockStatementExcept = array( "id" => "https://exampleau", "attempt" => NULL, "url" => "example.html?pages=1&complete=launch", "type" => "au example", - "lmsid" => NULL, "grade" => NULL, "scores" => NULL, "title" => array() , - "auIndex" => NULL, "parents" => array(), "objectives" => NULL, "description" => array( 0 => array( "lang" => "en-US", "text" => "Example AU lesson description") ), - 'activitytype' => NULL, - 'launchmethod' => NULL, - 'masteryscore' => NULL, 'satisfied' => NULL, 'sessions' => NULL, 'progress' => NULL, @@ -125,12 +84,11 @@ protected function setUp(): void 'inprogress' => NULL, 'launchMethod' => "AnyWindow", 'lmsId' => "https://exampleau/ranomnum/au0", - // 'moveOn' => "CompletedOrPassed", 'auIndex' => 0, 'activityType' => NULL, 'masteryScore' => NULL ); - // Based on created AU in program, but with some values removed. + // Based on created AU in program, but with some values changed. Here title is a string. $this->mockStatementExcept2 = array( "id" => "https://exampleau", "attempt" => NULL, @@ -139,10 +97,7 @@ protected function setUp(): void "lmsid" => NULL, "grade" => NULL, "scores" => NULL, - "title" => array( "title ") - , - // "moveOn"=> NULL, - "auIndex" => NULL, + "title" => array( "title "), "parents" => array(), "objectives" => NULL, "description" => array( 0 => array( @@ -153,8 +108,6 @@ protected function setUp(): void 'launchmethod' => NULL, 'masteryscore' => NULL, 'satisfied' => NULL, - - 'sessions' => NULL, 'progress' => NULL, 'noattempt' => NULL, @@ -169,7 +122,7 @@ protected function setUp(): void 'masteryScore' => NULL ); // Perhaps a good test would be to test the constructor with a statement that has all the properties set. - $this->mockStatementValues = array( + $this->mockstatementvalues = array( 'id' => 'id', 'attempt' => 'attempt', 'url' => 'url', @@ -188,7 +141,6 @@ protected function setUp(): void 'masteryscore' => 'masteryscore', 'satisfied' => 'satisfied', 'launchurl' => 'launchurl', - 'sessions' => 'sessions', 'progress' => 'progress', 'noattempt' => 'noattempt', @@ -196,7 +148,6 @@ protected function setUp(): void 'passed' => 'passed', 'inprogress' => 'inprogress', ); - } protected function tearDown(): void @@ -205,14 +156,11 @@ protected function tearDown(): void } - // Retrieve Aus parses and returns AUs from large statements from the CMI5 player - // So to test, maybe make a statement and ensure the test value is returned? - // Arbitrarily pick a word and put in right place? See if it is returned? + // Retrieve Aus parses and returns AUs from large statements from the CMI5 player. + // So to test, we will make a statement and ensure the test value is returned. public function testcmi5launch_retrieve_aus() { - //It's not just returning it, it's splitting it into chuncks~! - - //Fake values to return + // Fake values to return. $mockStatement = array( "createdAt" => "2023-06-26T18:36:15.000Z", "id"=> 000, @@ -265,9 +213,10 @@ public function testcmi5launch_retrieve_aus() ) ); - //This is the value that should be returned, basically, an array holding all the aus separately - $shouldBeReturned = array ( - //First au, nestled in array + // This is the value that should be returned, basically, an array holding all the aus separately. + $shouldbereturned = array ( + + //First au, nestled in array. 0 => array ( 0 => array ( "activityType" => null, @@ -291,7 +240,7 @@ public function testcmi5launch_retrieve_aus() "url" => "index.html?pages=1&complete=launch", ) ), - //second au nestled in array + // Second au nestled in array. 1 => array ( 0 => array ( "activityType" => null, @@ -315,119 +264,98 @@ public function testcmi5launch_retrieve_aus() "url"=> "index.html?pages=2&complete=launch" ), ) - ); $helper = new au_helpers(); - //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" + + // So now with this fake 'statement', lets ensure it pulls the correct value which is "correct retrieval". $retrieved = $helper->cmi5launch_retrieve_aus($mockStatement); - // It should retrieve the mock aus - $this->assertEquals($shouldBeReturned, $retrieved, "Expected retrieved statement to be equal to mock statement"); - //This is being flaged as risky? - //Is there a different way to test this? - //Maybe we 'expect' two properties since 2 aus were passed in? - //I mean we aren't testing 'chunked?' so....? + $this->assertEquals($shouldbereturned, $retrieved, "Expected retrieved statement to be equal to mock statement"); - //It DOES return as array + // It returns as array. $this->assertIsArray($retrieved, "Expected retrieved statement to be an array"); - //And it returns two in array? Since we passed in two? + // And it returns two in array? $this->assertCount(2, $retrieved, "Expected retrieved statement to have two aus"); - //TODO MB - //Those seem to pass, so take away line 206? } //Lets try testing so it throws excrption if thhe array doesn't have the right keys - - // To test the exception we need to test the riht output (from the exception) is generated, - // We cannot test ther 'caught' exception because it is thrown by the overriden error handler. So test that it shows the riht output + // We cannot test 'caught' exception because it is thrown by the overriden error handler, not the SUT. + // To test the exception we need to test the right output (from the exception) is generated, public function testcmi5launch_retrieve_aus_exception() { - //It's not just returning it, it's splitting it into chuncks~! - - // Note this is an innnnnncorrect statement, cut off before 'aus'. + // Note this is an incorrect statement, cut off before 'aus'. $mockStatement = array( "createdAt" => "2023-06-26T18:36:15.000Z", "id"=> 000, "lmsId"=> "https://example", "metadata" => array( )); - - //This is the expected output messager + // This is the expected output message. $expectedMessage = "Cannot retrieve AUs. Error found when trying to parse them from course creation: " . "Please check the connection to player or course format and try again. \n" . 'Cannot parse array. Error: Undefined array key "aus"' . "\n"; $helper = new au_helpers(); - //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" + // Call function under test. $retrieved = $helper->cmi5launch_retrieve_aus($mockStatement); // If the right message is displayed the try/catch wworked! $this->expectOutputString($expectedMessage); - } - - - - //Test function that is fed an array of statments and returns an array of aus onjects + // Test function that is fed an array of statments and returns an array of aus objects. public function testcmi5launch_create_aus() { - // Should be enough to pass the mock statement values here, make an array of them first - $testStatements = array(); + // Should be enough to pass the mock statement values here, make an array of them first. + $teststatements = array(); - //Lets create 4 aus statement + //Lets create 4 aus statement. for ($i = 0; $i < 4; $i++) { - $testStatements[$i][] = $this->mockStatementValues; + $teststatements[$i][] = $this->mockstatementvalues; } $helper = new au_helpers(); - //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" - $auList = $helper->cmi5launch_create_aus($testStatements); + // So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" + $auList = $helper->cmi5launch_create_aus($teststatements); - //There should be a total of 4 Aus in this array + // There should be a total of 4 Aus in this array. $this->assertCount(4, $auList, "Expected retrieved statement to have four aus"); - //And they should all be au objects + // And they should all be au objects. foreach ($auList as $au) { $this->assertInstanceOf(au::class, $au, "Expected retrieved statement to be an array of aus"); } } - //Test function that is fed an array of statments and returns an array of aus onjects + + // Test function creat aus null exception. public function testcmi5launch_create_aus_exception() { // If we pass a null value in, it should throw an exception immedietely - $testStatements = null; + $teststatements = null; $this->expectException(nullException::class); $this->expectExceptionMessage('Cannot retrieve AU information. AU statements from DB are: ' . null); $helper = new au_helpers(); - //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" - $helper->cmi5launch_create_aus($testStatements); - - + + // Pass null to SUT. + $helper->cmi5launch_create_aus($teststatements); } - //This one is going to be tricky, it saves to a DB! I know test php can have TEST DBs, but is that setup here? - //And how to freaking test THAT? - //Well, actually we don't need to test it goes to the DB, THAT was the job of the person who invented insert_record - //We just need tothat it saves the correct values and CALLS insert_record - //Technically this function returns ids, so we can make a stub which just returns ids - //This will test it is called without messing with the DB + // Test saving aus, this function returns ids, so we can make a stub which just returns ids. + // This will test it is called without messing with the DB. public function testcmi5launch_save_aus() { - // Make a global variable to hold the id's to pretend to be cmi5launch instance id. - global $cmi5launch; + global $cmi5launch, $auidForTest; $cmi5launch = new \stdClass(); $cmi5launch->id = 1; - // $cmi5launch->id = 1; // The func should return auids created by the DB when AU's were saved in array format. $helper = new au_helpers(); @@ -435,8 +363,6 @@ public function testcmi5launch_save_aus() //Lets create 4 aus statement for ($i = 0; $i < 3; $i++) { $testAus[$i][] = $this->mockStatement2; - // $testAus[$i][] = ($this->$cmi5launch); - // $testAus = array_merge($testAus, $cmi5launch); } //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" @@ -447,118 +373,75 @@ public function testcmi5launch_save_aus() // The array should have the same count of ids as AU's passed in $this->assertCount(3, $returnedAUids, "Expected retrieved statement to have three aus"); + // Now iterate through the returned array and ensure ids were passed back, numeric ids foreach ($returnedAUids as $auId) { - // what is id? - // echo"auId: $auId"; $this->assertIsNumeric($auId, "Expected array to have numeric values"); } - global $auidForTest; - //Save to use in next test? - $auidForTest = $returnedAUids; - //Do I need to test fail? + $auidForTest = $returnedAUids; } - //This one is going to be tricky, it saves to a DB! I know test php can have TEST DBs, but is that setup here? - //And how to freaking test THAT? - //Well, actually we don't need to test it goes to the DB, THAT was the job of the person who invented insert_record - //We just need tothat it saves the correct values and CALLS insert_record - //Technically this function returns ids, so we can make a stub which just returns ids - //This will test it is called without messing with the DB + // test saving aus with exceptions. public function testcmi5launch_save_aus_exceptions() { - // Make a global variable to hold the id's to pretend to be cmi5launch instance id. global $cmi5launch; $cmi5launch = new \stdClass(); $cmi5launch->id = 1; - // $cmi5launch->id = 1; // The func should return auids created by the DB when AU's were saved in array format. $helper = new au_helpers(); - // LEts try to pass in a value that an't be grabbed or encoded and see what happens? - - //Lets create 4 aus statement - // This one has a null title - $testAus[0][] = $this->mockStatementExcept; - - // $testAus[$i][] = ($this->$cmi5launch); - // $testAus = array_merge($testAus, $cmi5launch); + // Pass in a statement with something wrong. This one has a null title. + $testAus[0][] = $this->mockStatementExcept; - // These may be exceptions, buut they are thrown by ERROR handlers, therefore the SUT under test wont throw the error itself -// We need to tes toutput - //$this->expectException(fieldException::class); - // $this->expectExceptionMessage("Cannot save to DB. Stopped at record with ID number 1. One of the fields is incorrect. Check data for field 'title'. Error: Undefined array key 0"); - - // The expected is built bby the two messages knowing 'title' is an empty array. - $expected = "Cannot save to DB. Stopped at record with ID number " . 1 . "." + // Because this exception is thrown by the error handler, not the SUT, test the output to ensure right exception was thrown. + $expected = "Cannot save to DB. Stopped at record with ID number " . 1 . "." . " One of the fields is incorrect. Check data for field 'title'. Error: Undefined array key 0\n"; - //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" + + // Call function under test. $returnedAUids = $helper->cmi5launch_save_aus($helper->cmi5launch_create_aus($testAus)); // If the right message is displayed the try/catch wworked! $this->expectOutputString($expected); - - } - //This one is going to be tricky, it saves to a DB! I know test php can have TEST DBs, but is that setup here? - //And how to freaking test THAT? - //Well, actually we don't need to test it goes to the DB, THAT was the job of the person who invented insert_record - //We just need tothat it saves the correct values and CALLS insert_record - //Technically this function returns ids, so we can make a stub which just returns ids - //This will test it is called without messing with the DB + + // Test saving aus with exceptions, a different exception. public function testcmi5launch_save_aus_exceptions_2() { - // Make a global variable to hold the id's to pretend to be cmi5launch instance id. global $cmi5launch; $cmi5launch = new \stdClass(); $cmi5launch->id = 1; - // $cmi5launch->id = 1; // The func should return auids created by the DB when AU's were saved in array format. $helper = new au_helpers(); - // LEts try to pass in a value that an't be grabbed or encoded and see what happens? + // This first statement is correct. We want to test that it gets the SECOND statement number, + $testAus[0][] = $this->mockStatement2; + // This one has 'title' as string instead of array. + $testAus[1][] = $this->mockStatementExcept2; - //Lets create 4 aus statement - - // This one is correct. We want to test that it gets the SECOND statement number - // as a test - $testAus[0][] = $this->mockStatement2; - // This one has a missing launch url conplteley - $testAus[1][] = $this->mockStatementExcept2; - // $testAus[$i][] = ($this->$cmi5launch); - // $testAus = array_merge($testAus, $cmi5launch); - - // The expected is built bby the two messages knowing 'title' is an empty array. - $expected = "Cannot save to DB. Stopped at record with ID number " . 2 . "." - . " One of the fields is incorrect. Check data for field 'title'. Cannot access offset of type string on string\n"; - - //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" + // The expected is built by the two messages knowing 'title' is a string. + $expected = "Cannot save to DB. Stopped at record with ID number " . 2 . "." + . " One of the fields is incorrect. Check data for field 'title'. Cannot access offset of type string on string\n"; + + // Call the function to throw the exception. $returnedAUids = $helper->cmi5launch_save_aus($helper->cmi5launch_create_aus($testAus)); - // If the right message is displayed the try/catch wworked! - $this->expectOutputString($expected); + + // Because this exception is thrown by the error handler, not the SUT, test the output to ensure right exception was thrown. + $this->expectOutputString($expected); - //Do I need to test fail? - - } - //This one is going to be tricky, it saves to a DB! I know test php can have TEST DBs, but is that setup here? - //And how to freaking test THAT? - //Well, actually we don't need to test it goes to the DB, THAT was the job of the person who invented insert_record - //We just need tothat it saves the correct values and CALLS insert_record - //Technically this function returns ids, so we can make a stub which just returns ids - //This will test it is called without messing with the DB + // Test saving aus with exceptions, a (null) exception. public function testcmi5launch_save_aus_exceptions_test_null() { @@ -567,33 +450,26 @@ public function testcmi5launch_save_aus_exceptions_test_null() $cmi5launch = new \stdClass(); $cmi5launch->id = 1; - // $cmi5launch->id = 1; - // The func should return auids created by the DB when AU's were saved in array format. $helper = new au_helpers(); - // LEts try to pass in a value that an't be grabbed or encoded and see what happens? + // A test statement with a null value. + $testAus = null; - //Lets create 4 aus statement - - // This one has a null title - $testAus = null; - - // And this one the SUT is the one THTOWINGthe exception so it should be catchable - $this->expectException(nullException::class); - $this->expectExceptionMessage('Cannot save AU information. AU object array is: null' . null); - + // Catch the exception. + $this->expectException(nullException::class); + $this->expectExceptionMessage('Cannot save AU information. AU object array is: null' . null); - // The expected is built bby the two messages knowing 'title' is an empty array. - $expected = "Cannot save to DB. Stopped at record with ID number " . 1 . "." + // The expected is built bby the two messages knowing 'title' is an empty array. + $expected = "Cannot save to DB. Stopped at record with ID number " . 1 . "." . " One of the fields is incorrect. Check data for field 'title'. Error: Undefined array key 0\n"; //So now with this fake 'statement', lets ensure it pulls the correct value which is "correct Retrieval" $returnedAUids = $helper->cmi5launch_save_aus($testAus); - - + } + // Test retrieving an AU from the DB with a correct value. public function testcmi5launch_retrieve_aus_from_db() { // Access the global array of ids from above test @@ -610,34 +486,22 @@ public function testcmi5launch_retrieve_aus_from_db() // And the return should be an au object $this->assertInstanceOf(au::class, $returnedAu, "Expected retrieved object to be an au object"); } - - } + // Test retrieving an AU from the DB with a null value and thrown exception. public function testcmi5launch_retrieve_aus_from_db_null_exception() { - // Access the global array of ids from above test - global $auidForTest; - - // global $auidForTest; $helper = new au_helpers(); - // And if it fails it should fail gracefully + // And if it fails it should fail gracefully, throwin the correct exception. $badid = 0; - - // And this one the SUT is the one THTOWINGthe exception so it should be catchable - $this->expectException(nullException::class); - $this->expectExceptionMessage("Error attempting to get AU data from DB. Check AU id. AU id is: " . $badid ."" . null); - - + // Catch the exception. + $this->expectException(nullException::class); + $this->expectExceptionMessage("Error attempting to get AU data from DB. Check AU id. AU id is: " . $badid ."" . null); + $returnedAu = $helper->cmi5launch_retrieve_aus_from_db($badid); - - // And the return should be a false value - // $this->assertNotTrue($returnedAu, "Expected retrieved object to be false"); - //And it should output this error message - // $this->expectOutputString("Error attempting to get AU data from DB. Check AU id. AU id is: " . $badid . "
"); } } \ No newline at end of file diff --git a/cmi5PHP/tests/errorOverTest.php b/cmi5PHP/tests/errorOverTest.php index f1163e8..38d4c7c 100644 --- a/cmi5PHP/tests/errorOverTest.php +++ b/cmi5PHP/tests/errorOverTest.php @@ -4,19 +4,19 @@ use mod_cmi5launch\local\nullException; use PHPUnit\Framework\TestCase; use mod_cmi5launch\local\au; -use mod_cmi5launch\local\errorOver; +use mod_cmi5launch\local\errorover; -require_once(dirname(dirname(dirname(__FILE__))) . 'cmi5lPHP\tests\errorOver.php'); +require_once(dirname(dirname(dirname(__FILE__))) . 'cmi5lPHP\tests\errorover.php'); /** * Tests for AuHelpers class. * * @copyright 2023 Megan Bohland * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * - * @covers \errorOver - * @covers \errorOver::array_chunk_warning + * @covers \errorover + * @covers \errorover::array_chunk_warning */ -class errorOverTest extends TestCase +class erroroverTest extends TestCase { /** @@ -29,7 +29,7 @@ public function testcmi5launch_retrieve_aus_exception() $this->expectException(nullException::class); //can we just call it? - // is this necessary? errorOver::array_chunk_warning(E_WARNING, "This is a test error", "testfile.php", 1); + // is this necessary? errorover::array_chunk_warning(E_WARNING, "This is a test error", "testfile.php", 1); }