import pytest
from exploits.hashes.collisions import adler32
from test.exploits.dummy_output import DummyOutput


def adler32_hash(bytes, hash_table_size):
    v1 = 1
    v2 = 0
    for byte in bytes:
        v1 = (v1 + ord(byte)) % 65521
        v2 = (v2 + v1) % 65521
    return (v2 * 65536 + v1) % hash_table_size


def test_run():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 100
    target = '42'
    length = 10
    adler32.options['n_collisions'] = n_collisions
    adler32.options['length'] = length
    adler32.options['target_type'] = 'image'
    adler32.options['target'] = target
    adler32.options['hash_table_size'] = hash_table_size
    adler32.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert adler32_hash(i, hash_table_size) == int(target)
        assert len(i) == length


def test_more_collisions():
    output = DummyOutput()
    n_collisions = 20
    hash_table_size = 10
    target = '5'
    length = 10
    adler32.options['n_collisions'] = n_collisions
    adler32.options['length'] = length
    adler32.options['target_type'] = 'image'
    adler32.options['target'] = target
    adler32.options['hash_table_size'] = hash_table_size
    adler32.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert adler32_hash(i, hash_table_size) == int(target)
        assert len(i) == length


def test_short_length():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 100
    target = '42'
    length = 5
    adler32.options['n_collisions'] = n_collisions
    adler32.options['length'] = length
    adler32.options['target_type'] = 'image'
    adler32.options['target'] = target
    adler32.options['hash_table_size'] = hash_table_size
    adler32.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert adler32_hash(i, hash_table_size) == int(target)
        assert len(i) == length


def test_preimage():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 100
    target = 'hello'
    length = len(target)
    adler32.options['n_collisions'] = n_collisions
    adler32.options['length'] = length
    adler32.options['target_type'] = 'preimage'
    adler32.options['target'] = target
    adler32.options['hash_table_size'] = hash_table_size
    adler32.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert adler32_hash(i, hash_table_size) == adler32_hash(target, hash_table_size)
        assert len(i) == length


def test_too_short():
    output = DummyOutput()
    n_collisions = 100
    hash_table_size = 100
    target = '42'
    length = 1
    adler32.options['n_collisions'] = n_collisions
    adler32.options['length'] = length
    adler32.options['target_type'] = 'image'
    adler32.options['target'] = target
    adler32.options['hash_table_size'] = hash_table_size
    with pytest.raises(ValueError):
        adler32.run(output)
