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

import pytest


def test_run_small_collision_output():
    output = DummyOutput()
    n_collisions = 2
    length = 7
    substring_length = 3
    target = '42'
    python2_32.options['n_collisions'] = n_collisions
    python2_32.options['length'] = length
    python2_32.options['substring_length'] = substring_length
    python2_32.options['target'] = target
    python2_32.options['target_type'] = 'image'
    python2_32.run(CharGenerator(), output)
    assert output.count() == n_collisions
    for i in output:
        assert python2_32.hash(i) == int(target)


def test_run_more_collision_output():
    output = DummyOutput()
    n_collisions = 10
    length = 8
    substring_length = 4
    target = '42'
    python2_32.options['n_collisions'] = n_collisions
    python2_32.options['length'] = length
    python2_32.options['substring_length'] = substring_length
    python2_32.options['target'] = target
    python2_32.options['target_type'] = 'image'
    python2_32.run(CharGenerator(), output)
    assert output.count() == n_collisions
    for i in output:
        assert python2_32.hash(i) == int(target)


def test_preimage():
    output = DummyOutput()
    n_collisions = 2
    length = 8
    substring_length = 4
    target = 'hello'
    python2_32.options['n_collisions'] = n_collisions
    python2_32.options['length'] = length
    python2_32.options['substring_length'] = substring_length
    python2_32.options['target'] = target
    python2_32.options['target_type'] = 'preimage'
    python2_32.run(CharGenerator(), output)
    assert output.count() == n_collisions
    for i in output:
        assert python2_32.hash(i) == python2_32.hash(target)


def test_equal_length_and_substring_length():
    output = DummyOutput()
    length = 3
    substring_length = 3
    target = '42'
    python2_32.options['length'] = length
    python2_32.options['substring_length'] = substring_length
    python2_32.options['target'] = target
    with pytest.raises(ValueError):
        python2_32.run(CharGenerator(), output)


def test_smaller_length_than_substring_length():
    output = DummyOutput()
    length = 2
    substring_length = 3
    target = '42'
    python2_32.options['length'] = length
    python2_32.options['substring_length'] = substring_length
    python2_32.options['target'] = target
    with pytest.raises(ValueError):
        python2_32.run(CharGenerator(), output)
