Import error for relative import of module_name = 'testing_utils'
Author: teddius
Pull request: no

### System Info

Error message:



`
self = <module 'transformers' from '/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/__init__.py'>
module_name = 'testing_utils'

    def _get_module(self, module_name: str):
        try:
>           return importlib.import_module("." + module_name, self.__name__)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/utils/import_utils.py:1086:

name = '.testing_utils', package = 'transformers'

    def import_module(name, package=None):
        """Import a module.

        The 'package' argument is required when performing a relative import. It
        specifies the package to use as the anchor point from which to resolve the
        relative import to an absolute import.

        """
        level = 0
        if name.startswith('.'):
            if not package:
                msg = ("the 'package' argument is required to perform a relative "
                       "import for {!r}")
                raise TypeError(msg.format(name))
            for character in name:
                if character != '.':
                    break
                level += 1
>       return _bootstrap._gcd_import(name[level:], package, level)

../../miniconda3/envs/my_project/lib/python3.8/importlib/__init__.py:127:


name = 'transformers.testing_utils', package = 'transformers', level = 1

>   ???

<frozen importlib._bootstrap>:1014:


name = 'transformers.testing_utils'
import_ = <function _gcd_import at 0x7fc0abbb0430>

>   ???

<frozen importlib._bootstrap>:991:


name = 'transformers.testing_utils'
import_ = <function _gcd_import at 0x7fc0abbb0430>

>   ???

<frozen importlib._bootstrap>:975:


spec = ModuleSpec(name='transformers.testing_utils', loader=<_pytest.assertion.rewrite.AssertionRewritingHook object at 0x7fc0975af460>, origin='/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/testing_utils.py')

>   ???

<frozen importlib._bootstrap>:671:


self = <_pytest.assertion.rewrite.AssertionRewritingHook object at 0x7fc0975af460>
module = <module 'transformers.testing_utils' from '/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/testing_utils.py'>

    def exec_module(self, module: types.ModuleType) -> None:
        assert module.__spec__ is not None
        assert module.__spec__.origin is not None
        fn = Path(module.__spec__.origin)
        state = self.config.stash[assertstate_key]

        self._rewritten_names[module.__name__] = fn

        # The requested module looks like a test file, so rewrite it. This is
        # the most magical part of the process: load the source, rewrite the
        # asserts, and load the rewritten source. We also cache the rewritten
        # module code in a special pyc. We must be aware of the possibility of
        # concurrent pytest processes rewriting and loading pycs. To avoid
        # tricky race conditions, we maintain the following invariant: The
        # cached pyc is always a complete, valid pyc. Operations on it must be
        # atomic. POSIX's atomic rename comes in handy.
        write = not sys.dont_write_bytecode
        cache_dir = get_cache_dir(fn)
        if write:
            ok = try_makedirs(cache_dir)
            if not ok:
                write = False
                state.trace(f"read only directory: {cache_dir}")

        cache_name = fn.name[:-3] + PYC_TAIL
        pyc = cache_dir / cache_name
        # Notice that even if we're in a read-only directory, I'm going
        # to check for a cached pyc. This may not be optimal...
        co = _read_pyc(fn, pyc, state.trace)
        if co is None:
            state.trace(f"rewriting {fn!r}")
            source_stat, co = _rewrite_test(fn, self.config)
            if write:
                self._writing_pyc = True
                try:
                    _write_pyc(state, co, source_stat, pyc)
                finally:
                    self._writing_pyc = False
        else:
            state.trace(f"found cached rewritten pyc for {fn}")
>       exec(co, module.__dict__)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:168:


    import collections
    import contextlib
    import doctest
    import functools
    import inspect
    import logging
    import multiprocessing
    import os
    import re
    import shlex
    import shutil
    import subprocess
    import sys
    import tempfile
    import time
    import unittest
    from collections.abc import Mapping
    from io import StringIO
    from pathlib import Path
    from typing import Iterable, Iterator, List, Optional, Union
    from unittest import mock

    import huggingface_hub
    import requests
>   from _pytest.doctest import (
        Module,
        _get_checker,
        _get_continue_on_failure,
        _get_runner,
        _is_mocked,
        _patch_unwrap_mock_aware,
        get_optionflags,
        import_path,
    )
E   ImportError: cannot import name 'Module' from '_pytest.doctest' (/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/_pytest/doctest.py)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/testing_utils.py:39: ImportError

The above exception was the direct cause of the following exception:

args = ()
kwargs = {'end_date_str': '1990-02-13', 'is_valid': False, 'start_date_str': '1980-02-12'}

    def wrapper(*args, **kwargs):
>       with self as time_factory:

../../miniconda3/envs/my_project/lib/python3.8/site-packages/freezegun/api.py:800:


self = <freezegun.api._freeze_time object at 0x7fbf5285f8e0>

    def __enter__(self):
>       return self.start()

../../miniconda3/envs/my_project/lib/python3.8/site-packages/freezegun/api.py:633:


self = <freezegun.api._freeze_time object at 0x7fbf5285f8e0>

    def start(self):

        if self.auto_tick_seconds:
            freeze_factory = StepTickTimeFactory(self.time_to_freeze, self.auto_tick_seconds)
        elif self.tick:
            freeze_factory = TickingDateTimeFactory(self.time_to_freeze, real_datetime.now())
        else:
            freeze_factory = FrozenDateTimeFactory(self.time_to_freeze)

        is_already_started = len(freeze_factories) > 0
        freeze_factories.append(freeze_factory)
        tz_offsets.append(self.tz_offset)
        ignore_lists.append(self.ignore)
        tick_flags.append(self.tick)

        if is_already_started:
            return freeze_factory

        # Change the modules
        datetime.datetime = FakeDatetime
        datetime.date = FakeDate

        time.time = fake_time
        time.monotonic = fake_monotonic
        time.perf_counter = fake_perf_counter
        time.localtime = fake_localtime
        time.gmtime = fake_gmtime
        time.strftime = fake_strftime
        if uuid_generate_time_attr:
            setattr(uuid, uuid_generate_time_attr, None)
        uuid._UuidCreate = None
        uuid._last_timestamp = None

        copyreg.dispatch_table[real_datetime] = pickle_fake_datetime
        copyreg.dispatch_table[real_date] = pickle_fake_date

        # Change any place where the module had already been imported
        to_patch = [
            ('real_date', real_date, FakeDate),
            ('real_datetime', real_datetime, FakeDatetime),
            ('real_gmtime', real_gmtime, fake_gmtime),
            ('real_localtime', real_localtime, fake_localtime),
            ('real_monotonic', real_monotonic, fake_monotonic),
            ('real_perf_counter', real_perf_counter, fake_perf_counter),
            ('real_strftime', real_strftime, fake_strftime),
            ('real_time', real_time, fake_time),
        ]

        if _TIME_NS_PRESENT:
            time.time_ns = fake_time_ns
            to_patch.append(('real_time_ns', real_time_ns, fake_time_ns))

        if _MONOTONIC_NS_PRESENT:
            time.monotonic_ns = fake_monotonic_ns
            to_patch.append(('real_monotonic_ns', real_monotonic_ns, fake_monotonic_ns))

        if _PERF_COUNTER_NS_PRESENT:
            time.perf_counter_ns = fake_perf_counter_ns
            to_patch.append(('real_perf_counter_ns', real_perf_counter_ns, fake_perf_counter_ns))

        if real_clock is not None:
            # time.clock is deprecated and was removed in Python 3.8
            time.clock = fake_clock
            to_patch.append(('real_clock', real_clock, fake_clock))

        self.fake_names = tuple(fake.__name__ for real_name, real, fake in to_patch)
        self.reals = {id(fake): real for real_name, real, fake in to_patch}
        fakes = {id(real): fake for real_name, real, fake in to_patch}
        add_change = self.undo_changes.append

        # Save the current loaded modules
        self.modules_at_start = set(sys.modules.keys())

        with warnings.catch_warnings():
            warnings.filterwarnings('ignore')

            for mod_name, module in list(sys.modules.items()):
                if mod_name is None or module is None or mod_name == __name__:
                    continue
                elif mod_name.startswith(self.ignore) or mod_name.endswith('.six.moves'):
                    continue
                elif (not hasattr(module, "__name__") or module.__name__ in ('datetime', 'time')):
                    continue

>               module_attrs = _get_cached_module_attributes(module)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/freezegun/api.py:722:


module = <module 'transformers' from '/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/__init__.py'>

    def _get_cached_module_attributes(module):
        module_hash, cached_attrs = _GLOBAL_MODULES_CACHE.get(module.__name__, ('0', []))
        if _get_module_attributes_hash(module) == module_hash:
            return cached_attrs

        # cache miss: update the cache and return the refreshed value
>       _setup_module_cache(module)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/freezegun/api.py:129:


module = <module 'transformers' from '/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/__init__.py'>

    def _setup_module_cache(module):
        date_attrs = []
>       all_module_attributes = _get_module_attributes(module)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/freezegun/api.py:108:


module = <module 'transformers' from '/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/__init__.py'>

    def _get_module_attributes(module):
        result = []
        try:
            module_attributes = dir(module)
        except (ImportError, TypeError):
            return result
        for attribute_name in module_attributes:
            try:
>               attribute_value = getattr(module, attribute_name)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/freezegun/api.py:97:


self = <module 'transformers' from '/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/__init__.py'>
name = 'testing_utils'

    def __getattr__(self, name: str) -> Any:
        if name in self._objects:
            return self._objects[name]
        if name in self._modules:
>           value = self._get_module(name)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/utils/import_utils.py:1074:


self = <module 'transformers' from '/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/__init__.py'>
module_name = 'testing_utils'

    def _get_module(self, module_name: str):
        try:
            return importlib.import_module("." + module_name, self.__name__)
        except Exception as e:
>           raise RuntimeError(
                f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
                f" traceback):\n{e}"
            ) from e
E           RuntimeError: Failed to import transformers.testing_utils because of the following error (look up to see its traceback):
E           cannot import name 'Module' from '_pytest.doctest' (/home/user/miniconda3/envs/my_project/lib/python3.8/site-packages/_pytest/doctest.py)

../../miniconda3/envs/my_project/lib/python3.8/site-packages/transformers/utils/import_utils.py:1088: RuntimeError

`


### Who can help?

_No response_

### Information

- [X] The official example scripts
- [ ] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [ ] My own task or dataset (give details below)

### Reproduction

import transformers in a pytest

### Expected behavior

No import error


Comments:
Hi @teddius 

Could you show us the command or the python script you run that gives this error.

It's not super clear what
```
import transformers in a pytest
```
this means. 

Thank you in advance!


This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.