PATH issue with pytest 'ImportError: No module named YadaYadaYada'












145















I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so:



repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py


run py.test while in the repo directory, everything behaves as you would expect



but when I try that same thing on either linux or windows (both have pytest 2.2.3 on them) it barks whenever it hits its first import of something from my application path. Say for instance from app import some_def_in_app



Do I need to be editing my PATH to run py.test on these systems? Has Anyone experienced this?










share|improve this question




















  • 1





    Here is the way to fix it with setuptools.

    – ederag
    Oct 14 '16 at 21:27













  • Please check @hoefling answer and consider changing your accepted one, if SO allows after this long: much better!

    – Davide
    Sep 20 '18 at 21:42






  • 1





    Great question title

    – bozdoz
    Jan 24 at 18:01
















145















I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so:



repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py


run py.test while in the repo directory, everything behaves as you would expect



but when I try that same thing on either linux or windows (both have pytest 2.2.3 on them) it barks whenever it hits its first import of something from my application path. Say for instance from app import some_def_in_app



Do I need to be editing my PATH to run py.test on these systems? Has Anyone experienced this?










share|improve this question




















  • 1





    Here is the way to fix it with setuptools.

    – ederag
    Oct 14 '16 at 21:27













  • Please check @hoefling answer and consider changing your accepted one, if SO allows after this long: much better!

    – Davide
    Sep 20 '18 at 21:42






  • 1





    Great question title

    – bozdoz
    Jan 24 at 18:01














145












145








145


37






I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so:



repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py


run py.test while in the repo directory, everything behaves as you would expect



but when I try that same thing on either linux or windows (both have pytest 2.2.3 on them) it barks whenever it hits its first import of something from my application path. Say for instance from app import some_def_in_app



Do I need to be editing my PATH to run py.test on these systems? Has Anyone experienced this?










share|improve this question
















I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so:



repo/
repo/app.py
repo/settings.py
repo/models.py
repo/tests/
repo/tests/test_app.py


run py.test while in the repo directory, everything behaves as you would expect



but when I try that same thing on either linux or windows (both have pytest 2.2.3 on them) it barks whenever it hits its first import of something from my application path. Say for instance from app import some_def_in_app



Do I need to be editing my PATH to run py.test on these systems? Has Anyone experienced this?







python unit-testing pytest






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 2 '18 at 10:54









IanS

8,61732864




8,61732864










asked Apr 20 '12 at 21:32









MattoToddMattoTodd

5,322104771




5,322104771








  • 1





    Here is the way to fix it with setuptools.

    – ederag
    Oct 14 '16 at 21:27













  • Please check @hoefling answer and consider changing your accepted one, if SO allows after this long: much better!

    – Davide
    Sep 20 '18 at 21:42






  • 1





    Great question title

    – bozdoz
    Jan 24 at 18:01














  • 1





    Here is the way to fix it with setuptools.

    – ederag
    Oct 14 '16 at 21:27













  • Please check @hoefling answer and consider changing your accepted one, if SO allows after this long: much better!

    – Davide
    Sep 20 '18 at 21:42






  • 1





    Great question title

    – bozdoz
    Jan 24 at 18:01








1




1





Here is the way to fix it with setuptools.

– ederag
Oct 14 '16 at 21:27







Here is the way to fix it with setuptools.

– ederag
Oct 14 '16 at 21:27















Please check @hoefling answer and consider changing your accepted one, if SO allows after this long: much better!

– Davide
Sep 20 '18 at 21:42





Please check @hoefling answer and consider changing your accepted one, if SO allows after this long: much better!

– Davide
Sep 20 '18 at 21:42




1




1





Great question title

– bozdoz
Jan 24 at 18:01





Great question title

– bozdoz
Jan 24 at 18:01












11 Answers
11






active

oldest

votes


















69














Yes, the source folder is not in Python's path if you cd to the tests directory.



You have 2 choices:





  1. Add the path manually to the test files, something like this:



    import sys, os
    myPath = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, myPath + '/../')


  2. Run the tests with the env var PYTHONPATH=../.







share|improve this answer





















  • 8





    when am i cding to a directory? i am running py.test from my root. unless I am mistaken and you mean as pytest walks through my folders

    – MattoTodd
    Apr 20 '12 at 21:46











  • if it was a cd issue, wouldn't i hit it on mac as well?

    – MattoTodd
    Apr 20 '12 at 21:46











  • Oh, I misread and thought it doesn't work from the tests directory. still the trick in suggestion 1 would work. I only use Linux so I can't explain the behavior on other OSes.

    – Not_a_Golfer
    Apr 20 '12 at 21:50











  • do you have an import like that on all your test.py files?

    – MattoTodd
    Apr 20 '12 at 21:50






  • 4





    yes, but my directory structure is usually slightly different - I usually keep /src and /test under the root directory.

    – Not_a_Golfer
    Apr 20 '12 at 21:51



















176














I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):



python -m pytest tests/


It works because Python adds the current directory in the PYTHONPATH for you.






share|improve this answer



















  • 2





    That's a pretty neat workaround, e.g. for testing scripts and modules which are not packages/installable!

    – Christoph
    May 30 '16 at 8:41






  • 1





    It requires to rewrite relative imports to absolute ones, if you have the code for running the application not on the level, where you execute the command from. For example: project/test/all-my-tests and project/src/app.py and because of that change, one needs to call the app.py indirectly using a __main__.py file in project/src, so that one can use the call python -m src. Pretty messy stuff as far as I can tell.

    – Zelphir
    Sep 26 '16 at 15:44






  • 2





    @Zelphir: Using absolute imports is a recommended practice. Habnabit's has a good article about packaging best practices: blog.habnab.it/blog/2013/07/21/python-packages-and-you, and PEP8 says that "implicit relative imports should never be used and have been removed in Python 3." See: python.org/dev/peps/pep-0008.

    – Apteryx
    Nov 4 '16 at 20:23













  • @Apteryx You mean "project-absolute" right? Because things like /home/user/dev/projectxyz/src ... would be really bad and not run on other machines in most cases. I think what I meant is, that I have to always write the whole project root to module path even if a module is in the same folder as the file run. I didn't know that this is considered best practice, so that's a useful bit of information, thanks. I agree with most of pep8, although it is still not perfect.

    – Zelphir
    Nov 6 '16 at 19:44






  • 2





    I have added __init__.py in tests, that solved the problem. Now I can use pytest

    – Kiran Kumar Kotari
    Dec 26 '18 at 6:08



















91














I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.






share|improve this answer





















  • 60





    Note that this is NOT recommended by py.test: avoid “__init__.py” files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not. SRC: pytest.org/latest/goodpractises.html

    – K.-Michael Aye
    May 30 '14 at 21:52








  • 18





    I came here with the same question and found removing __init__.py from my tests directory solved it for me.

    – 101
    Oct 13 '15 at 0:24








  • 2





    @K.-MichaelAye How are you supposed to import modules in your tests, if the tests directory is not a package??

    – mafrosis
    Nov 3 '15 at 15:11






  • 3





    Adding an __init__.py in sub-directories of test/ makes absolute import work for running specific tests in that sub-directory against to-be installed modules. Thanks.

    – Bryce Guinta
    Sep 9 '16 at 22:01






  • 5





    there you go: doc.pytest.org/en/latest/goodpractices.html really easy to find with google.

    – K.-Michael Aye
    Jan 12 '17 at 0:56



















36















conftest solution



The least invasive solution is adding an empty file named conftest.py in the repo/ directory:



$ touch repo/conftest.py


That's it. No need to write custom code for mangling the sys.path or remember to drag PYTHONPATH along, or placing __init__.py into dirs where it doesn't belong.



The project directory afterwards:



repo
├── conftest.py
├── app.py
├── settings.py
├── models.py
└── tests
└── test_app.py


Explanation



pytest looks for the conftest modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest adds the parent directory of the conftest.py to the sys.path.



Other project structures



If you have other project structure, place the conftest.py in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py), for example:



