package org.kohsuke.file_leak_detector;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.kohsuke.asm6.ClassReader;
import org.kohsuke.asm6.util.CheckClassAdapter;
import org.kohsuke.file_leak_detector.transform.ClassTransformSpec;
import org.kohsuke.file_leak_detector.transform.TransformerImpl;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipFile;

/**
 * @author Kohsuke Kawaguchi
 */
@RunWith(Parameterized.class)
public class TransformerTest {
    List<ClassTransformSpec> specs = AgentMain.createSpec();

    Class<?> c;
    
    public TransformerTest(Class<?> c) {
        this.c = c;
    }

    @Test
    public void testInstrumentations() throws Exception {
        TransformerImpl t = new TransformerImpl(specs);

        String name = c.getName().replace('.', '/');
        byte[] data = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream(name + ".class"));
        byte[] data2 = t.transform(name,data);

//        File classFile = new File("/tmp/" + name + ".class");
//        classFile.getParentFile().mkdirs();
//        FileOutputStream o = new FileOutputStream(classFile);
//        o.write(data2);
//        o.close();

        CheckClassAdapter.verify(new ClassReader(data2), false, new PrintWriter(System.err));
    }
    
    @Parameters
    public static List<Object[]> specs() throws Exception {
        List<Object[]> r = new ArrayList<Object[]>();
        for (ClassTransformSpec s : AgentMain.createSpec()) {
            Class<?> c = TransformerTest.class.getClassLoader().loadClass(s.name.replace('/', '.'));
            r.add(new Object[]{c});
        }
        return r;
    }
}

@@ -438,16 +438,54 @@
 rImpl;%0A%0A
+import java.io.ByteArrayOutputStream;%0A
 import j
@@ -559,35 +559,104 @@
 st;%0A
+%0A
 import 
-java.util.zip.ZipFil
+static java.nio.charset.StandardCharsets.UTF_8;%0Aimport static org.junit.Assert.assertTru
 e;%0A%0A
@@ -1457,24 +1457,182 @@
 o.close();%0A%0A
+        String errors;%0A        ClassReader classReader = new ClassReader(data2);%0A        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) %7B%0A    
         Chec
@@ -1652,21 +1652,17 @@
 .verify(
-new C
+c
 lassRead
@@ -1663,23 +1663,16 @@
 ssReader
-(data2)
 , false,
@@ -1692,18 +1692,168 @@
 ter(
-System.err
+baos));%0A            errors = new String(baos.toByteArray(), UTF_8);%0A        %7D%0A        assertTrue(%22Verification failed for %22 + c + %22%5Cn%22 + errors, errors.isEmpty(
 ));%0A

Add a missing assertion to `TransformerTest` (#59)