I am getting an error Import "_frozen_importlib" could not be resolved

In summary, the conversation is about an error that occurs when running a command in Python. The error is related to a source code string containing null bytes. The conversation also includes warnings and a short summary of the error. Additionally, the conversation mentions importing certain modules and using deprecated functions. The conversation also includes a code snippet for a Python implementation of import.
  • #1
rgtr
92
8
TL;DR Summary
I am getting the error Import "_frozen_importlib" could not be resolved when using pytest and conda. Can someone please help?
Here is the error when I run python -m pytest


Code:
 ERROR collecting test session _______________________________________________________________________________
..\..\..\..\anaconda3\envs\flaskblog2\lib\importlib\__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
<frozen importlib._bootstrap>:1050: in _gcd_import
    ?
<frozen importlib._bootstrap>:1027: in _find_and_load
    ?
<frozen importlib._bootstrap>:992: in _find_and_load_unlocked
    ?
<frozen importlib._bootstrap>:241: in _call_with_frames_removed
    ?
<frozen importlib._bootstrap>:1050: in _gcd_import
    ?
<frozen importlib._bootstrap>:1027: in _find_and_load
    ?
<frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
    ?
<frozen importlib._bootstrap>:688: in _load_unlocked
    ?
<frozen importlib._bootstrap_external>:879: in exec_module
    ?
<frozen importlib._bootstrap_external>:1017: in get_code
    ?
<frozen importlib._bootstrap_external>:947: in source_to_code
    ?
<frozen importlib._bootstrap>:241: in _call_with_frames_removed
    ?