repo
├── conftest.py
├── spam
│ ├── __init__.py
│ ├── bacon.py
│ └── egg.py
├── eggs
│ ├── __init__.py
│ └── sausage.py
└── tests
├── test_bacon.py
└── test_egg.py


Same approach with the src layout: place conftest.py in the src dir:



repo
├── src
│ ├── conftest.py
│ ├── spam
│ │ ├── __init__.py
│ │ ├── bacon.py
│ │ └── egg.py
│ └── eggs
│ ├── __init__.py
│ └── sausage.py
└── tests
├── test_bacon.py
└── test_egg.py


Where to go from here



Of course, conftest modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest framework and the customization of your test suite happen. pytest has a lot of information on conftest modules scattered throughout their docs; start with conftest.py: local per-directory plugins



Also, SO has an excellent question on conftest modules: In py.test, what is the use of conftest.py files?






share|improve this answer





















  • 3





    This really ought to be the accepted answer, all the others are clunky workarounds.

    – Davide
    Sep 20 '18 at 21:40











  • @Davide thanks, glad the recipe was worth sharing!

    – hoefling
    Sep 26 '18 at 16:52






  • 1





    Thanks a million, this fixed tests inside VS Code!

    – Daniel McLean
    Oct 25 '18 at 14:40











  • This does not work, simple as that. Try putting a file at the root directory, and then importing that from a test. Setting PYTHONPATH to root works fine, this hack does not help at all.

    – aaa90210
    Jan 15 at 21:55











  • @aaa90210 although I can't reproduce your issue (importing from a conftest in a root dir works on any level), you should never import from conftest files as it's a reserved name for pytest and it's strongly advised not to do so. By doing that, you plant seeds for future errors. Create another module named utils.py and place the code for reusing in tests there.

    – hoefling
    Jan 15 at 22:09



















35














You can run with PYTHONPATH in project root



PYTHONPATH=. py.test


Or use pip install as editable import



pip install -e .   # install package using setup.py in editable mode





share|improve this answer



















  • 2





    That didn't work for me with a test directory not in src directory structure and calling from the directory containing both test and src directory.

    – Zelphir
    Mar 13 '16 at 22:53



















24














Run pytest itself as a module with:
python -m pytest tests






share|improve this answer



















  • 4





    This is the best solution. Thanks!

    – blakev
    Apr 23 '18 at 16:52






  • 1





    This seems to be a working solution, but can anyone explain WHY? I'd rather fix the underlying cause than just use python -m pytest without any explanation other than "because it works"

    – Janne Enberg
    Aug 23 '18 at 8:30






  • 2





    This happens when project hierarchy is for example: package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute than relative to the execution location.

    – Stefano Messina
    Aug 23 '18 at 11:55













  • This solution helped me, thanks! The cause of this was because of the conflict in Python version. pytest test works for earlier python version. In my situation, my python version is 3.7.1, python -m pytest tests works but not pytest tests.

    – Ruxi Zhang
    Jan 4 at 19:16



















18














I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.



https://github.com/jeffmacdonald/pytest_test



Specifically: You have to tell py.test and tox where to find the modules you are including.



With py.test you can do this:



PYTHONPATH=. py.test


And with tox, add this to your tox.ini:



[testenv]
deps= -r{toxinidir}/requirements.txt
commands=py.test
setenv =
PYTHONPATH = {toxinidir}





share|improve this answer





















  • 1





    Could you give a short explanation for the project you linked?

    – JF Meier
    Jul 15 '16 at 14:06






  • 1





    Maybe its just me, but the README on the project is pretty detailed, and my comment on stackoverflow says why I created the repo.

    – Jeff MacDonald
    Jul 15 '16 at 14:10






  • 4





    While it is not strictly necessary, it is a usual policy to have the main content of an answer in the answer itself because it ensures that the answer is understandable in x years from now when the linked resource may be long gone.

    – JF Meier
    Jul 15 '16 at 14:13











  • Fair point. I'll update it.

    – Jeff MacDonald
    Jul 15 '16 at 14:22











  • Thank you (FYI: I did not vote you down).

    – JF Meier
    Jul 15 '16 at 14:28



















6














