Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a python package in pytest using relative import

Tags:

python

pytest

my-proj
├── src
│   ├── main.py
└── test
│   ├── my_tests.py

I have the above directory structure for my python project. I have some unittests in the my_test.py and when I run them, I get the following error using following imports:

import os, sys
import json
from ..src import main
import unittest

running like this from my-proj/test/ directory: python my_tests.py

from ..src import main

ValueError: attempted relative import beyond top-level package

Apologies if this was answered but i tried a few things, even included __ main __.py in both directories (src and test) but didn't work. Any idea how I can get this to work? It is a FLASK application in python (main.py)

like image 448
Saffik Avatar asked Jun 04 '26 09:06

Saffik


1 Answers

You can also write the following in my_tests.py

import sys
sys.path.append("../src/")
import main
like image 182
Artyom Vancyan Avatar answered Jun 06 '26 23:06

Artyom Vancyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!