Search code examples
python-3.xpython-unittestpy2app

Unit Testing File with Space in the Name


I have a Python project where the main file has spaces in the name. I understand that this is not encouraged, but in this case, I think it's necessary. The file is being compiled into a stand alone executable using py2app--which uses the file name for the application name when building the executable (app name, menu references, etc.). This works fine because the base file is not imported anywhere within the project and py2app handles the spaces gracefully. Let's call the file Application Name.py.

In order to run unit tests against Application Name.py, however, I have to eliminate the spaces in order to import the file into unittest. I'm unable to use importlib or __import__ because the file is not constructed as a package, so both approaches fail. My workflow has been to refactor the file name to application_name.py, run the unit tests, and then refactor the name to Application Name.py before compiling it into Application Name.app.

So the options appear to be:

  1. Keep doing what I'm doing (workable, but not ideal),
  2. Create a wrapper called Application Name.py that imports application_name.py where the wrapper doesn't need to be unit tested (seems silly),
  3. Convert Application Name into a package so I can use importlib (seems like overkill), or
  4. Something else entirely.

Is there some way to gracefully handle file names with spaces in unit testing that I'm not seeing or should I just suck it up?


Solution

  • Seems like option 2 probably works best. Option 1 and 2 are your best bets (yes 3 is a bit overkill), and although 2 seems excessive, it does isolate your python logic from your py2app requirements - now Application Name.py is a "py2app wrapper file", and application_name.py contains your actual logic.

    This works better than Option 1 because separation of responsibilities is generally preferred. If you come up with other requirements for your application name, you'd want to have to deal with just the "py2app wrapper file", and not change anything related to actual logic.

    Your current workflow works too, but it does mean more manual renaming when you want to run unit tests - what if you want to automate the unit testing process?