Last active
October 29, 2015 09:47
-
-
Save Loupax/6bacd52c1d2d28b5460f to your computer and use it in GitHub Desktop.
A function that generates assertions against the schema of a specific object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Helper function that generates tests for the | |
| * schema and data of a specific object. | |
| * | |
| * NOTE: | |
| * IF THE DATA IN THE OBJECT IS WRONG, THE GENERATED | |
| * TESTS WILL BE WRONG. | |
| * It is still your responsibility to make sure your | |
| * tests are correct. This function only exists to | |
| * save you the typing. | |
| * | |
| * Also non-native objects are not handled correctly. | |
| * Didn't bother fixing since those objects should | |
| * be tested separately | |
| * | |
| * <code> | |
| * $object = json_decode("{'prop':1, 'prop2': 'two', 'prop3':true, 'prop4':null }"); | |
| * echo generateTestsForObject($object, '$object'); | |
| * // $this->assertEquals(1, $object->prop); | |
| * // $this->assertEquals('two', $object->prop2) | |
| * // $this->assertTrue($object->prop3) | |
| * // $this->assertNull($object->prop4) | |
| * </code> | |
| * | |
| * @param \stdClass $object The object we are generating the tests for | |
| * @param string $objectName The name of the object | |
| * | |
| * @return string | |
| */ | |
| protected function generateTestsForObject($object, $objectName = '$name') | |
| { | |
| $test = []; | |
| $test[] = '$this->assertInstanceOf(\''.get_class($object).'\', '.$objectName.');'; | |
| foreach ($object as $prop => $value) { | |
| if ($value === true) { | |
| $test[] = '$this->assertTrue(' . $objectName . '->' . $prop . ');'; | |
| } elseif ($value === false) { | |
| $test[] = '$this->assertFalse(' . $objectName . '->' . $prop . ');'; | |
| } elseif ($value === null) { | |
| $test[] = '$this->assertNull(' . $objectName . '->' . $prop . ');'; | |
| } elseif ($value instanceof \DateTime) { | |
| $test[] = '$this->assertInstanceOf(\'\\DateTime\', '.$objectName.'->'.$prop.');'; | |
| $test[] = '$testDate = new \DateTime(\''.$value->format('Y-m-d H:i:s.m').'\');'; | |
| $test[] = '$this->assertEquals($testDate->format(\'U\'), '.$objectName.'->'.$prop.'->format(\'U\'));'; | |
| } else { | |
| $value = json_encode($value); | |
| $test[] = '$this->assertEquals(' . $value . ', ' . $objectName . '->' . $prop . ');'; | |
| } | |
| } | |
| return implode(PHP_EOL, $test); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment