from jawa.cf import ClassFile
from jawa.util.classloader import ClassLoader
from jawa.transforms.simple_swap import simple_swap
from jawa.assemble import assemble


def test_load_from_class():
    """Ensure we can add ClassFile's directly to the ClassLoader."""
    cl = ClassLoader()

    cf = ClassFile.create('TestClass')
    cl.update(cf)

    assert cl.load('TestClass') is cf


def test_default_bytecode_transforms():
    cl = ClassLoader(bytecode_transforms=[simple_swap])

    cf = ClassFile.create('TestClass')
    cl.update(cf)

    test_method = cf.methods.create('test', '(V)V;', code=True)
    test_method.code.max_stack = 2
    test_method.code.max_locals = 0

    test_method.code.assemble(assemble([
        ('iconst_0',),
        ('pop',),
        ('return',)
    ]))

    # Load from the ClassLoader to bind to it.
    cf = cl.load('TestClass')

    # Ensure the defaults apply.
    ins_iter = test_method.code.disassemble()
    ins = next(ins_iter)
    assert ins.mnemonic == 'bipush'
    assert len(ins.operands) == 1
    assert ins.operands[0].value == 0

    # Ensure we can override the default.
    ins_iter = test_method.code.disassemble(transforms=[])
    ins = next(ins_iter)
    assert ins.mnemonic == 'iconst_0'
    assert len(ins.operands) == 0

@@ -1,16 +1,77 @@
+import os.path%0Aimport shutil%0Aimport tempfile%0Aimport zipfile%0A%0A
 from jawa.cf imp
@@ -1325,12 +1325,1144 @@
 rands) == 0%0A
+%0A%0Adef test_load_from_directory():%0A    %22%22%22Ensure we can load a ClassFile from a simple directory.%22%22%22%0A    with tempfile.TemporaryDirectory() as dir:%0A        shutil.copy(%0A            os.path.join(%0A                os.path.dirname(__file__),%0A                'data',%0A                'HelloWorld.class'%0A            ),%0A            dir%0A        )%0A%0A        cl = ClassLoader()%0A        cl.update(dir)%0A%0A        assert isinstance(cl.load('HelloWorld'), cl.klass)%0A        assert isinstance(cl.load('HelloWorld.class'), cl.klass)%0A%0A%0Adef test_load_from_zipfile():%0A    %22%22%22Ensure we can load a ClassFile from a ZipFile.%22%22%22%0A    with tempfile.NamedTemporaryFile(suffix='.jar') as tmp:%0A        with zipfile.ZipFile(tmp, 'w') as zf:%0A            zf.write(%0A                os.path.join(%0A                    os.path.dirname(__file__),%0A                    'data',%0A                    'HelloWorld.class'%0A                ),%0A                arcname='HelloWorld.class'%0A%0A            )%0A%0A        cl = ClassLoader()%0A        cl.update(tmp.name)%0A%0A        assert isinstance(cl.load('HelloWorld'), cl.klass)%0A        assert isinstance(cl.load('HelloWorld.class'), cl.klass)%0A

Add ClassLoader tests for loading from directories and from zipfiles.