E   ValueError: source code string cannot contain null bytes
===================================================================================== warnings summary ======================================================================================
..\..\..\..\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:851
  C:\Users\nmyle\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:851: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
    warnings.warn(
 
..\..\..\..\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:872
  C:\Users\nmyle\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
    warnings.warn(FSADeprecationWarning(
 
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
================================================================================== short test summary info ==================================================================================
ERROR  - ValueError: source code string cannot contain null bytes
! Interrupted: 1 error during collection !
When I click on ..\..\..\..\anaconda3\envs\flaskblog2\lib\importlib\__init__.py:
from the pastebin above I get the file below.

Code:
"""A pure Python implementation of import."""
__all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']
 
# Bootstrap help #####################################################
 
# Until bootstrapping is complete, DO NOT import any modules that attempt
# to import importlib._bootstrap (directly or indirectly). Since this
# partially initialised package would be present in sys.modules, those
# modules would get an uninitialised copy of the source version, instead
# of a fully initialised version (either the frozen one or the one
# initialised below if the frozen one is not available).
import _imp  # Just the builtin component, NOT the full Python module
import sys
 
try:
    import _frozen_importlib as _bootstrap
except ImportError:
    from . import _bootstrap
    _bootstrap._setup(sys, _imp)
else:
    # importlib._bootstrap is the built-in import, ensure we don't create
    # a second copy of the module.
    _bootstrap.__name__ = 'importlib._bootstrap'
    _bootstrap.__package__ = 'importlib'
    try:
        _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py')
    except NameError:
        # __file__ is not guaranteed to be defined, e.g. if this code gets
        # frozen by a tool like cx_Freeze.
        pass
    sys.modules['importlib._bootstrap'] = _bootstrap
 
try:
    import _frozen_importlib_external as _bootstrap_external
except ImportError:
    from . import _bootstrap_external
    _bootstrap_external._set_bootstrap_module(_bootstrap)
    _bootstrap._bootstrap_external = _bootstrap_external
else:
    _bootstrap_external.__name__ = 'importlib._bootstrap_external'
    _bootstrap_external.__package__ = 'importlib'
    try:
        _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py')
    except NameError:
        # __file__ is not guaranteed to be defined, e.g. if this code gets
        # frozen by a tool like cx_Freeze.
        pass
    sys.modules['importlib._bootstrap_external'] = _bootstrap_external
 
# To simplify imports in test code
_pack_uint32 = _bootstrap_external._pack_uint32
_unpack_uint32 = _bootstrap_external._unpack_uint32
 
# Fully bootstrapped at this point, import whatever you like, circular
# dependencies and startup overhead minimisation permitting :)
 
import warnings
 
 
# Public API #########################################################
 
from ._bootstrap import __import__
 
 
def invalidate_caches():
    """Call the invalidate_caches() method on all meta path finders stored in
    sys.meta_path (where implemented)."""
    for finder in sys.meta_path:
        if hasattr(finder, 'invalidate_caches'):
            finder.invalidate_caches()
 
 
def find_loader(name, path=None):
    """Return the loader for the specified module.
 
    This is a backward-compatible wrapper around find_spec().
 
    This function is deprecated in favor of importlib.util.find_spec().
 
    """
    warnings.warn('Deprecated since Python 3.4 and slated for removal in '
                  'Python 3.12; use importlib.util.find_spec() instead',
                  DeprecationWarning, stacklevel=2)
    try:
        loader = sys.modules[name].__loader__
        if loader is None:
            raise ValueError('{}.__loader__ is None'.format(name))
        else:
            return loader
    except KeyError:
        pass
    except AttributeError:
        raise ValueError('{}.__loader__ is not set'.format(name)) from None
 
    spec = _bootstrap._find_spec(name, path)
    # We won't worry about malformed specs (missing attributes).
    if spec is None:
        return None
    if spec.loader is None:
        if spec.submodule_search_locations is None:
            raise ImportError('spec for {} missing loader'.format(name),
                              name=name)
        raise ImportError('namespace packages do not have loaders',
                          name=name)
    return spec.loader
 
 
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)
 
 
_RELOADING = {}
 
 
def reload(module):
    """Reload the module and return it.
 
    The module must have been successfully imported before.
 
    """
    try:
        name = module.__spec__.name
    except AttributeError:
        try:
            name = module.__name__
        except AttributeError:
            raise TypeError("reload() argument must be a module")
 
    if sys.modules.get(name) is not module:
        msg = "module {} not in sys.modules"
        raise ImportError(msg.format(name), name=name)
    if name in _RELOADING:
        return _RELOADING[name]
    _RELOADING[name] = module
    try:
        parent_name = name.rpartition('.')[0]
        if parent_name:
            try:
                parent = sys.modules[parent_name]
            except KeyError:
                msg = "parent {!r} not in sys.modules"
                raise ImportError(msg.format(parent_name),
                                  name=parent_name) from None
            else:
                pkgpath = parent.__path__
        else:
            pkgpath = None
        target = module
        spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
        if spec is None:
            raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
        _bootstrap._exec(spec, module)
        # The module may have replaced itself in sys.modules!
        return sys.modules[name]
    finally:
        try:
            del _RELOADING[name]
        except KeyError:
            pass
In the file in the pastebin above I am getting the error Import "_frozen_importlib" could not be resolved.

I tried googling this and just can't seem to solve it.
Do you think this could be an error with conda?

Thanks for the help.
 
Last edited:
Technology news on Phys.org
  • #2
rgtr said:
Here is the error.
Please put your code and transcripts directly in code blocks instead of linking to a pastebin. The pastebin linking destroys your code formatting, which with Python is a big problem.
 
  • #3
rgtr said:
Do you think this could be an error with conda?
No, I think you are not bootstrapping flask properly (or at all).

Take a look at e.g. https://testdriven.io/blog/flask-pytest/
 
  • #4
What do you mean by bootstrapping flask properly?

Here is the code I am using. Do I need to successfully login before running pytest?
I am running pytest by typing python -m pytest. I have a lot of commented out code because I want to test the simplest version of pytest.
app/tests/unit/test_models:
from app.models import User

def test_new_user():
    '''
    Given a User model
    When a new user is being logged in
    Check the User database columns
    '''
 
   # username  hashed_password  emai  confirmation_email  reset_email_password
    user = User('aiohrgihrtg', 'jotpjgjbgt','nojafa5998@royins.com', True, False)
    # Just for testing ?
    assert user.username == 'aiohrgihrtg'
    '''
    # check if the user exists in the other file by checking if email exists
    assert user.email == 'nojafa5998@royins.com'
    # check to make sure the hashed password doesn't contain plaintext.
    assert user.hashed_password!= 'jotpjgjbgt'
    # check if the email is registered
    assert user.confirmation_email == True
    '''
app/tests/functional/test_login.py:
from app.models import User

def test_new_user():
    '''
    Given a User model
    When a new user is being logged in
    Check the User database columns
    '''
 
   # username  hashed_password  emai  confirmation_email  reset_email_password
    user = User('aiohrgihrtg', 'jotpjgjbgt','nojafa5998@royins.com', True, False)
    # Just for testing ?
    assert user.username == 'aiohrgihrtg'
    '''
    # check if the user exists in the other file by checking if email exists
    assert user.email == 'nojafa5998@royins.com'
    # check to make sure the hashed password doesn't contain plaintext.
    assert user.hashed_password!= 'jotpjgjbgt'
    # check if the email is registered
    assert user.confirmation_email == True
    '''

app/tests/functional/test_login.py
from app import create_appdef test_login_page():
    """
    GIVEN a Flask application configured for testing
    WHEN the '/login'page requested (GET)
    THEN check that the response is valid
    """
    # what is 'flask_test.cfg'?
    flask_app = create_app('flask_test.cfg')
    # The with statemnt allows you to open and close files safely by making sure there is no errors
    # What is test_client?  test_client makes requests to the application without running a live server
    # Use the test_client to check the route which is a get request
    with flask_app.test_client() as test_client:
        response = test_client.post('/login')
        """
        In Python, the assert statement is used to continue the execute if the given condition evaluates to True.
        If the assert condition evaluates to False, then it raises the AssertionError exception with the specified error message.
        """
        # Why use a b string? What is response.data? Does it only work if I have a status code like 200?
        assert response.status_code == 405
       
        # checking username
        assert b'Flask User management Example' in response.data
        '''
        # checking email
        assert b' You need an an account' in response.data
        # checking hashed_password
        assert b'The password is plaintext' in response.data
        # checking confirmation_email
        assert b'The registeration email is False' in response.data
        '''
 
  • #5
I'm afraid there are too many unknowns here to effectively provide direct help, you are going to need to work this out yourself.

Try removing all your test files except one with a trivial test like assert 1=1. If that works you know that pytest is working.

Add a unit test like your User model test. If that works then good; if it doesn't then work out why: if your model uses SQL then obviously it will need some configuration of a test database to work.

Add a SIMPLE functional test like get /...

Add more complex functional test like your post /login which presumably expects some encoded data in the body which it checks against a user database which will need to be mocked in test.cfg.

Alternatively start again from scratch following one of the many flask+pytest app development tutorials out there.
 
  • #6
Here is my github https://github.com/NML240/flaskblog2/tree/master .
I accidentally called the side branch master I just have not had a chance to change it.
I also added an empty __init__.py file in my unit folder.
app/tests/functional/test_login.py::
# Here is the code I am trying.

assert b'this should come back true'

# I even tried this and got the same error

def test_number():

    assert b'this should come back true'
app/tests/unit/test_models::
# Here is the code I am trying.

assert 1 == 1

# I even tried this and got the same error

def test_number():

    assert 1 == 1
I am getting the error still when I type pytest -m python .

.
error:
_______________________________________________________________________________ ERROR collecting test session _______________________________________________________________________________

..\..\..\..\anaconda3\envs\flaskblog2\lib\importlib\__init__.py:126: in import_module

    return _bootstrap._gcd_import(name[level:], package, level)

<frozen importlib._bootstrap>:1050: in _gcd_import

    ?

<frozen importlib._bootstrap>:1027: in _find_and_load

    ?

<frozen importlib._bootstrap>:992: in _find_and_load_unlocked

    ?

<frozen importlib._bootstrap>:241: in _call_with_frames_removed

    ?

<frozen importlib._bootstrap>:1050: in _gcd_import

    ?

<frozen importlib._bootstrap>:1027: in _find_and_load

    ?

<frozen importlib._bootstrap>:1006: in _find_and_load_unlocked

    ?

<frozen importlib._bootstrap>:688: in _load_unlocked

    ?

<frozen importlib._bootstrap_external>:879: in exec_module

    ?

<frozen importlib._bootstrap_external>:1017: in get_code

    ?

<frozen importlib._bootstrap_external>:947: in source_to_code

    ?

<frozen importlib._bootstrap>:241: in _call_with_frames_removed

    ?

E   ValueError: source code string cannot contain null bytes

===================================================================================== warnings summary ======================================================================================

..\..\..\..\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:851

  C:\Users\nmyle\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:851: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".

    warnings.warn(..\..\..\..\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:872

  C:\Users\nmyle\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.

    warnings.warn(FSADeprecationWarning(-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

================================================================================== short test summary info ==================================================================================

ERROR  - ValueError: source code string cannot contain null bytes

! Interrupted: 1 error during collection !

=============================================================================== 2 warnings, 1 error in 0.66s ================================================================================

(flaskblog2) PS C:\Users\nmyle\OneDrive\Desktop\flask code\flaskblog2>

When I type conda list I get
conda list:
# Name                    Version                   Build  Channel
alembic                   1.4.3                      py_0    anaconda
atomicwrites              1.4.0                      py_0    anaconda
attrs                     20.2.0                     py_0    anaconda
bcrypt                    3.2.0           py310h2bbff1b_0
blinker                   1.4             py310haa95532_0
bootstrap                 4.4.1                         0    conda-forge
bzip2                     1.0.8                he774522_0    anaconda
ca-certificates           2020.10.14                    0    anaconda
certifi                   2021.5.30       py310haa95532_0
cffi                      1.15.0          py310h2bbff1b_1
click                     7.1.2                      py_0    anaconda
colorama                  0.4.4                      py_0    anaconda
dataclasses               0.8                pyh6d0b6a4_7
dnspython                 1.16.0          py310haa95532_0
email-validator           1.1.1                      py_0    anaconda
flask                     2.0.3              pyhd3eb1b0_0
flask-login               0.5.0              pyhd3eb1b0_0
flask-mail                0.9.1                      py_2    conda-forge
flask-migrate             3.1.0              pyhd8ed1ab_0    conda-forge
flask-sqlalchemy          2.5.1              pyhd3eb1b0_0
flask-wtf                 0.15.1             pyhd3eb1b0_0
greenlet                  1.1.1           py310hd77b12b_0
idna                      2.10                       py_0    anaconda
importlib-metadata        2.0.0                      py_1    anaconda
importlib_metadata        2.0.0                         1    anaconda
iniconfig                 1.1.1                      py_0    anaconda
itsdangerous              2.0.1              pyhd3eb1b0_0
jinja2                    3.0.3              pyhd3eb1b0_0
libffi                    3.4.2                h604cdb4_1
mako                      1.1.3                      py_0    anaconda
markupsafe                2.0.1           py310h2bbff1b_0
openssl                   1.1.1n               h2bbff1b_0
packaging                 20.4                       py_0    anaconda
pip                       21.2.4          py310haa95532_0
pluggy                    0.12.0                     py_0    anaconda
py                        1.9.0                      py_0    anaconda
pycparser                 2.20                       py_2    anaconda
pyparsing                 2.4.7                      py_0    anaconda
pytest                    7.1.1           py310haa95532_0
python                    3.10.4               hbb2ffb3_0
python-dateutil           2.8.1                      py_0    anaconda
python-editor             1.0.4                      py_0    anaconda
setuptools                61.2.0          py310haa95532_0
six                       1.15.0                     py_0    anaconda
sqlalchemy                1.4.32          py310h2bbff1b_0
sqlite                    3.38.2               h2bbff1b_0
tk                        8.6.11               h2bbff1b_0
tomli                     1.2.2              pyhd3eb1b0_0
tzdata                    2020b                h7b6447c_0    anaconda
vc                        14.1                 h0510ff6_4    anaconda
vs2015_runtime            14.16.27012          hf0eaf9b_3    anaconda
werkzeug                  2.0.3              pyhd3eb1b0_0
wheel                     0.35.1                     py_0    anaconda
wincertstore              0.2             py310haa95532_2
wtforms                   2.3.3                      py_0    anaconda
xz                        5.2.5                h62dcd97_0    anaconda
zipp                      3.3.1                      py_0    anaconda
zlib                      1.2.11           vc14h1cdd9ab_1  [vc14]  anaconda
 

FAQ: I am getting an error Import "_frozen_importlib" could not be resolved

What does the error "Import "_frozen_importlib" could not be resolved" mean?

The error means that the module or package named "_frozen_importlib" cannot be found or imported in the current code or environment.

Why am I getting this error?

There could be multiple reasons for this error, such as a misspelled module or package name, a missing or corrupted installation, or a compatibility issue with the current code or environment.

How can I fix this error?

You can try checking for any typos in the module or package name, ensuring that the module or package is installed correctly, or updating your code or environment to be compatible with the module or package.

Can this error be caused by a missing dependency?

Yes, if the module or package "_frozen_importlib" is dependent on another module or package that is not installed or cannot be found, it can result in this error.

Is there a way to prevent this error from occurring?

To prevent this error, make sure all necessary modules and packages are installed and correctly spelled, and regularly update your code and environment to ensure compatibility with any changes in the module or package.

Similar threads

Replies
5
Views
3K
Back
Top