2

I'm trying to set up pytest with my project, and the directory structure is shown below.

├── 
├── README.md
├── my_code
│   ├── __init__.py
│   ├── __main__.py
│   └── target_file.py
└── tests
│   ├── __init__.py
│   └── test_one.py

In my test_one.py I'm importing the target_file.py with

import sys
import os
sys.path.insert(0, "my_code")

if I run pytest from the command line in the root directory this works. However if I cd into a different directory, such as into tests I get an error saying the module my_code has no attribute bla bla bla. I assume this is because the way I am importing, it depends on where I actually am in the directory. So if I'm in the tests directory, then it will try to import from /root/tests/my_code, which doesn't exist. Is there a way to import target_file.py into test_one.py so that no matter where I am, I can go on the command line and run pytest, so that my tests will run? As it stands now, I have to go to the root directory so that the imports work correctly.

girbic
  • 301
  • 3
  • 11

1 Answers1

1

Add the full path of your project home directory to sys.path not only relative path. Under linux this start from / to the directory containing readme file

Omar
  • 11
  • 3
  • Is there a way to do this independently so that it will also work for others? B/c if someone else tries to run this and the path is just hard coded in, it obviously won't work – girbic May 20 '18 at 05:33
  • Put your libs in the python libs folder. Also you may add your project home to the python libs path. Both of these depend directly on the path. Otherwise, you may create your python main program in the project main directory and call any needed libs in the project with the relative path. – Omar May 20 '18 at 05:38
  • I'm sorry what do you mean by put your libs in the python libs folder? I'm not super familiar with python. – girbic May 20 '18 at 05:48
  • 1
    Append your home project directory to PYTHONPATH environment variable. – Omar May 20 '18 at 05:56
  • Please check for windows: https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7 – Omar May 20 '18 at 05:58