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


def xor8_hash(bytes, hash_table_size):
    v1 = 0
    for byte in bytes:
        v1 = (v1 ^ ord(byte)) & 0xff
    return v1 % hash_table_size


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


def test_more_collisions():
    output = DummyOutput()
    n_collisions = 3
    length = 5
    hash_table_size = 100
    target = '42'
    xor8.options['n_collisions'] = n_collisions
    xor8.options['length'] = length
    xor8.options['hash_table_size'] = hash_table_size
    xor8.options['target_type'] = 'image'
    xor8.options['target'] = target
    xor8.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert xor8_hash(i, hash_table_size) == int(target)
        assert len(i) == length


def test_larger_width():
    output = DummyOutput()
    n_collisions = 1
    length = 5
    hash_table_size = 100
    target = '42'
    xor8.options['n_collisions'] = n_collisions
    xor8.options['length'] = length
    xor8.options['hash_table_size'] = hash_table_size
    xor8.options['target_type'] = 'image'
    xor8.options['target'] = target
    xor8.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert xor8_hash(i, hash_table_size) == int(target)
        assert len(i) == length


def test_length_too_short():
    output = DummyOutput()
    n_collisions = 300
    length = 2
    hash_table_size = 100
    target = '42'
    xor8.options['n_collisions'] = n_collisions
    xor8.options['length'] = length
    xor8.options['hash_table_size'] = hash_table_size
    xor8.options['target_type'] = 'image'
    xor8.options['target'] = target
    with pytest.raises(ValueError):
        xor8.run(output)
