2012-10-10 20 views
5

¿Puedo utilizar ApprovalTests con archivos PDF? Intenté usar FileLauncher, pero parece que los PDF idénticos son ligeramente diferentes a nivel de archivo (bit). ¿O lo usé incorrectamente?Approvaltests y PDF

[TestMethod] 
[UseReporter(typeof(FileLauncherReporter))] 
public void TestPdf() 
{ 
    var createSomePdf = PdfCreate(); 

    ApprovalTests.Approvals.Verify(new FileInfo(createSomePdf.FileName)); 

} 

Respuesta

6

El Pdf probablemente se está creando con una marca de tiempo. Dependiendo del método utilizado para crear el pdf, es posible que pueda simular el tiempo creado. pero tuve que fregarlo.

Aquí está el código que solía hacer eso.

public static void VerifyPdf(string coverFile) 
    { 
     ScrubPdf(coverFile); 
     Approvals.Verify(new ExistingFileWriter(coverFile)); 
    } 

    private static void ScrubPdf(string coverFile) 
    { 
     long location; 
     using (var pdf = File.OpenRead(coverFile)) 
     { 
      location = Find("/CreationDate (", pdf); 

     } 
     using (var pdf = File.OpenWrite(coverFile)) 
     { 
      pdf.Seek(location, SeekOrigin.Begin); 

      var original = "/CreationDate (D:20110426104115-07'00')"; 
      var desired = new System.Text.ASCIIEncoding().GetBytes(original); 

      pdf.Write(desired, 0, desired.Length); 
      pdf.Flush(); 
     } 
    } 
+0

brillante, gracias Llewellyn, también había una fecha y documento de identidad modificada creada por mi pdf-generador (iTextSharp), tuvo que añadirlos también. – joeriks

5

Encontré una herramienta de línea de comandos, diff-pdf. Compara 2 PDF y devuelve el código de salida 0 si son iguales, 1 si difieren. Descarga + extracto + agrégalo a tu RUTA.

Desventaja: debe representar ambos archivos PDF para realizar la diferencia. Si son grandes, perf golpear.

aprobador (basado en gran medida en ApprovalTests.Approvers.FileApprover):

public class DiffPdfApprover : IApprovalApprover 
{ 
    public static void Verify(byte[] bytes) 
    { 
     var writer = new ApprovalTests.Writers.BinaryWriter(bytes, "pdf"); 
     var namer = ApprovalTests.Approvals.GetDefaultNamer(); 
     var reporter = ApprovalTests.Approvals.GetReporter(); 

     ApprovalTests.Core.Approvals.Verify(new DiffPdfApprover(writer, namer), reporter); 
    } 

    private DiffPdfApprover(IApprovalWriter writer, IApprovalNamer namer) 
    { 
     this.writer = writer; 
     this.namer = namer; 
    } 

    private readonly IApprovalNamer namer; 
    private readonly IApprovalWriter writer; 
    private string approved; 
    private ApprovalException failure; 
    private string received; 

    public virtual bool Approve() 
    { 
     string basename = string.Format(@"{0}\{1}", namer.SourcePath, namer.Name); 
     approved = Path.GetFullPath(writer.GetApprovalFilename(basename)); 
     received = Path.GetFullPath(writer.GetReceivedFilename(basename)); 
     received = writer.WriteReceivedFile(received); 

     failure = Approve(approved, received); 
     return failure == null; 
    } 

    public static ApprovalException Approve(string approved, string received) 
    { 
     if (!File.Exists(approved)) 
     { 
      return new ApprovalMissingException(received, approved); 
     } 

     var process = new Process(); 
     //settings up parameters for the install process 
     process.StartInfo.FileName = "diff-pdf"; 
     process.StartInfo.Arguments = String.Format("\"{0}\" \"{1}\"", received, approved); 

     process.Start(); 

     process.WaitForExit(); 

     if (process.ExitCode != 0) 
     { 
      return new ApprovalMismatchException(received, approved); 
     } 

     return null; 
    } 

    public void Fail() 
    { 
     throw failure; 
    } 

    public void ReportFailure(IApprovalFailureReporter reporter) 
    { 
     reporter.Report(approved, received); 
    } 

    public void CleanUpAfterSucess(IApprovalFailureReporter reporter) 
    { 
     File.Delete(received); 
     if (reporter is IApprovalReporterWithCleanUp) 
     { 
      ((IApprovalReporterWithCleanUp)reporter).CleanUp(approved, received); 
     } 
    } 
} 

para verificar:

DiffPdfApprover.Verify(pdfBytes);

diff-PDF pueden mostrar visualmente las diferenciaciones también. Lancé un Reporter para esto, pero no lo uso mucho. Creo que será útil si hay regresiones después del desarrollo del informe inicial (que es donde estoy ahora mismo).

public class DiffPdfReporter : GenericDiffReporter 
{ 
    private static readonly string Path = FindFullPath("diff-pdf.exe"); 
    public DiffPdfReporter() : base(Path, 
     GetArgs(), 
     "Please put diff-pdf.exe in your %PATH%. https://github.com/vslavik/diff-pdf. And restart whatever's running the tests. Everything seems to cache the %PATH%.") { } 

    private static string GetArgs() 
    { 
     return "--view \"{0}\" \"{1}\""; 
    } 

    private static string FindFullPath(string programInPath) 
    { 
     foreach (var path in from path in Environment.GetEnvironmentVariable("path").Split(';') 
          select path) 
     { 
      var fullPath = System.IO.Path.Combine(path, programInPath); 
      if (File.Exists(fullPath)) 
       return fullPath; 
     } 
     return null; 
    } 
} 
1

Parece que está construido en ApprovalTests ahora.

uso:

Approvals.VerifyPdfFile(pdfFileLocation); 

Ver the source:

public static void VerifyPdfFile(string pdfFilePath) 
{ 
    PdfScrubber.ScrubPdf(pdfFilePath); 
    Verify(new ExistingFileWriter(pdfFilePath)); 
} 
+0

Soy nuevo en ApprovalTests y por lo que he visto la documentación es bastante escaso (especialmente para archivos PDF). ¿Podría explicar cómo escribiría una prueba unitaria que verifica un PDF? El ejemplo en github hace que parezca un filename.recieved.pdf debería haberse creado, pero no puedo encontrar uno. – Ben

+1

@Ben eche un vistazo al [ejemplo de prueba de unidad] (https://github.com/approvals/ApprovalTests.Net/blob/master/ApprovalTests.Tests/Pdf/PdfTest.cs) en el proyecto. Pero tiene razón, no parece crear un archivo .recibido para archivos PDF. Yo mismo lo creo en mis pruebas. – Mathew

+0

gracias @Mathew. Al menos ejecuta la comparación ahora, pero aún falla. Si comparo los dos documentos de mi ser la fecha de creación es diferente (supongo que es atendido por el método PdfScrubber.ScrubPdf (...)), y también hay un par de GUID cerca de la parte inferior del archivo que difieren – Ben

Cuestiones relacionadas