Julho 26th 2007 04:41 am
Criando Listener para o PHPUnit
propositalmente, criei um teste que gera um erro, outro gerando uma falha outro com sucesso e assim por diante, para poder ilustrar nosso exemplo de formatação de resultados melhor.
Tipicamente poderiamos pelo console testar este TestCase apenas executando:
phpunit ArrayObjectTest.php
o resultado seria:
PHPUnit 3.1.3 by Sebastian Bergmann.
IF.SE
Time: 0 seconds
There was 1 error:
1) testAppend(ArrayObjectTest)
Exception: Este teste irá gerar um erro
There was 1 failure:
1) testOffsetGet(ArrayObjectTest)
'Valor 2' não é igual a 'Valor 1'
C:\localhost\phpunit-listener\ArrayObjectTest.php:59
FAILURES!
Tests: 5, Failures: 1, Errors: 1, Incomplete: 1, Skipped: 1.
A questão é: e se eu quiser gravar esses resultados em um arquivo e envia-lo por email?
Uma solução elegante para esse tipo de problema é criar um listener para armazenar os resultados da execução, implementando a interface PHPUnit_Framework_TestListener disponível no framework do PHPUnit e extendendo a classe PHPUnit_Util_Printer também disponível no framework.
Da seguinte maneira:
-
<?php
-
require_once 'PHPUnit/Framework.php';
-
-
/**
-
* Listener responsável por armazenar os resultados e formatalos como html,
-
* opcionalmente pode ser enviado um email com os resultados dos testes
-
*
-
* @author Diego Tremper
-
*/
-
class MailListener extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener {
-
-
/**
-
* @var resource
-
*/
-
private $sOutput = NULL;
-
-
/**
-
* @var string
-
*/
-
private $sTitle = '';
-
-
/**
-
* @var bool
-
*/
-
private $bSendMail;
-
-
/**
-
* @var int
-
*/
-
private $iTestCounter;
-
-
private $fStartTests = null, $fEndtTests = null;
-
-
/**
-
* Ao construir o objeto, escreve no arquivo .html
-
* os cabeçalhos e os estilos da página de resultados
-
*
-
* uso:
-
*
-
* $o = new MailListener();
-
* $o = new MailListener(true); <-- neste caso enviará
-
* um email com os resultados dos testes
-
*
-
* @param bool $bSendMail
-
*/
-
public function __construct($bSendMail = false) {
-
$this->bSendMail = $bSendMail;
-
-
$this->sTitle = "Resultado dos dos testes unitários executados em " . $_SERVER['COMPUTERNAME'];
-
$sHeader = "<html>\r\n<head>\r\n <title>".$this->sTitle."</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n";
-
$sHeader .= "
-
<style>
-
h1 {
-
font-family: \"Lucida Sans\",Georgia,Verdana,Arial,Serif;
-
}
-
body {
-
font-family: Arial;
-
}
-
.error {
-
background-color:red;
-
}
-
.failure {
-
background-color:red;
-
}
-
.incomplete {
-
background-color:yellow;
-
}
-
.skipped {
-
background-color:yellow;
-
}
-
</style>";
-
$sHeader .= "</head>\r\n<body>\r\n<table>\r\n <tr>\r\n <td><h1>".$this->sTitle."<h1></td>\r\n </tr>\r\n</table>\r\n<table width=\"100%\">\r\n";
-
-
$sHeader .= " <tr>\r\n";
-
$sHeader .= " <th>Teste</th>\r\n";
-
$sHeader .= " <th>Status</th>\r\n";
-
$sHeader .= " <th>Mensagem adicional</th>\r\n";
-
$sHeader .= " </tr>\r\n";
-
-
$this->sOutput = fopen('resultado.html', 'wb');
-
fwrite($this->sOutput, $sHeader);
-
-
}
-
-
/**
-
* escreve a saída no arquivo .html, opcionalmente
-
* envia um email dos resultados
-
*
-
*/
-
public function flush() {
-
if (is_resource($this->sOutput)) {
-
$sFooter = "<i>".$this->iTestCounter." testes executados em ".($this->fEndtTests - $this->fStartTests)." segundos.</i>";
-
$sFooter .= "</body>";
-
fwrite($this->sOutput, "</table>\r\n".$sFooter);
-
fclose($this->sOutput);
-
-
if ($this->bSendMail)
-
$this->sendMail();
-
}
-
}
-
-
/**
-
* escreve uma string no arquivo .html
-
*
-
* @param string $sText
-
*/
-
public function write($sText) {
-
if (is_resource($this->sOutput)) {
-
fwrite($this->sOutput, $sText);
-
}
-
}
-
-
/**
-
* método invocado no caso de um teste dar error
-
*
-
* @param PHPUnit_Framework_Test $test
-
* @param Exception $e
-
* @param unknown_type $time
-
*/
-
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) {
-
$sText = " <tr class=\"error\">\r\n";
-
$sText .= " <td>".$test->getName()."</td>\r\n";
-
$sText .= " <td>Erro</td>\r\n";
-
$sText .= " <td>".$e->getMessage()."</td>\r\n";
-
$sText .= " </tr>\r\n";
-
$this->write($sText);
-
}
-
-
/**
-
* método invocado no caso de um teste falhar
-
*
-
* @param PHPUnit_Framework_Test $test
-
* @param PHPUnit_Framework_AssertionFailedError $e
-
* @param unknown_type $time
-
*/
-
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) {
-
$sText = " <tr class=\"failure\">\r\n";
-
$sText .= " <td>".$test->getName()."</td>\r\n";
-
$sText .= " <td>Falha</td>\r\n";
-
$sText .= " <td>".$e->getMessage()."</td>\r\n";
-
$sText .= " </tr>\r\n";
-
$this->write($sText);
-
}
-
-
/**
-
* método invocado no caso de um teste for marcado como incompleto
-
*
-
* @param PHPUnit_Framework_Test $test
-
* @param Exception $e
-
* @param unknown_type $time
-
*/
-
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) {
-
$sText = " <tr class=\"incomplete\">\r\n";
-
$sText .= " <td>".$test->getName()."</td>\r\n";
-
$sText .= " <td>Incompleto</td>\r\n";
-
$sText .= " <td>".$e->getMessage()."</td>\r\n";
-
$sText .= " </tr>\r\n";
-
$this->write($sText);
-
}
-
-
/**
-
* método invocado caso a execução 'pule' o teste
-
*
-
* @param PHPUnit_Framework_Test $test
-
* @param Exception $e
-
* @param unknown_type $time
-
*/
-
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) {
-
$sText = " <tr class=\"skipped\">\r\n";
-
$sText .= " <td>".$test->getName()."</td>\r\n";
-
$sText .= " <td>Pulado</td>\r\n";
-
$sText .= " <td>".$e->getMessage()."</td>\r\n";
-
$sText .= " </tr>\r\n";
-
$this->write($sText);
-
}
-
-
/**
-
* invocado ao iniciar um TestCase, apenas conta quantos
-
* testes são executados
-
*
-
* @param PHPUnit_Framework_Test $test
-
*/
-
public function startTest(PHPUnit_Framework_Test $test) {
-
$this->iTestCounter++;
-
if ($this->fStartTests === null) {
-
$this->fStartTests = microtime(true);
-
}
-
}
-
-
/**
-
* invocado ao finalizar um TestCase
-
*
-
* @param PHPUnit_Framework_Test $test
-
* @param unknown_type $time
-
*/
-
public function endTest(PHPUnit_Framework_Test $test, $time) {
-
$this->fEndtTests = microtime(true);
-
}
-
-
/**
-
* invocado ao iniciar uma suite de testes
-
*
-
* @param PHPUnit_Framework_TestSuite $suite
-
*/
-
public function startTestSuite(PHPUnit_Framework_TestSuite $suite) {
-
//suite de teste iniciada
-
}
-
-
/**
-
* invocado ao finalizar uma suite de testes
-
*
-
* @param PHPUnit_Framework_TestSuite $suite
-
*/
-
public function endTestSuite(PHPUnit_Framework_TestSuite $suite) {
-
//suite de teste finalizada
-
}
-
-
/**
-
* envia um email para o usuário com o conteúdo
-
* do arquivo resultado.html
-
*
-
*/
-
private function sendMail() {
-
$headers = "Content-type: text/html; charset=UTF-8\r\n";
-
mail("contato@diegotremper.com", $this->sTitle, file_get_contents('resultado.html'), $headers);
-
}
-
}
salve este código em um arquivo chamado MailListener.php
No Comments yet »













