'Pytest throws 'attempted relative import beyond top-level package'

I know this question has been asked before but i cannot seem to find a solution.

This is my folder structure:

folder_name/

  __init__.py
  start.py

  src/
    __init__.py
    app.py
    api.py
   

  tests/
     __init__.py
     thetest.py

Start.py:

from src.app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

App.py:

def create_app():
    app = Flask(__name__)
    return app

Api.py: Here are all the endpoints

My server works fine.

However, when i introduce pytest into the equation, it fails.

I use this line: from ..start import app import pytest

and i get this error.

I have tried placing these lines in the start of thetest.py:

import os
import sys
sys.path.append(os.getcwd())

But the error remains.



Solution 1:[1]

This is what worked: Inside the thetest.py file:

from start import app

Solution 2:[2]

Perhaps you can try using unittest for testing:

cd "folder_name/../" # ! outside folder_name !
python3 -m unittest discover --top-level-directory=. --start-directory=./tests

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1584421
Solution 2 Ark-kun