import pathlib
import importlib


def get_test_directory_path(module_name: str, test_directory_name: str = 'tests') -> pathlib.Path:
    """ Returns the absolute path to the tests directory for a module, specified by name
    this works unter Pycharm Doctest, and pytest

    >>> test_directory = get_test_directory_path('lib_path', test_directory_name='tests')
    >>> assert test_directory.is_dir()
    """
    # ok for pytest:
    path_origin_directory = pathlib.Path(str(importlib.util.find_spec(module_name).origin)).parent  # type: ignore
    path_origin_resolved_directory = path_origin_directory.resolve()
    # for doctest under pycharm, we need to go probably some levels up:
    root_directory = pathlib.Path('/')
    while True:
        if (path_origin_resolved_directory / test_directory_name).is_dir():
            break
        if path_origin_resolved_directory == root_directory:
            raise FileNotFoundError('test directory "{test_directory_name}" not found'.format(test_directory_name=test_directory_name))
        path_origin_resolved_directory = path_origin_resolved_directory.parent
    path_to_test_directory = path_origin_resolved_directory / test_directory_name
    return path_to_test_directory