from exploits.hashes.collisions import php5
from exploits.hashes.collisions import php5_common
from test.exploits.dummy_output import DummyOutput
from input.chars import CharGenerator


def test_run_small_collision_count():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 2**32
    target = '42'
    php5.options['n_collisions'] = n_collisions
    php5.options['target_type'] = 'image'
    php5.options['target'] = target
    php5.options['hash_table_size'] = hash_table_size
    php5.run(CharGenerator(), output)
    assert output.count() == n_collisions
    for i in output:
        assert php5_common.php_hash(i, hash_table_size) == int(target)


def test_run_larger_collision_count():
    output = DummyOutput()
    n_collisions = 20
    hash_table_size = 2**32
    target = '42'
    php5.options['n_collisions'] = n_collisions
    php5.options['target_type'] = 'image'
    php5.options['target'] = target
    php5.options['hash_table_size'] = hash_table_size
    php5.run(CharGenerator(), output)
    assert output.count() == n_collisions
    for i in output:
        assert php5_common.php_hash(i, hash_table_size) == int(target)


def test_preimage():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 2**32
    preimage_target = 'hello world'
    php5.options['n_collisions'] = n_collisions
    php5.options['target_type'] = 'preimage'
    php5.options['target'] = preimage_target
    php5.options['hash_table_size'] = hash_table_size
    php5.run(CharGenerator(), output)
    target = php5_common.php_hash(preimage_target, hash_table_size)
    assert output.count() == n_collisions
    for i in output:
        assert php5_common.php_hash(i, hash_table_size) == target


def test_run_small_hash_table_size():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 100
    target = '42'
    php5.options['n_collisions'] = n_collisions
    php5.options['target_type'] = 'image'
    php5.options['target'] = target
    php5.options['hash_table_size'] = hash_table_size
    php5.run(CharGenerator(), output)
    assert output.count() == n_collisions
    for i in output:
        assert php5_common.php_hash(i, hash_table_size) == int(target)
