When I include __init__.py
throughout my project, my unit tests can find everything that my main program can, so long as I do all imports relative to the project root. But this doesn't work for files that get loaded. I'm trying to write tests for code that includes imports of yaml files throughout the code.
This question is a follow-on, but distinct from this question that I recently asked, which was answered in the comments.
Here's my project structure:
Here's util1:
def add(x, y):
return x + y
if __name__ == "__main__":
pass
Here's util2:
from Scripts.Project.util1 import add
import yaml
def add_then_string(x, y):
z = add(x, y)
with open("file.yml") as f:
word = yaml.safe_load(f)['A']
return str(z) + word
if __name__ == "__main__":
print(add_then_string(2, 3))
And here's the test file:
import unittest
class TestProject(unittest.TestCase):
def test_dummy(self):
self.assertTrue(True)
def test_add(self):
from Scripts.Project.util1 import add
self.assertEqual(add(1,1), 2)
def test_add_then_string(self):
from Scripts.Project.util2 import add_then_string
self.assertEqual(add_then_string(1,1), "2hello")
if __name__ == "__main__":
unittest.main()
The problem is that util2
looks for file.yml
in a different place than the tests look for it.
Here's the error when I run the tests:
Error
Traceback (most recent call last):
File "C:\Users\Andrew_Cranedroesch\projects\dummy_test_project\UnitTests\test_project.py", line 14, in test_add_then_string
self.assertEqual(add_then_string(1,1), "2hello")
File "C:\Users\Andrew_Cranedroesch\projects\dummy_test_project\Scripts\Project\util2.py", line 7, in add_then_string
with open("file.yml") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'file.yml'
How do I make this work so that I can test a function that imports a file from a path?