0

I set up my project in IntelliJ IDEA (or PyCharm) like this:

project_root
  + src
    + business
      - production_code.py (has a random class I want to test)
  + test
    + business
      - test_production_code.py (using unittest module)

I tried multiple solutions I found online, but unfortunately none of them allow me to run all of the tests inside test directory and its subdirectories, without adding __init__.py everywhere (I'd like to avoid that) or changing sources or changing the configured directory structure.

Note that using pytest actually allows me to find all the tests and run them, but then the imports fail. Looks like none of the classes/modules from src could be found from the test directory - I'm guessing because by default src is not added to the test path.

Also note that my tests run fine from the IDE, but I noticed that IntelliJ somehow seems to add the src directory to the path, so that's probably why it works.

milosmns
  • 3,595
  • 4
  • 36
  • 48
  • 1
    The `src` layout is being practiced when you plan to run the tests over the installed package instead of the source code in repository, to check whether the code works when installed. For that, the package must be installed - either via egglink ("dev mode") or a regular installation. The `src` dir has the purpose of blocking the imports from the source dir so the installed code is imported instead. Since you are obviously missing this - do you really need the `src` dir? – hoefling Aug 01 '19 at 10:28
  • That being said, you need to adjust the import paths for the test run since `src` blocks the import. You can e.g. place an empty `conftest.py` file in the `src` dir. See [this answer of mine](https://stackoverflow.com/a/50610630/2650249) for more details. – hoefling Aug 01 '19 at 10:30
  • @hoefling Well as you can see, I'm not super experienced with Python :) I don't like the idea of having the `test` directory inside of my main code, the reason is mainly to avoid confusion when importing stuff and reduce the number of items in the IDE auto-complete popup. If they're in the same root directory, theoretically I'd be able to import test functions/modules into my main sources. Is there another way to achieve what I want? – milosmns Aug 01 '19 at 12:34
  • 1
    If you are only interested in getting it to work with Pycharm, making `project_root/src` a source root in Pycharm's project settings should fix the import path. If the imports still fail, best is to provide a [mcve] so one can reproduce it locally. – hoefling Aug 01 '19 at 12:37
  • No no, I mentioned that from IDE it's working fine. From the command line it is not, so that was the problem I was looking to solve. I'll take a look at your comment about conftest.py, maybe that solves my issue. – milosmns Aug 01 '19 at 14:35

0 Answers0