Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

339
Views
Python ModuleNotFoundError al importar un módulo en conftest para el marco Pytest

La estructura de mi proyecto

 mt-kart | --> src/data_kart | | | -->apis | | | -->__init__.py | | | -->main.py --> tests | -->__init__.py | -->conftest.py | -->test_others.py

conftest.py tiene la siguiente línea.

from data_kart.main import fastapi_app

Cuando ejecute pytest desde la línea de comando desde la raíz del proyecto (mt-kart). Obtuve el siguiente error

ModuleNotFoundError No module named 'data_kart'

Cómo hacer que data_kart sea visible para conftest.py .

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Opción 1

Usar importaciones relativas:

 from ..src.data_kart.main import fastapi_app fastapi_app()

Tenga en cuenta que lo anterior requiere ejecutar conftest.py fuera del directorio del proyecto, así:

 python -m mt-kart.tests.conftest

opcion 2

Use lo siguiente en conftest.py ( ref ):

 import sys import os # getting the name of the directory where the this file is present. current = os.path.dirname(os.path.realpath(__file__)) # Getting the parent directory name where the current directory is present. parent = os.path.dirname(current) # adding the parent directory to the sys.path. sys.path.append(parent) # import the module from src.data_kart.main import fastapi_app # call the function fastapi_app()

Y si sucede que un módulo está fuera del directorio principal de tests , entonces puede obtener el directorio principal del directorio principal y agregarlo a sys.path . Por ejemplo:

 parentparent = os.path.dirname(parent) sys.path.append(parentparent)

Opción 3

Igual que la Opción 2, pero más corto.

 import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from src.data_kart.main import fastapi_app fastapi_app()

Opción 4

Las opciones 2 y 3 funcionarían para proyectos más pequeños, donde solo se necesita actualizar un par de archivos con el código anterior. Sin embargo, para proyectos más grandes, puede considerar incluir el directorio que contiene el directorio de su paquete en PYTHONPATH , como se describe aquí (Opción 3).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!