Opening file in a lcc test

14 views
Skip to first unread message

Akshay Maldhure

unread,
May 21, 2020, 12:32:08 AM5/21/20
to lemoncheesecake
I'm getting FileNotFoundError at the open() function call for a valid absolute path in a lcc test. So for debugging, I tried to use the exists() function provided by the os module in Python. And to my surprise, the first print() (which is outside the suite declaration) returns True (since it is a valid path/file indeed) whereas the second print() (which is inside the lcc suite/test) returns False - which implies that the path is rendered invalid inside that lcc suite/test.
Here's what my code looks like (imports have been removed).

CURRENT_PATH = os.getcwd()
TEST_FILE_DIR = os.path.join(CURRENT_PATH, 'resources')
TEST_FILE_PATH = os.path.join(TEST_FILE_DIR, 'my_file.txt'))
print(os.path.exists(TEST_FILE_PATH))


@lcc.suite("My suite")
class MySuite:

    @lcc.test("my test")
    def verify_something(self):
        print(os.path.exists(TEST_FILE_PATH))
        with open(TEST_FILE_PATH, 'r') as file:
            #  do something with the opened file

What could be the issue here?

Akshay Maldhure

unread,
May 21, 2020, 1:06:11 AM5/21/20
to lemoncheesecake
I saw some unrelated documentation at http://docs.lemoncheesecake.io/en/latest/generated.html?highlight=open(#generating-tests and I tried to fix the issue I'm facing by moving the open() call to the suite constructor. And it worked.

Not sure if that's the right thing to do though. Please suggest.

Nicolas Delon

unread,
May 21, 2020, 8:14:54 AM5/21/20
to lemoncheesecake
Hello,

I'm not sure about the behavior difference between the load-time and the run-time because "lcc run" does not change the current working directory.
Anyway, loading a file using the current working directory as the base directory is not safe, because "lcc run" can be run from anywhere inside your project directory and lookup the top project directory dynamically.
The best practice is to find the file path according your current module directory because it's independent from your current working directory, something like (to be adapted depending your module path of course):

PROJECT_DIR = os.path.join(os.path.dirname(__file__), "..")

And then build the actual file path based on that "PROJECT_DIR" variable.

Best regards.
Reply all
Reply to author
Forward
0 new messages