1

This is probably a relatively simple question, but I struggle to find an answer otherwise.

I am working on a small Python project, and I would like to do this in a test driven way. File operations in a defined folder in the User's home directory are quite essential to the programme, but I would like these to happen in a separate temporary folder for the tests.

Is there a way to set a variable in my app that is different if the app realises it's run as part of the testing environment? My current workarounds (def some_function(self, test=False) or to include lots of @patch decorators) are not very elegant...

I'm thinking of something along the lines of:

def return_home_folder():
    if testing:
        home = os.getcwd() + '/testrun'
    else:
        home = os.path.expanduser('~')
    returnvalue = home + '/appname/'
    return returnvalue
1
  • See stackoverflow.com/a/79527017/819417 to detect doctest, unittest, and probably other frameworks/libs, but note the accepted answer here that such is not good form. Commented Mar 22 at 16:07

2 Answers 2

1

IMHO it is not a good idea to have a function behave differently in test vs. production. The whole point of tests is to foretell how the program will behave in production, and changing the behaviour kinda defeats that.

(Unit Testing is different from a "dry run", but that's a separate issue.)

I'ld go for something like this:

def get_app_folder():
    return os.path.join(os.path.expanduser("~"), "appname")

def test_get_app_folder():
    assert get_app_folder().startswith(os.path.expanduser("~"))
    assert get_app_folder().endswith("appname")

The unit tests themselves aren't overly instructive, but they show how you can work around the need for a "testing mode" altogether.

Sign up to request clarification or add additional context in comments.

Comments

1

You could define your environment in an environment variable:

$ export MY_APP_ENVIRONMENT=test

Read it in a settings.py module:

import os

ENVIRONMENT = os.environ['MY_APP_ENVIRONMENT']

_base_dir_map = {
    'test': os.path.join(os.getcwd(), 'testrun'),
    'prod': os.path.expanduser('~'),
}

HOME_DIR = os.path.join(_base_dir_map[ENVIRONMENT], 'appname')

Then, everywhere (tests and app code), you would use settings.HOME_DIR:

import os
from my_app import settings

file_path = os.path.join(settings.HOME_DIR, 'filename')

...

Hope this works for you or gets you on a track to something that does.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.