Specially named directories using nosetests

浪尽此生 提交于 2019-12-22 14:06:18

问题


Does nosetests treat directories with certain names differently? Is a src directory special?

If I have a project whose source directory is named src, nosetests seems to work fine. However, if the directory is named anything else, nosetests reports a bunch of import errors.

Here's what I did:

  1. run tests

    ~/src$ nosetests
    ..
    ----------------------------------------------------------------------
    Ran 2 tests in 0.001s
    
    OK
    
  2. rename directory

    ~/src$ cd ..
    ~/$ mv src/ src2
    
  3. rerun tests

    ~/$ cd src2
    ~/src2$ nosetests
    E
    ======================================================================
    ERROR: Failure: ImportError (No module named **whatever**)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
    ... etc. ...
        import **whatever**
    ImportError: No module named **whatever**
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.001s
    
    FAILED (errors=1) 
    

I wasn't able to find anything in the docs about this.


Example: with this directory structure:

.
|-- a
|   |-- b.py
|   `-- __init__.py
|-- __init__.py
`-- test
    |-- a
    |   |-- __init__.py
    |   `-- testb.py
    `-- __init__.py

all __init__.py files are empty, the contents of a/b.py are:

y = 3

and of test/a/testb.py:

import a.b
import unittest as u


class TestB(u.TestCase):

    def test1(self):
        self.assertTrue(True)

    def test2(self):
        self.assertTrue(False)

I can reliably reproduce this problem. Running nosetests -V gives:

nosetests version 1.2.1

回答1:


Quick solution is to remove __init__.py from the top level directory. Another option is to use relative imports, for your example: replace import a.b with from ...a import b.

The culprit of this mess and trickiness is nose importer.

If the directory you are running nosetests in, is a package, nose won't add it to sys.path, otherwise, it'll add it (source). Then, it goes up throw directory tree and applies recursively the same logic. Same thing for all affected files. This explains why it isn't working with __init__.py - root dir (src2 in your case) wasn't in sys.path - that's why package a wasn't found.

But, the open question here is: why it worked the first time, with src folder? src folder is on sys.path in this case. May be there will be other answers or edits.

See related questions:

  • Python Nose Import Error
  • Nosetest including unwanted parent directories
  • Python imports for tests using nose - what is best practice for imports of modules above current package


来源:https://stackoverflow.com/questions/16174649/specially-named-directories-using-nosetests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!