0

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.

bcsta
  • 1,963
  • 3
  • 22
  • 61
  • Try using an alias for your import: Like so: `import mysql.connector as MODULE_ALIAS`. PS: don't forget to replace `mysql.connector.connect` with `MODULE_ALIAS.connect` – Novus Edge Jan 30 '21 at 15:40
  • If `import mysql` fails, it means that `mysql-connector-python` is not installed. How should running `python -m pytest` help in this case? – hoefling Jan 31 '21 at 17:12
  • If "it works" because you have simply unpacked MySQL connector into the project root dir, this is surely not the right way of installing third-party packages. – hoefling Jan 31 '21 at 17:12
  • I assume you are not running this from a python virtual environment? If not, do you have multiple versions of python installed? – ENDEESA Feb 01 '21 at 07:34

2 Answers2

0

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

mango orange
  • 118
  • 9
-1

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.

bcsta
  • 1,963
  • 3
  • 22
  • 61
  • `python -m` only safeguards the version of the python module you are using and is considered best practice. It doesn't affect the command itself (`pytest tests/test.py`) – Tormod Haugene Oct 05 '21 at 10:44