I started getting weird ConftestImportFailure: ImportError('No module named ... errors when I had accidentally added __init__.py file to my src directory (which was not supposed to be a Python package, just a container of all source).






share|improve this answer

































    2














    I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.



    'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.






    share|improve this answer

































      1














      For me the problem was tests.py generated by Django along with tests directory. Removing tests.py solved the problem.






      share|improve this answer































        1














        I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.



        from repo.app import *


        However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.



        from app import *


        Here's an example of what I had to do with one of my projects:



        Here’s my project structure:



        microbit/
        microbit/activity_indicator/activity_indicator.py
        microbit/tests/test_activity_indicator.py


        To be able to access activity_indicator.py from test_activity_indicator.py I needed to:




        • start test_activity_indicatory.py with the correct relative import:


            from microbit.activity_indicator.activity_indicator import *



        • put __init__.py files throughout the project structure:


            microbit/
        microbit/__init__.py
        microbit/activity_indicator/__init__.py
        microbit/activity_indicator/activity_indicator.py
        microbit/tests/__init__.py
        microbit/tests/test_activity_indicator.py





        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10253826%2fpath-issue-with-pytest-importerror-no-module-named-yadayadayada%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          11 Answers
          11






          active

          oldest

          votes








          11 Answers
          11






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          69














          Yes, the source folder is not in Python's path if you cd to the tests directory.



          You have 2 choices:





          1. Add the path manually to the test files, something like this:



            import sys, os
            myPath = os.path.dirname(os.path.abspath(__file__))
            sys.path.insert(0, myPath + '/../')


          2. Run the tests with the env var PYTHONPATH=../.







          share|improve this answer





















          • 8





            when am i cding to a directory? i am running py.test from my root. unless I am mistaken and you mean as pytest walks through my folders

            – MattoTodd
            Apr 20 '12 at 21:46











          • if it was a cd issue, wouldn't i hit it on mac as well?

            – MattoTodd
            Apr 20 '12 at 21:46











          • Oh, I misread and thought it doesn't work from the tests directory. still the trick in suggestion 1 would work. I only use Linux so I can't explain the behavior on other OSes.

            – Not_a_Golfer
            Apr 20 '12 at 21:50











          • do you have an import like that on all your test.py files?

            – MattoTodd
            Apr 20 '12 at 21:50






          • 4





            yes, but my directory structure is usually slightly different - I usually keep /src and /test under the root directory.

            – Not_a_Golfer
            Apr 20 '12 at 21:51
















          69














          Yes, the source folder is not in Python's path if you cd to the tests directory.



          You have 2 choices:





          1. Add the path manually to the test files, something like this:



            import sys, os
            myPath = os.path.dirname(os.path.abspath(__file__))
            sys.path.insert(0, myPath + '/../')


          2. Run the tests with the env var PYTHONPATH=../.







          share|improve this answer





















          • 8





            when am i cding to a directory? i am running py.test from my root. unless I am mistaken and you mean as pytest walks through my folders

            – MattoTodd
            Apr 20 '12 at 21:46











          • if it was a cd issue, wouldn't i hit it on mac as well?

            – MattoTodd
            Apr 20 '12 at 21:46











          • Oh, I misread and thought it doesn't work from the tests directory. still the trick in suggestion 1 would work. I only use Linux so I can't explain the behavior on other OSes.

            – Not_a_Golfer
            Apr 20 '12 at 21:50











          • do you have an import like that on all your test.py files?

            – MattoTodd
            Apr 20 '12 at 21:50






          • 4





            yes, but my directory structure is usually slightly different - I usually keep /src and /test under the root directory.

            – Not_a_Golfer
            Apr 20 '12 at 21:51














          69












          69








          69







          Yes, the source folder is not in Python's path if you cd to the tests directory.



          You have 2 choices:





          1. Add the path manually to the test files, something like this:



            import sys, os
            myPath = os.path.dirname(os.path.abspath(__file__))
            sys.path.insert(0, myPath + '/../')


          2. Run the tests with the env var PYTHONPATH=../.







          share|improve this answer















          Yes, the source folder is not in Python's path if you cd to the tests directory.



          You have 2 choices:





          1. Add the path manually to the test files, something like this:



            import sys, os
            myPath = os.path.dirname(os.path.abspath(__file__))
            sys.path.insert(0, myPath + '/../')


          2. Run the tests with the env var PYTHONPATH=../.








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 18 '18 at 13:44









          Lii

          7,20344162




          7,20344162










          answered Apr 20 '12 at 21:39









          Not_a_GolferNot_a_Golfer

          30.2k28664




          30.2k28664








          • 8





            when am i cding to a directory? i am running py.test from my root. unless I am mistaken and you mean as pytest walks through my folders

            – MattoTodd
            Apr 20 '12 at 21:46











          • if it was a cd issue, wouldn't i hit it on mac as well?

            – MattoTodd
            Apr 20 '12 at 21:46











          • Oh, I misread and thought it doesn't work from the tests directory. still the trick in suggestion 1 would work. I only use Linux so I can't explain the behavior on other OSes.

            – Not_a_Golfer
            Apr 20 '12 at 21:50











          • do you have an import like that on all your test.py files?

            – MattoTodd
            Apr 20 '12 at 21:50






          • 4





            yes, but my directory structure is usually slightly different - I usually keep /src and /test under the root directory.

            – Not_a_Golfer
            Apr 20 '12 at 21:51














          • 8





            when am i cding to a directory? i am running py.test from my root. unless I am mistaken and you mean as pytest walks through my folders

            – MattoTodd
            Apr 20 '12 at 21:46











          • if it was a cd issue, wouldn't i hit it on mac as well?

            – MattoTodd
            Apr 20 '12 at 21:46











          • Oh, I misread and thought it doesn't work from the tests directory. still the trick in suggestion 1 would work. I only use Linux so I can't explain the behavior on other OSes.

            – Not_a_Golfer
            Apr 20 '12 at 21:50











          • do you have an import like that on all your test.py files?

            – MattoTodd
            Apr 20 '12 at 21:50






          • 4





            yes, but my directory structure is usually slightly different - I usually keep /src and /test under the root directory.

            – Not_a_Golfer
            Apr 20 '12 at 21:51








          8




          8





          when am i cding to a directory? i am running py.test from my root. unless I am mistaken and you mean as pytest walks through my folders

          – MattoTodd
          Apr 20 '12 at 21:46





          when am i cding to a directory? i am running py.test from my root. unless I am mistaken and you mean as pytest walks through my folders

          – MattoTodd
          Apr 20 '12 at 21:46













          if it was a cd issue, wouldn't i hit it on mac as well?

          – MattoTodd
          Apr 20 '12 at 21:46





          if it was a cd issue, wouldn't i hit it on mac as well?

          – MattoTodd
          Apr 20 '12 at 21:46













          Oh, I misread and thought it doesn't work from the tests directory. still the trick in suggestion 1 would work. I only use Linux so I can't explain the behavior on other OSes.

          – Not_a_Golfer
          Apr 20 '12 at 21:50





          Oh, I misread and thought it doesn't work from the tests directory. still the trick in suggestion 1 would work. I only use Linux so I can't explain the behavior on other OSes.

          – Not_a_Golfer
          Apr 20 '12 at 21:50













          do you have an import like that on all your test.py files?

          – MattoTodd
          Apr 20 '12 at 21:50





          do you have an import like that on all your test.py files?

          – MattoTodd
          Apr 20 '12 at 21:50




          4




          4





          yes, but my directory structure is usually slightly different - I usually keep /src and /test under the root directory.

          – Not_a_Golfer
          Apr 20 '12 at 21:51





          yes, but my directory structure is usually slightly different - I usually keep /src and /test under the root directory.

          – Not_a_Golfer
          Apr 20 '12 at 21:51













          176














          I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):



          python -m pytest tests/


          It works because Python adds the current directory in the PYTHONPATH for you.






          share|improve this answer



















          • 2





            That's a pretty neat workaround, e.g. for testing scripts and modules which are not packages/installable!

            – Christoph
            May 30 '16 at 8:41






          • 1





            It requires to rewrite relative imports to absolute ones, if you have the code for running the application not on the level, where you execute the command from. For example: project/test/all-my-tests and project/src/app.py and because of that change, one needs to call the app.py indirectly using a __main__.py file in project/src, so that one can use the call python -m src. Pretty messy stuff as far as I can tell.

            – Zelphir
            Sep 26 '16 at 15:44






          • 2





            @Zelphir: Using absolute imports is a recommended practice. Habnabit's has a good article about packaging best practices: blog.habnab.it/blog/2013/07/21/python-packages-and-you, and PEP8 says that "implicit relative imports should never be used and have been removed in Python 3." See: python.org/dev/peps/pep-0008.

            – Apteryx
            Nov 4 '16 at 20:23













          • @Apteryx You mean "project-absolute" right? Because things like /home/user/dev/projectxyz/src ... would be really bad and not run on other machines in most cases. I think what I meant is, that I have to always write the whole project root to module path even if a module is in the same folder as the file run. I didn't know that this is considered best practice, so that's a useful bit of information, thanks. I agree with most of pep8, although it is still not perfect.

            – Zelphir
            Nov 6 '16 at 19:44






          • 2





            I have added __init__.py in tests, that solved the problem. Now I can use pytest

            – Kiran Kumar Kotari
            Dec 26 '18 at 6:08
















          176














          I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):



          python -m pytest tests/


          It works because Python adds the current directory in the PYTHONPATH for you.






          share|improve this answer



















          • 2





            That's a pretty neat workaround, e.g. for testing scripts and modules which are not packages/installable!

            – Christoph
            May 30 '16 at 8:41






          • 1





            It requires to rewrite relative imports to absolute ones, if you have the code for running the application not on the level, where you execute the command from. For example: project/test/all-my-tests and project/src/app.py and because of that change, one needs to call the app.py indirectly using a __main__.py file in project/src, so that one can use the call python -m src. Pretty messy stuff as far as I can tell.

            – Zelphir
            Sep 26 '16 at 15:44






          • 2





            @Zelphir: Using absolute imports is a recommended practice. Habnabit's has a good article about packaging best practices: blog.habnab.it/blog/2013/07/21/python-packages-and-you, and PEP8 says that "implicit relative imports should never be used and have been removed in Python 3." See: python.org/dev/peps/pep-0008.

            – Apteryx
            Nov 4 '16 at 20:23













          • @Apteryx You mean "project-absolute" right? Because things like /home/user/dev/projectxyz/src ... would be really bad and not run on other machines in most cases. I think what I meant is, that I have to always write the whole project root to module path even if a module is in the same folder as the file run. I didn't know that this is considered best practice, so that's a useful bit of information, thanks. I agree with most of pep8, although it is still not perfect.

            – Zelphir
            Nov 6 '16 at 19:44






          • 2





            I have added __init__.py in tests, that solved the problem. Now I can use pytest

            – Kiran Kumar Kotari
            Dec 26 '18 at 6:08














          176












          176








          176







          I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):



          python -m pytest tests/


          It works because Python adds the current directory in the PYTHONPATH for you.






          share|improve this answer













          I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):



          python -m pytest tests/


          It works because Python adds the current directory in the PYTHONPATH for you.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 7 '15 at 18:21









          ApteryxApteryx

          2,32721013




          2,32721013








          • 2





            That's a pretty neat workaround, e.g. for testing scripts and modules which are not packages/installable!

            – Christoph
            May 30 '16 at 8:41






          • 1





            It requires to rewrite relative imports to absolute ones, if you have the code for running the application not on the level, where you execute the command from. For example: project/test/all-my-tests and project/src/app.py and because of that change, one needs to call the app.py indirectly using a __main__.py file in project/src, so that one can use the call python -m src. Pretty messy stuff as far as I can tell.

            – Zelphir
            Sep 26 '16 at 15:44






          • 2





            @Zelphir: Using absolute imports is a recommended practice. Habnabit's has a good article about packaging best practices: blog.habnab.it/blog/2013/07/21/python-packages-and-you, and PEP8 says that "implicit relative imports should never be used and have been removed in Python 3." See: python.org/dev/peps/pep-0008.

            – Apteryx
            Nov 4 '16 at 20:23













          • @Apteryx You mean "project-absolute" right? Because things like /home/user/dev/projectxyz/src ... would be really bad and not run on other machines in most cases. I think what I meant is, that I have to always write the whole project root to module path even if a module is in the same folder as the file run. I didn't know that this is considered best practice, so that's a useful bit of information, thanks. I agree with most of pep8, although it is still not perfect.

            – Zelphir
            Nov 6 '16 at 19:44






          • 2





            I have added __init__.py in tests, that solved the problem. Now I can use pytest

            – Kiran Kumar Kotari
            Dec 26 '18 at 6:08














          • 2





            That's a pretty neat workaround, e.g. for testing scripts and modules which are not packages/installable!

            – Christoph
            May 30 '16 at 8:41






          • 1





            It requires to rewrite relative imports to absolute ones, if you have the code for running the application not on the level, where you execute the command from. For example: project/test/all-my-tests and project/src/app.py and because of that change, one needs to call the app.py indirectly using a __main__.py file in project/src, so that one can use the call python -m src. Pretty messy stuff as far as I can tell.

            – Zelphir
            Sep 26 '16 at 15:44






          • 2





            @Zelphir: Using absolute imports is a recommended practice. Habnabit's has a good article about packaging best practices: blog.habnab.it/blog/2013/07/21/python-packages-and-you, and PEP8 says that "implicit relative imports should never be used and have been removed in Python 3." See: python.org/dev/peps/pep-0008.

            – Apteryx
            Nov 4 '16 at 20:23













          • @Apteryx You mean "project-absolute" right? Because things like /home/user/dev/projectxyz/src ... would be really bad and not run on other machines in most cases. I think what I meant is, that I have to always write the whole project root to module path even if a module is in the same folder as the file run. I didn't know that this is considered best practice, so that's a useful bit of information, thanks. I agree with most of pep8, although it is still not perfect.

            – Zelphir
            Nov 6 '16 at 19:44






          • 2





            I have added __init__.py in tests, that solved the problem. Now I can use pytest

            – Kiran Kumar Kotari
            Dec 26 '18 at 6:08








          2




          2





          That's a pretty neat workaround, e.g. for testing scripts and modules which are not packages/installable!

          – Christoph
          May 30 '16 at 8:41





          That's a pretty neat workaround, e.g. for testing scripts and modules which are not packages/installable!

          – Christoph
          May 30 '16 at 8:41




          1




          1





          It requires to rewrite relative imports to absolute ones, if you have the code for running the application not on the level, where you execute the command from. For example: project/test/all-my-tests and project/src/app.py and because of that change, one needs to call the app.py indirectly using a __main__.py file in project/src, so that one can use the call python -m src. Pretty messy stuff as far as I can tell.

          – Zelphir
          Sep 26 '16 at 15:44





          It requires to rewrite relative imports to absolute ones, if you have the code for running the application not on the level, where you execute the command from. For example: project/test/all-my-tests and project/src/app.py and because of that change, one needs to call the app.py indirectly using a __main__.py file in project/src, so that one can use the call python -m src. Pretty messy stuff as far as I can tell.

          – Zelphir
          Sep 26 '16 at 15:44




          2




          2





          @Zelphir: Using absolute imports is a recommended practice. Habnabit's has a good article about packaging best practices: blog.habnab.it/blog/2013/07/21/python-packages-and-you, and PEP8 says that "implicit relative imports should never be used and have been removed in Python 3." See: python.org/dev/peps/pep-0008.

          – Apteryx
          Nov 4 '16 at 20:23







          @Zelphir: Using absolute imports is a recommended practice. Habnabit's has a good article about packaging best practices: blog.habnab.it/blog/2013/07/21/python-packages-and-you, and PEP8 says that "implicit relative imports should never be used and have been removed in Python 3." See: python.org/dev/peps/pep-0008.

          – Apteryx
          Nov 4 '16 at 20:23















          @Apteryx You mean "project-absolute" right? Because things like /home/user/dev/projectxyz/src ... would be really bad and not run on other machines in most cases. I think what I meant is, that I have to always write the whole project root to module path even if a module is in the same folder as the file run. I didn't know that this is considered best practice, so that's a useful bit of information, thanks. I agree with most of pep8, although it is still not perfect.

          – Zelphir
          Nov 6 '16 at 19:44





          @Apteryx You mean "project-absolute" right? Because things like /home/user/dev/projectxyz/src ... would be really bad and not run on other machines in most cases. I think what I meant is, that I have to always write the whole project root to module path even if a module is in the same folder as the file run. I didn't know that this is considered best practice, so that's a useful bit of information, thanks. I agree with most of pep8, although it is still not perfect.

          – Zelphir
          Nov 6 '16 at 19:44




          2




          2





          I have added __init__.py in tests, that solved the problem. Now I can use pytest

          – Kiran Kumar Kotari
          Dec 26 '18 at 6:08





          I have added __init__.py in tests, that solved the problem. Now I can use pytest

          – Kiran Kumar Kotari
          Dec 26 '18 at 6:08











          91














          I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.






          share|improve this answer





















          • 60





            Note that this is NOT recommended by py.test: avoid “__init__.py” files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not. SRC: pytest.org/latest/goodpractises.html

            – K.-Michael Aye
            May 30 '14 at 21:52








          • 18





            I came here with the same question and found removing __init__.py from my tests directory solved it for me.

            – 101
            Oct 13 '15 at 0:24








          • 2





            @K.-MichaelAye How are you supposed to import modules in your tests, if the tests directory is not a package??

            – mafrosis
            Nov 3 '15 at 15:11






          • 3





            Adding an __init__.py in sub-directories of test/ makes absolute import work for running specific tests in that sub-directory against to-be installed modules. Thanks.

            – Bryce Guinta
            Sep 9 '16 at 22:01






          • 5





            there you go: doc.pytest.org/en/latest/goodpractices.html really easy to find with google.

            – K.-Michael Aye
            Jan 12 '17 at 0:56
















          91














          I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.






          share|improve this answer





















          • 60





            Note that this is NOT recommended by py.test: avoid “__init__.py” files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not. SRC: pytest.org/latest/goodpractises.html

            – K.-Michael Aye
            May 30 '14 at 21:52








          • 18





            I came here with the same question and found removing __init__.py from my tests directory solved it for me.

            – 101
            Oct 13 '15 at 0:24








          • 2





            @K.-MichaelAye How are you supposed to import modules in your tests, if the tests directory is not a package??

            – mafrosis
            Nov 3 '15 at 15:11






          • 3





            Adding an __init__.py in sub-directories of test/ makes absolute import work for running specific tests in that sub-directory against to-be installed modules. Thanks.

            – Bryce Guinta
            Sep 9 '16 at 22:01






          • 5





            there you go: doc.pytest.org/en/latest/goodpractices.html really easy to find with google.

            – K.-Michael Aye
            Jan 12 '17 at 0:56














          91












          91








          91







          I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.






          share|improve this answer















          I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 10 '14 at 1:38

























          answered Sep 24 '13 at 1:20









          Aron CurzonAron Curzon

          1,77711314




          1,77711314








          • 60





            Note that this is NOT recommended by py.test: avoid “__init__.py” files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not. SRC: pytest.org/latest/goodpractises.html

            – K.-Michael Aye
            May 30 '14 at 21:52








          • 18





            I came here with the same question and found removing __init__.py from my tests directory solved it for me.

            – 101
            Oct 13 '15 at 0:24








          • 2





            @K.-MichaelAye How are you supposed to import modules in your tests, if the tests directory is not a package??

            – mafrosis
            Nov 3 '15 at 15:11






          • 3





            Adding an __init__.py in sub-directories of test/ makes absolute import work for running specific tests in that sub-directory against to-be installed modules. Thanks.

            – Bryce Guinta
            Sep 9 '16 at 22:01






          • 5





            there you go: doc.pytest.org/en/latest/goodpractices.html really easy to find with google.

            – K.-Michael Aye
            Jan 12 '17 at 0:56














          • 60





            Note that this is NOT recommended by py.test: avoid “__init__.py” files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not. SRC: pytest.org/latest/goodpractises.html

            – K.-Michael Aye
            May 30 '14 at 21:52








          • 18





            I came here with the same question and found removing __init__.py from my tests directory solved it for me.

            – 101
            Oct 13 '15 at 0:24








          • 2





            @K.-MichaelAye How are you supposed to import modules in your tests, if the tests directory is not a package??

            – mafrosis
            Nov 3 '15 at 15:11






          • 3





            Adding an __init__.py in sub-directories of test/ makes absolute import work for running specific tests in that sub-directory against to-be installed modules. Thanks.

            – Bryce Guinta
            Sep 9 '16 at 22:01






          • 5





            there you go: doc.pytest.org/en/latest/goodpractices.html really easy to find with google.

            – K.-Michael Aye
            Jan 12 '17 at 0:56








          60




          60





          Note that this is NOT recommended by py.test: avoid “__init__.py” files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not. SRC: pytest.org/latest/goodpractises.html

          – K.-Michael Aye
          May 30 '14 at 21:52







          Note that this is NOT recommended by py.test: avoid “__init__.py” files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not. SRC: pytest.org/latest/goodpractises.html

          – K.-Michael Aye
          May 30 '14 at 21:52






          18




          18





          I came here with the same question and found removing __init__.py from my tests directory solved it for me.

          – 101
          Oct 13 '15 at 0:24







          I came here with the same question and found removing __init__.py from my tests directory solved it for me.

          – 101
          Oct 13 '15 at 0:24






          2




          2





          @K.-MichaelAye How are you supposed to import modules in your tests, if the tests directory is not a package??

          – mafrosis
          Nov 3 '15 at 15:11





          @K.-MichaelAye How are you supposed to import modules in your tests, if the tests directory is not a package??

          – mafrosis
          Nov 3 '15 at 15:11




          3




          3





          Adding an __init__.py in sub-directories of test/ makes absolute import work for running specific tests in that sub-directory against to-be installed modules. Thanks.

          – Bryce Guinta
          Sep 9 '16 at 22:01





          Adding an __init__.py in sub-directories of test/ makes absolute import work for running specific tests in that sub-directory against to-be installed modules. Thanks.

          – Bryce Guinta
          Sep 9 '16 at 22:01




          5




          5





          there you go: doc.pytest.org/en/latest/goodpractices.html really easy to find with google.

          – K.-Michael Aye
          Jan 12 '17 at 0:56





          there you go: doc.pytest.org/en/latest/goodpractices.html really easy to find with google.

          – K.-Michael Aye
          Jan 12 '17 at 0:56











          36















          conftest solution



          The least invasive solution is adding an empty file named conftest.py in the repo/ directory:



          $ touch repo/conftest.py


          That's it. No need to write custom code for mangling the sys.path or remember to drag PYTHONPATH along, or placing __init__.py into dirs where it doesn't belong.



          The project directory afterwards:



          repo
          ├── conftest.py
          ├── app.py
          ├── settings.py
          ├── models.py
          └── tests
          └── test_app.py


          Explanation



          pytest looks for the conftest modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest adds the parent directory of the conftest.py to the sys.path.



          Other project structures



          If you have other project structure, place the conftest.py in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py), for example:



          repo
          ├── conftest.py
          ├── spam
          │ ├── __init__.py
          │ ├── bacon.py
          │ └── egg.py
          ├── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Same approach with the src layout: place conftest.py in the src dir:



          repo
          ├── src
          │ ├── conftest.py
          │ ├── spam
          │ │ ├── __init__.py
          │ │ ├── bacon.py
          │ │ └── egg.py
          │ └── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Where to go from here



          Of course, conftest modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest framework and the customization of your test suite happen. pytest has a lot of information on conftest modules scattered throughout their docs; start with conftest.py: local per-directory plugins



          Also, SO has an excellent question on conftest modules: In py.test, what is the use of conftest.py files?






          share|improve this answer





















          • 3





            This really ought to be the accepted answer, all the others are clunky workarounds.

            – Davide
            Sep 20 '18 at 21:40











          • @Davide thanks, glad the recipe was worth sharing!

            – hoefling
            Sep 26 '18 at 16:52






          • 1





            Thanks a million, this fixed tests inside VS Code!

            – Daniel McLean
            Oct 25 '18 at 14:40











          • This does not work, simple as that. Try putting a file at the root directory, and then importing that from a test. Setting PYTHONPATH to root works fine, this hack does not help at all.

            – aaa90210
            Jan 15 at 21:55











          • @aaa90210 although I can't reproduce your issue (importing from a conftest in a root dir works on any level), you should never import from conftest files as it's a reserved name for pytest and it's strongly advised not to do so. By doing that, you plant seeds for future errors. Create another module named utils.py and place the code for reusing in tests there.

            – hoefling
            Jan 15 at 22:09
















          36















          conftest solution



          The least invasive solution is adding an empty file named conftest.py in the repo/ directory:



          $ touch repo/conftest.py


          That's it. No need to write custom code for mangling the sys.path or remember to drag PYTHONPATH along, or placing __init__.py into dirs where it doesn't belong.



          The project directory afterwards:



          repo
          ├── conftest.py
          ├── app.py
          ├── settings.py
          ├── models.py
          └── tests
          └── test_app.py


          Explanation



          pytest looks for the conftest modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest adds the parent directory of the conftest.py to the sys.path.



          Other project structures



          If you have other project structure, place the conftest.py in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py), for example:



          repo
          ├── conftest.py
          ├── spam
          │ ├── __init__.py
          │ ├── bacon.py
          │ └── egg.py
          ├── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Same approach with the src layout: place conftest.py in the src dir:



          repo
          ├── src
          │ ├── conftest.py
          │ ├── spam
          │ │ ├── __init__.py
          │ │ ├── bacon.py
          │ │ └── egg.py
          │ └── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Where to go from here



          Of course, conftest modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest framework and the customization of your test suite happen. pytest has a lot of information on conftest modules scattered throughout their docs; start with conftest.py: local per-directory plugins



          Also, SO has an excellent question on conftest modules: In py.test, what is the use of conftest.py files?






          share|improve this answer





















          • 3





            This really ought to be the accepted answer, all the others are clunky workarounds.

            – Davide
            Sep 20 '18 at 21:40











          • @Davide thanks, glad the recipe was worth sharing!

            – hoefling
            Sep 26 '18 at 16:52






          • 1





            Thanks a million, this fixed tests inside VS Code!

            – Daniel McLean
            Oct 25 '18 at 14:40











          • This does not work, simple as that. Try putting a file at the root directory, and then importing that from a test. Setting PYTHONPATH to root works fine, this hack does not help at all.

            – aaa90210
            Jan 15 at 21:55











          • @aaa90210 although I can't reproduce your issue (importing from a conftest in a root dir works on any level), you should never import from conftest files as it's a reserved name for pytest and it's strongly advised not to do so. By doing that, you plant seeds for future errors. Create another module named utils.py and place the code for reusing in tests there.

            – hoefling
            Jan 15 at 22:09














          36












          36








          36








          conftest solution



          The least invasive solution is adding an empty file named conftest.py in the repo/ directory:



          $ touch repo/conftest.py


          That's it. No need to write custom code for mangling the sys.path or remember to drag PYTHONPATH along, or placing __init__.py into dirs where it doesn't belong.



          The project directory afterwards:



          repo
          ├── conftest.py
          ├── app.py
          ├── settings.py
          ├── models.py
          └── tests
          └── test_app.py


          Explanation



          pytest looks for the conftest modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest adds the parent directory of the conftest.py to the sys.path.



          Other project structures



          If you have other project structure, place the conftest.py in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py), for example:



          repo
          ├── conftest.py
          ├── spam
          │ ├── __init__.py
          │ ├── bacon.py
          │ └── egg.py
          ├── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Same approach with the src layout: place conftest.py in the src dir:



          repo
          ├── src
          │ ├── conftest.py
          │ ├── spam
          │ │ ├── __init__.py
          │ │ ├── bacon.py
          │ │ └── egg.py
          │ └── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Where to go from here



          Of course, conftest modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest framework and the customization of your test suite happen. pytest has a lot of information on conftest modules scattered throughout their docs; start with conftest.py: local per-directory plugins



          Also, SO has an excellent question on conftest modules: In py.test, what is the use of conftest.py files?






          share|improve this answer
















          conftest solution



          The least invasive solution is adding an empty file named conftest.py in the repo/ directory:



          $ touch repo/conftest.py


          That's it. No need to write custom code for mangling the sys.path or remember to drag PYTHONPATH along, or placing __init__.py into dirs where it doesn't belong.



          The project directory afterwards:



          repo
          ├── conftest.py
          ├── app.py
          ├── settings.py
          ├── models.py
          └── tests
          └── test_app.py


          Explanation



          pytest looks for the conftest modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest adds the parent directory of the conftest.py to the sys.path.



          Other project structures



          If you have other project structure, place the conftest.py in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py), for example:



          repo
          ├── conftest.py
          ├── spam
          │ ├── __init__.py
          │ ├── bacon.py
          │ └── egg.py
          ├── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Same approach with the src layout: place conftest.py in the src dir:



          repo
          ├── src
          │ ├── conftest.py
          │ ├── spam
          │ │ ├── __init__.py
          │ │ ├── bacon.py
          │ │ └── egg.py
          │ └── eggs
          │ ├── __init__.py
          │ └── sausage.py
          └── tests
          ├── test_bacon.py
          └── test_egg.py


          Where to go from here



          Of course, conftest modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest framework and the customization of your test suite happen. pytest has a lot of information on conftest modules scattered throughout their docs; start with conftest.py: local per-directory plugins



          Also, SO has an excellent question on conftest modules: In py.test, what is the use of conftest.py files?







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 20 at 12:55

























          answered May 30 '18 at 17:42









          hoeflinghoefling

          13.3k43467




          13.3k43467








          • 3





            This really ought to be the accepted answer, all the others are clunky workarounds.

            – Davide
            Sep 20 '18 at 21:40











          • @Davide thanks, glad the recipe was worth sharing!

            – hoefling
            Sep 26 '18 at 16:52






          • 1





            Thanks a million, this fixed tests inside VS Code!

            – Daniel McLean
            Oct 25 '18 at 14:40











          • This does not work, simple as that. Try putting a file at the root directory, and then importing that from a test. Setting PYTHONPATH to root works fine, this hack does not help at all.

            – aaa90210
            Jan 15 at 21:55











          • @aaa90210 although I can't reproduce your issue (importing from a conftest in a root dir works on any level), you should never import from conftest files as it's a reserved name for pytest and it's strongly advised not to do so. By doing that, you plant seeds for future errors. Create another module named utils.py and place the code for reusing in tests there.

            – hoefling
            Jan 15 at 22:09














          • 3





            This really ought to be the accepted answer, all the others are clunky workarounds.

            – Davide
            Sep 20 '18 at 21:40











          • @Davide thanks, glad the recipe was worth sharing!

            – hoefling
            Sep 26 '18 at 16:52






          • 1





            Thanks a million, this fixed tests inside VS Code!

            – Daniel McLean
            Oct 25 '18 at 14:40











          • This does not work, simple as that. Try putting a file at the root directory, and then importing that from a test. Setting PYTHONPATH to root works fine, this hack does not help at all.

            – aaa90210
            Jan 15 at 21:55











          • @aaa90210 although I can't reproduce your issue (importing from a conftest in a root dir works on any level), you should never import from conftest files as it's a reserved name for pytest and it's strongly advised not to do so. By doing that, you plant seeds for future errors. Create another module named utils.py and place the code for reusing in tests there.

            – hoefling
            Jan 15 at 22:09








          3




          3





          This really ought to be the accepted answer, all the others are clunky workarounds.

          – Davide
          Sep 20 '18 at 21:40





          This really ought to be the accepted answer, all the others are clunky workarounds.

          – Davide
          Sep 20 '18 at 21:40













          @Davide thanks, glad the recipe was worth sharing!

          – hoefling
          Sep 26 '18 at 16:52





          @Davide thanks, glad the recipe was worth sharing!

          – hoefling
          Sep 26 '18 at 16:52




          1




          1





          Thanks a million, this fixed tests inside VS Code!

          – Daniel McLean
          Oct 25 '18 at 14:40





          Thanks a million, this fixed tests inside VS Code!

          – Daniel McLean
          Oct 25 '18 at 14:40













          This does not work, simple as that. Try putting a file at the root directory, and then importing that from a test. Setting PYTHONPATH to root works fine, this hack does not help at all.

          – aaa90210
          Jan 15 at 21:55





          This does not work, simple as that. Try putting a file at the root directory, and then importing that from a test. Setting PYTHONPATH to root works fine, this hack does not help at all.

          – aaa90210
          Jan 15 at 21:55













          @aaa90210 although I can't reproduce your issue (importing from a conftest in a root dir works on any level), you should never import from conftest files as it's a reserved name for pytest and it's strongly advised not to do so. By doing that, you plant seeds for future errors. Create another module named utils.py and place the code for reusing in tests there.

          – hoefling
          Jan 15 at 22:09





          @aaa90210 although I can't reproduce your issue (importing from a conftest in a root dir works on any level), you should never import from conftest files as it's a reserved name for pytest and it's strongly advised not to do so. By doing that, you plant seeds for future errors. Create another module named utils.py and place the code for reusing in tests there.

          – hoefling
          Jan 15 at 22:09











          35














          You can run with PYTHONPATH in project root



          PYTHONPATH=. py.test


          Or use pip install as editable import



          pip install -e .   # install package using setup.py in editable mode





          share|improve this answer



















          • 2





            That didn't work for me with a test directory not in src directory structure and calling from the directory containing both test and src directory.

            – Zelphir
            Mar 13 '16 at 22:53
















          35














          You can run with PYTHONPATH in project root



          PYTHONPATH=. py.test


          Or use pip install as editable import



          pip install -e .   # install package using setup.py in editable mode





          share|improve this answer



















          • 2





            That didn't work for me with a test directory not in src directory structure and calling from the directory containing both test and src directory.

            – Zelphir
            Mar 13 '16 at 22:53














          35












          35








          35







          You can run with PYTHONPATH in project root



          PYTHONPATH=. py.test


          Or use pip install as editable import



          pip install -e .   # install package using setup.py in editable mode





          share|improve this answer













          You can run with PYTHONPATH in project root



          PYTHONPATH=. py.test


          Or use pip install as editable import



          pip install -e .   # install package using setup.py in editable mode






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Oct 24 '14 at 9:03









          Ford GuoFord Guo

          781716




          781716








          • 2





            That didn't work for me with a test directory not in src directory structure and calling from the directory containing both test and src directory.

            – Zelphir
            Mar 13 '16 at 22:53














          • 2





            That didn't work for me with a test directory not in src directory structure and calling from the directory containing both test and src directory.

            – Zelphir
            Mar 13 '16 at 22:53








          2




          2





          That didn't work for me with a test directory not in src directory structure and calling from the directory containing both test and src directory.

          – Zelphir
          Mar 13 '16 at 22:53





          That didn't work for me with a test directory not in src directory structure and calling from the directory containing both test and src directory.

          – Zelphir
          Mar 13 '16 at 22:53











          24














          Run pytest itself as a module with:
          python -m pytest tests






          share|improve this answer



















          • 4





            This is the best solution. Thanks!

            – blakev
            Apr 23 '18 at 16:52






          • 1





            This seems to be a working solution, but can anyone explain WHY? I'd rather fix the underlying cause than just use python -m pytest without any explanation other than "because it works"

            – Janne Enberg
            Aug 23 '18 at 8:30






          • 2





            This happens when project hierarchy is for example: package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute than relative to the execution location.

            – Stefano Messina
            Aug 23 '18 at 11:55













          • This solution helped me, thanks! The cause of this was because of the conflict in Python version. pytest test works for earlier python version. In my situation, my python version is 3.7.1, python -m pytest tests works but not pytest tests.

            – Ruxi Zhang
            Jan 4 at 19:16
















          24














          Run pytest itself as a module with:
          python -m pytest tests






          share|improve this answer



















          • 4





            This is the best solution. Thanks!

            – blakev
            Apr 23 '18 at 16:52






          • 1





            This seems to be a working solution, but can anyone explain WHY? I'd rather fix the underlying cause than just use python -m pytest without any explanation other than "because it works"

            – Janne Enberg
            Aug 23 '18 at 8:30






          • 2





            This happens when project hierarchy is for example: package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute than relative to the execution location.

            – Stefano Messina
            Aug 23 '18 at 11:55













          • This solution helped me, thanks! The cause of this was because of the conflict in Python version. pytest test works for earlier python version. In my situation, my python version is 3.7.1, python -m pytest tests works but not pytest tests.

            – Ruxi Zhang
            Jan 4 at 19:16














          24












          24








          24







          Run pytest itself as a module with:
          python -m pytest tests






          share|improve this answer













          Run pytest itself as a module with:
          python -m pytest tests







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 2 '18 at 9:37









          Stefano MessinaStefano Messina

          425714




          425714








          • 4





            This is the best solution. Thanks!

            – blakev
            Apr 23 '18 at 16:52






          • 1





            This seems to be a working solution, but can anyone explain WHY? I'd rather fix the underlying cause than just use python -m pytest without any explanation other than "because it works"

            – Janne Enberg
            Aug 23 '18 at 8:30






          • 2





            This happens when project hierarchy is for example: package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute than relative to the execution location.

            – Stefano Messina
            Aug 23 '18 at 11:55













          • This solution helped me, thanks! The cause of this was because of the conflict in Python version. pytest test works for earlier python version. In my situation, my python version is 3.7.1, python -m pytest tests works but not pytest tests.

            – Ruxi Zhang
            Jan 4 at 19:16














          • 4





            This is the best solution. Thanks!

            – blakev
            Apr 23 '18 at 16:52






          • 1





            This seems to be a working solution, but can anyone explain WHY? I'd rather fix the underlying cause than just use python -m pytest without any explanation other than "because it works"

            – Janne Enberg
            Aug 23 '18 at 8:30






          • 2





            This happens when project hierarchy is for example: package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute than relative to the execution location.

            – Stefano Messina
            Aug 23 '18 at 11:55













          • This solution helped me, thanks! The cause of this was because of the conflict in Python version. pytest test works for earlier python version. In my situation, my python version is 3.7.1, python -m pytest tests works but not pytest tests.

            – Ruxi Zhang
            Jan 4 at 19:16








          4




          4





          This is the best solution. Thanks!

          – blakev
          Apr 23 '18 at 16:52





          This is the best solution. Thanks!

          – blakev
          Apr 23 '18 at 16:52




          1




          1





          This seems to be a working solution, but can anyone explain WHY? I'd rather fix the underlying cause than just use python -m pytest without any explanation other than "because it works"

          – Janne Enberg
          Aug 23 '18 at 8:30





          This seems to be a working solution, but can anyone explain WHY? I'd rather fix the underlying cause than just use python -m pytest without any explanation other than "because it works"

          – Janne Enberg
          Aug 23 '18 at 8:30




          2




          2





          This happens when project hierarchy is for example: package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute than relative to the execution location.

          – Stefano Messina
          Aug 23 '18 at 11:55







          This happens when project hierarchy is for example: package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute than relative to the execution location.

          – Stefano Messina
          Aug 23 '18 at 11:55















          This solution helped me, thanks! The cause of this was because of the conflict in Python version. pytest test works for earlier python version. In my situation, my python version is 3.7.1, python -m pytest tests works but not pytest tests.

          – Ruxi Zhang
          Jan 4 at 19:16





          This solution helped me, thanks! The cause of this was because of the conflict in Python version. pytest test works for earlier python version. In my situation, my python version is 3.7.1, python -m pytest tests works but not pytest tests.

          – Ruxi Zhang
          Jan 4 at 19:16











          18














          I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.



          https://github.com/jeffmacdonald/pytest_test



          Specifically: You have to tell py.test and tox where to find the modules you are including.



          With py.test you can do this:



          PYTHONPATH=. py.test


          And with tox, add this to your tox.ini:



          [testenv]
          deps= -r{toxinidir}/requirements.txt
          commands=py.test
          setenv =
          PYTHONPATH = {toxinidir}





          share|improve this answer





















          • 1





            Could you give a short explanation for the project you linked?

            – JF Meier
            Jul 15 '16 at 14:06






          • 1





            Maybe its just me, but the README on the project is pretty detailed, and my comment on stackoverflow says why I created the repo.

            – Jeff MacDonald
            Jul 15 '16 at 14:10






          • 4





            While it is not strictly necessary, it is a usual policy to have the main content of an answer in the answer itself because it ensures that the answer is understandable in x years from now when the linked resource may be long gone.

            – JF Meier
            Jul 15 '16 at 14:13











          • Fair point. I'll update it.

            – Jeff MacDonald
            Jul 15 '16 at 14:22











          • Thank you (FYI: I did not vote you down).

            – JF Meier
            Jul 15 '16 at 14:28
















          18














          I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.



          https://github.com/jeffmacdonald/pytest_test



          Specifically: You have to tell py.test and tox where to find the modules you are including.



          With py.test you can do this:



          PYTHONPATH=. py.test


          And with tox, add this to your tox.ini:



          [testenv]
          deps= -r{toxinidir}/requirements.txt
          commands=py.test
          setenv =
          PYTHONPATH = {toxinidir}





          share|improve this answer





















          • 1





            Could you give a short explanation for the project you linked?

            – JF Meier
            Jul 15 '16 at 14:06






          • 1





            Maybe its just me, but the README on the project is pretty detailed, and my comment on stackoverflow says why I created the repo.

            – Jeff MacDonald
            Jul 15 '16 at 14:10






          • 4





            While it is not strictly necessary, it is a usual policy to have the main content of an answer in the answer itself because it ensures that the answer is understandable in x years from now when the linked resource may be long gone.

            – JF Meier
            Jul 15 '16 at 14:13











          • Fair point. I'll update it.

            – Jeff MacDonald
            Jul 15 '16 at 14:22











          • Thank you (FYI: I did not vote you down).

            – JF Meier
            Jul 15 '16 at 14:28














          18












          18








          18







          I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.



          https://github.com/jeffmacdonald/pytest_test



          Specifically: You have to tell py.test and tox where to find the modules you are including.



          With py.test you can do this:



          PYTHONPATH=. py.test


          And with tox, add this to your tox.ini:



          [testenv]
          deps= -r{toxinidir}/requirements.txt
          commands=py.test
          setenv =
          PYTHONPATH = {toxinidir}





          share|improve this answer















          I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.



          https://github.com/jeffmacdonald/pytest_test



          Specifically: You have to tell py.test and tox where to find the modules you are including.



          With py.test you can do this:



          PYTHONPATH=. py.test


          And with tox, add this to your tox.ini:



          [testenv]
          deps= -r{toxinidir}/requirements.txt
          commands=py.test
          setenv =
          PYTHONPATH = {toxinidir}






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 15 '16 at 14:24

























          answered Jul 15 '16 at 13:46









          Jeff MacDonaldJeff MacDonald

          36133




          36133








          • 1





            Could you give a short explanation for the project you linked?

            – JF Meier
            Jul 15 '16 at 14:06






          • 1





            Maybe its just me, but the README on the project is pretty detailed, and my comment on stackoverflow says why I created the repo.

            – Jeff MacDonald
            Jul 15 '16 at 14:10






          • 4





            While it is not strictly necessary, it is a usual policy to have the main content of an answer in the answer itself because it ensures that the answer is understandable in x years from now when the linked resource may be long gone.

            – JF Meier
            Jul 15 '16 at 14:13











          • Fair point. I'll update it.

            – Jeff MacDonald
            Jul 15 '16 at 14:22











          • Thank you (FYI: I did not vote you down).

            – JF Meier
            Jul 15 '16 at 14:28














          • 1





            Could you give a short explanation for the project you linked?

            – JF Meier
            Jul 15 '16 at 14:06






          • 1





            Maybe its just me, but the README on the project is pretty detailed, and my comment on stackoverflow says why I created the repo.

            – Jeff MacDonald
            Jul 15 '16 at 14:10






          • 4





            While it is not strictly necessary, it is a usual policy to have the main content of an answer in the answer itself because it ensures that the answer is understandable in x years from now when the linked resource may be long gone.

            – JF Meier
            Jul 15 '16 at 14:13











          • Fair point. I'll update it.

            – Jeff MacDonald
            Jul 15 '16 at 14:22











          • Thank you (FYI: I did not vote you down).

            – JF Meier
            Jul 15 '16 at 14:28








          1




          1





          Could you give a short explanation for the project you linked?

          – JF Meier
          Jul 15 '16 at 14:06





          Could you give a short explanation for the project you linked?

          – JF Meier
          Jul 15 '16 at 14:06




          1




          1





          Maybe its just me, but the README on the project is pretty detailed, and my comment on stackoverflow says why I created the repo.

          – Jeff MacDonald
          Jul 15 '16 at 14:10





          Maybe its just me, but the README on the project is pretty detailed, and my comment on stackoverflow says why I created the repo.

          – Jeff MacDonald
          Jul 15 '16 at 14:10




          4




          4





          While it is not strictly necessary, it is a usual policy to have the main content of an answer in the answer itself because it ensures that the answer is understandable in x years from now when the linked resource may be long gone.

          – JF Meier
          Jul 15 '16 at 14:13





          While it is not strictly necessary, it is a usual policy to have the main content of an answer in the answer itself because it ensures that the answer is understandable in x years from now when the linked resource may be long gone.

          – JF Meier
          Jul 15 '16 at 14:13













          Fair point. I'll update it.

          – Jeff MacDonald
          Jul 15 '16 at 14:22





          Fair point. I'll update it.

          – Jeff MacDonald
          Jul 15 '16 at 14:22













          Thank you (FYI: I did not vote you down).

          – JF Meier
          Jul 15 '16 at 14:28





          Thank you (FYI: I did not vote you down).

          – JF Meier
          Jul 15 '16 at 14:28











          6














          I started getting weird ConftestImportFailure: ImportError('No module named ... errors when I had accidentally added __init__.py file to my src directory (which was not supposed to be a Python package, just a container of all source).






          share|improve this answer






























            6














            I started getting weird ConftestImportFailure: ImportError('No module named ... errors when I had accidentally added __init__.py file to my src directory (which was not supposed to be a Python package, just a container of all source).






            share|improve this answer




























              6












              6








              6







              I started getting weird ConftestImportFailure: ImportError('No module named ... errors when I had accidentally added __init__.py file to my src directory (which was not supposed to be a Python package, just a container of all source).






              share|improve this answer















              I started getting weird ConftestImportFailure: ImportError('No module named ... errors when I had accidentally added __init__.py file to my src directory (which was not supposed to be a Python package, just a container of all source).







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 22 '18 at 11:03









              AkshayNevrekar

              5,32291940




              5,32291940










              answered Aug 14 '17 at 16:44









              jbaskojbasko

              4,78012639




              4,78012639























                  2














                  I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.



                  'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.






                  share|improve this answer






























                    2














                    I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.



                    'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.






                    share|improve this answer




























                      2












                      2








                      2







                      I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.



                      'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.






                      share|improve this answer















                      I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.



                      'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 9 '17 at 15:22









                      pbskumar

                      683713




                      683713










                      answered Aug 28 '17 at 2:56









                      craqcraq

                      4011723




                      4011723























                          1














                          For me the problem was tests.py generated by Django along with tests directory. Removing tests.py solved the problem.






                          share|improve this answer




























                            1














                            For me the problem was tests.py generated by Django along with tests directory. Removing tests.py solved the problem.






                            share|improve this answer


























                              1












                              1








                              1







                              For me the problem was tests.py generated by Django along with tests directory. Removing tests.py solved the problem.






                              share|improve this answer













                              For me the problem was tests.py generated by Django along with tests directory. Removing tests.py solved the problem.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Dec 4 '18 at 12:10









                              Paweł MuchaPaweł Mucha

                              563




                              563























                                  1














                                  I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.



                                  from repo.app import *


                                  However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.



                                  from app import *


                                  Here's an example of what I had to do with one of my projects:



                                  Here’s my project structure:



                                  microbit/
                                  microbit/activity_indicator/activity_indicator.py
                                  microbit/tests/test_activity_indicator.py


                                  To be able to access activity_indicator.py from test_activity_indicator.py I needed to:




                                  • start test_activity_indicatory.py with the correct relative import:


                                      from microbit.activity_indicator.activity_indicator import *



                                  • put __init__.py files throughout the project structure:


                                      microbit/
                                  microbit/__init__.py
                                  microbit/activity_indicator/__init__.py
                                  microbit/activity_indicator/activity_indicator.py
                                  microbit/tests/__init__.py
                                  microbit/tests/test_activity_indicator.py





                                  share|improve this answer






























                                    1














                                    I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.



                                    from repo.app import *


                                    However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.



                                    from app import *


                                    Here's an example of what I had to do with one of my projects:



                                    Here’s my project structure:



                                    microbit/
                                    microbit/activity_indicator/activity_indicator.py
                                    microbit/tests/test_activity_indicator.py


                                    To be able to access activity_indicator.py from test_activity_indicator.py I needed to:




                                    • start test_activity_indicatory.py with the correct relative import:


                                        from microbit.activity_indicator.activity_indicator import *



                                    • put __init__.py files throughout the project structure:


                                        microbit/
                                    microbit/__init__.py
                                    microbit/activity_indicator/__init__.py
                                    microbit/activity_indicator/activity_indicator.py
                                    microbit/tests/__init__.py
                                    microbit/tests/test_activity_indicator.py





                                    share|improve this answer




























                                      1












                                      1








                                      1







                                      I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.



                                      from repo.app import *


                                      However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.



                                      from app import *


                                      Here's an example of what I had to do with one of my projects:



                                      Here’s my project structure:



                                      microbit/
                                      microbit/activity_indicator/activity_indicator.py
                                      microbit/tests/test_activity_indicator.py


                                      To be able to access activity_indicator.py from test_activity_indicator.py I needed to:




                                      • start test_activity_indicatory.py with the correct relative import:


                                          from microbit.activity_indicator.activity_indicator import *



                                      • put __init__.py files throughout the project structure:


                                          microbit/
                                      microbit/__init__.py
                                      microbit/activity_indicator/__init__.py
                                      microbit/activity_indicator/activity_indicator.py
                                      microbit/tests/__init__.py
                                      microbit/tests/test_activity_indicator.py





                                      share|improve this answer















                                      I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.



                                      from repo.app import *


                                      However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.



                                      from app import *


                                      Here's an example of what I had to do with one of my projects:



                                      Here’s my project structure:



                                      microbit/
                                      microbit/activity_indicator/activity_indicator.py
                                      microbit/tests/test_activity_indicator.py


                                      To be able to access activity_indicator.py from test_activity_indicator.py I needed to:




                                      • start test_activity_indicatory.py with the correct relative import:


                                          from microbit.activity_indicator.activity_indicator import *



                                      • put __init__.py files throughout the project structure:


                                          microbit/
                                      microbit/__init__.py
                                      microbit/activity_indicator/__init__.py
                                      microbit/activity_indicator/activity_indicator.py
                                      microbit/tests/__init__.py
                                      microbit/tests/test_activity_indicator.py






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jan 16 at 19:01

























                                      answered Jan 16 at 17:07









                                      OppyOppy

                                      99549




                                      99549






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10253826%2fpath-issue-with-pytest-importerror-no-module-named-yadayadayada%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          這個網誌中的熱門文章

                                          Hercules Kyvelos

                                          Tangent Lines Diagram Along Smooth Curve

                                          Yusuf al-Mu'taman ibn Hud