I am having problems importing anything into my testing files that I intend to run with py.test.
I have a project structure as follows:
/ProjectName
|
|-- /Title
| |-- file1.py
| |-- file2.py
| |-- file3.py
| |-- __init__.py
|
|-- /test
| |-- test_file1.py
I have not been able to get any import statements working with pytest inside the test_file1.py
file, and so am currently just attempting to use a variable declared in file_1.py
and print it out when test_file1.py
is run.
file1.py contains:
file1_variable = "Hello"
test_file1.py contains:
import sys
import os
sys.path.append(os.path.abspath('../Title'))
import file1
def test_something():
assert file1.file1_variable == "Hello"
print(file1.file1_variable)
The import statement from my testing file is taken from https://stackoverflow.com/a/10272919/5477580 which works by editing the PYTHONPATH variable. This allows me to run the test_file1.py
script and successfully execute the print
statement.
However, attempting to run py.test
from the /ProjectName
directory gives me an error saying ImportError: No module named 'file1'
Is there some way in which I can structure things better so that pytest will be possible? Do I need to add something to my __init__.py
file?
The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .
Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.
So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.
A module can be imported by another program to make use of its functionality. This is how you can use the Python standard library as well. Simply put, a module is a file consisting of Python code. It can define functions, classes, and variables, and can also include runnable code.
No you don't need to add anything to __init__.py
. This file tells python to treat the parent directory as module which can be imported as described here.
Just add it to your Title directory and import it like
from ..Tiltle.file import file1_variable
here we are moving 1 hierarchy above in the directory just like cd ..
Note ..
is for reaching the Title package from test directory. If you need to run your file from ProjectName directory you will have to do
from Tiltle.file import file1_variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With