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


def sum_hash(bytes, hash_table_size):
    v1 = 0
    for byte in bytes:
        v1 += ord(byte)
    return v1 % hash_table_size


def test_run():
    output = DummyOutput()
    n_collisions = 1
    length = 10
    hash_table_size = 100
    target = '42'
    sum.options['n_collisions'] = n_collisions
    sum.options['length'] = length
    sum.options['hash_table_size'] = hash_table_size
    sum.options['target_type'] = 'image'
    sum.options['target'] = target
    sum.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert sum_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'
    sum.options['n_collisions'] = n_collisions
    sum.options['length'] = length
    sum.options['hash_table_size'] = hash_table_size
    sum.options['target_type'] = 'image'
    sum.options['target'] = target
    sum.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert sum_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'
    sum.options['n_collisions'] = n_collisions
    sum.options['length'] = length
    sum.options['hash_table_size'] = hash_table_size
    sum.options['target_type'] = 'image'
    sum.options['target'] = target
    sum.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert sum_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'
    sum.options['n_collisions'] = n_collisions
    sum.options['length'] = length
    sum.options['hash_table_size'] = hash_table_size
    sum.options['target_type'] = 'image'
    sum.options['target'] = target
    with pytest.raises(ValueError):
        sum.run(output)
