from typing import Optional


def run_validate_merge_block(spec, pow_chain, beacon_block, valid=True):
    """
    Run ``validate_merge_block``
    If ``valid == False``, run expecting ``AssertionError``
    """

    def get_pow_block(hash: spec.Bytes32) -> Optional[spec.PowBlock]:
        for block in pow_chain:
            if block.block_hash == hash:
                return block
        return None

    get_pow_block_backup = spec.get_pow_block

    # Guido authorized everyone to do this
    spec.get_pow_block = get_pow_block
    assertion_error_caught = False
    try:
        spec.validate_merge_block(beacon_block)
    except AssertionError:
        assertion_error_caught = True
    except Exception as e:
        spec.get_pow_block = get_pow_block_backup
        raise e
    spec.get_pow_block = get_pow_block_backup

    if valid:
        assert not assertion_error_caught
    else:
        assert assertion_error_caught