Pytest ImportError and ModuleNotFoundError when running test from a sub directory

1.3k Views Asked by At

I have the below project structure

- root
    - main.py
    - test/
        - __init__.py
        - conftest.py
        - test.py

In conftest.py I have some custom fixtures using mysql.connector. Therefore I am importing:

import mysql.connector

@pytest.fixture(scope='module')  # maintain connection for all tests
def cnx(database, username, password):
    cnx = mysql.connector.connect(database=database, user=username, password=password)
    yield cnx
    cnx.close()

when I run test.py from the terminal in the root directory with the below command:

pytest tests/test.py

I get the below error:

ImportError while loading conftest '/tests/conftest.py'.
tests/conftest.py:5: in <module>
    import mysql.connector
E   ModuleNotFoundError: No module named 'mysql'

Why is this happening? mysql is definitely installed.

2

There are 2 best solutions below

1
On

The command to run a test script with pytest is not pytest tests/test.py but

python -m pytest tests/test.py

as detailed in the official docs.

0
On

Have you tried running that python on CLI? then try if import mysql.connector is working? Another solution is you uninstall the current version of MySQL and try this package instead pip install mysql-connector-python-rf