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


def test_java7_hashmap_run():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 1024
    target_hash = 848473
    java7_hashmap.options['n_collisions'] = n_collisions
    java7_hashmap.options['hash_table_size'] = hash_table_size
    java7_hashmap.options['target_hash'] = target_hash
    java7_hashmap.run(output)
    assert len(output) == n_collisions
    for i in output:
        assert java7_hashmap.hash(i) % hash_table_size == target_hash % hash_table_size


def test_more_collisions():
    output = DummyOutput()
    n_collisions = 10000
    hash_table_size = 1024
    target_hash = 848473
    java7_hashmap.options['n_collisions'] = n_collisions
    java7_hashmap.options['hash_table_size'] = hash_table_size
    java7_hashmap.options['target_hash'] = target_hash
    java7_hashmap.run(output)
    assert len(output) == n_collisions
    for i in output:
        assert java7_hashmap.hash(i) % hash_table_size == target_hash % hash_table_size


def test_small_hash_table_size():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 128
    target_hash = 848473
    java7_hashmap.options['n_collisions'] = n_collisions
    java7_hashmap.options['hash_table_size'] = hash_table_size
    java7_hashmap.options['target_hash'] = target_hash
    java7_hashmap.run(output)
    assert len(output) == n_collisions
    for i in output:
        assert java7_hashmap.hash(i) % hash_table_size == target_hash % hash_table_size


def test_different_target_hash():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 1024
    target_hash = 542432
    java7_hashmap.options['n_collisions'] = n_collisions
    java7_hashmap.options['hash_table_size'] = hash_table_size
    java7_hashmap.options['target_hash'] = target_hash
    java7_hashmap.run(output)
    assert len(output) == n_collisions
    for i in output:
        assert java7_hashmap.hash(i) % hash_table_size == target_hash % hash_table_size


def test_invalid_target_hash():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 1024
    target_hash = 0xFFFFFFFFFF
    java7_hashmap.options['n_collisions'] = n_collisions
    java7_hashmap.options['hash_table_size'] = hash_table_size
    java7_hashmap.options['target_hash'] = target_hash
    with pytest.raises(ValueError):
        java7_hashmap.run(output)
