Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 11 | class LoggerTest extends \PHPUnit_Framework_TestCase |
||
| 12 | { |
||
| 13 | public static $full_log_location; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * @var File $log_file |
||
| 17 | */ |
||
| 18 | public static $log_file; |
||
| 19 | |||
| 20 | public static function setUpBeforeClass() |
||
| 21 | { |
||
| 22 | self::$full_log_location = DILMUN_LOGS_DIR . "Logger_test.log"; |
||
| 23 | |||
| 24 | if (file_exists(self::$full_log_location)) { |
||
| 25 | unlink(self::$full_log_location); |
||
| 26 | } |
||
| 27 | |||
| 28 | self::$log_file = new File(self::$full_log_location); |
||
| 29 | self::$log_file->initialize(); |
||
| 30 | } |
||
| 31 | |||
| 32 | protected function assertPreconditions() |
||
| 33 | { |
||
| 34 | $this->assertFileExists(self::$full_log_location); |
||
| 35 | } |
||
| 36 | |||
| 37 | protected function setUp() |
||
| 38 | { |
||
| 39 | if (file_exists(self::$full_log_location)) { |
||
| 40 | self::$log_file->clearFile(); |
||
| 41 | } |
||
| 42 | } |
||
| 43 | |||
| 44 | protected function tearDown() |
||
| 45 | { |
||
| 46 | } |
||
| 47 | |||
| 48 | public static function tearDownAfterClass() |
||
| 49 | { |
||
| 50 | if (file_exists(self::$full_log_location)) { |
||
| 51 | unlink(self::$full_log_location); |
||
| 52 | } |
||
| 53 | } |
||
| 54 | |||
| 55 | public function testLogToFileWithFileHandler() |
||
| 56 | { |
||
| 57 | $logger = new Logger(self::$log_file); |
||
| 58 | |||
| 59 | $returned_message = $logger->log("debug", "Logging works!"); |
||
| 60 | |||
| 61 | $logged_message = file_get_contents(self::$full_log_location); |
||
| 62 | |||
| 63 | $this->assertContains($returned_message, $logged_message); |
||
| 64 | } |
||
| 65 | |||
| 66 | /** |
||
| 67 | * @expectedException \InvalidArgumentException |
||
| 68 | */ |
||
| 69 | public function testLoggerThrowsExceptionWithInvalidLogLevel() |
||
| 70 | { |
||
| 71 | $logger = new Logger(self::$log_file); |
||
| 72 | |||
| 73 | $logger->log("this is not a valid level", "this should never be logged"); |
||
| 74 | } |
||
| 75 | |||
| 76 | public function testGetHandlerReturnsHandler() |
||
| 77 | { |
||
| 78 | $logger = new Logger(self::$log_file); |
||
| 79 | |||
| 80 | $handler = $logger->getHandler(); |
||
| 81 | |||
| 82 | if ($handler instanceof File) { |
||
| 83 | $handler_is_file = true; |
||
| 84 | } else { |
||
| 85 | $handler_is_file = false; |
||
| 86 | } |
||
| 87 | |||
| 88 | $this->assertTrue($handler_is_file); |
||
| 89 | } |
||
| 90 | } |
||
| 91 |