Reto Schmid
Reto Schmid

Reputation: 1

How can I access my task.py file inside my unittest.py?

I'm using jetbrains academy with pycharm and I'm trying to build a course with automatic checking with unittests in python. Here what I get when creating a default task of type "edu":

file structure

When I look at the default test_task.py (I didn't change a single line), the problem is already obvious:

import unittest

from task import summe


# todo: replace this with an actual test
class TestCase(unittest.TestCase):
    def test_add(self):
        self.assertEqual(summe(1, 2), 3, msg="adds 1 + 2 to equal 3")

Line 3 doesn't work because task is not visible from test_task.py. I can't/don't want to change the structure because of the course structure. What can I do? And why is there no documentation from Jetbrains?

Edit: And why would Jetbrains give us a template which is not working, am I missing something?

Thx for any help Reto

I already tried relative imports (from .. import task), obviously don't work. I also tried some path-meddling with sys.path.append('../task1'), no results. It's amazing something seemingly that simple is so complicated...

Upvotes: 0

Views: 73

Answers (3)

ThanujaM
ThanujaM

Reputation: 11

In Pycharm you can add content routes. Add the parent folder of task.py as a source.

https://www.jetbrains.com/help/pycharm/configuring-project-structure.html#create-content-root

Upvotes: 0

Reto Schmid
Reto Schmid

Reputation: 1

Nevermind...I just tried again, and it works like a charm. You just have to ignore the PyCharm IDE telling you it doesn't!

Upvotes: 0

Finn Luca Jensen
Finn Luca Jensen

Reputation: 5

I think you are not able to get files from higher directories. You can use test_task.py in task.py by:

import tests.test_task.py

But I think it's not possible to do it the other way around. What's possible tho, is using the sys and os module to create a directory where your task.py is stored and import it like this. This website explains it:

https://favtutor.com/blogs/import-from-parent-directory-python#:~:text=Conclusion,Python%20with%20many%20subdirectories%20simple.

I hope this helps!

Upvotes: 0

Related Questions