Search code examples
pythonnosenosetests

nosetests unable to find requests package


I have a file foo.py which imports the requests package, and defines a class Foo.

I can run this class just fine from the Python REPL, but when I run nosetests, it fails with the error:

ImportError: No module named requests

This is my dir structure:

.
./mvp
./mvp/__init__.py
./mvp/foo.py
./mvp/tests
./mvp/tests/__init__.py
./mvp/tests/test_foo.py

This is the file ./mvp/__init__.py :

➜  mvp  cat mvp/__init__.py
from .foo import Foo

➜  mvp

This is the file I want to test:

➜  mvp  cat mvp/foo.py
import requests

class Foo(object):
  def foo(self):
    return True

➜  mvp 

./mvp/tests/__init__.py is an empty file.

And this is my test file:

➜  mvp  cat mvp/tests/test_foo.py
from mvp import Foo

def test_foo():
  f = Foo()
  assert f.foo()

➜  mvp  

Running from the Python REPL:

>>> from mvp import Foo
>>> f = Foo()
>>> f
<mvp.foo.Foo object at 0x1012ba1d0>
>>> 

But, running nosetests fails:

(.env)➜  mvp  nosetests
E
======================================================================
ERROR: Failure: ImportError (No module named requests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/loader.py", line 414, in loadTestsFromName
    addr.filename, addr.module)
  File "/Library/Python/2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/Library/Python/2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/Users/foobar/Coding/mvp/mvp/__init__.py", line 1, in <module>
    from .foo import Foo
  File "/Users/foobar/Coding/mvp/mvp/foo.py", line 1, in <module>
    import requests
ImportError: No module named requests

----------------------------------------------------------------------
Ran 1 test in 0.006s

FAILED (errors=1)

I'm in a virtualenv, and requests is installed:

(.env)➜  mvp  pip freeze
requests==2.2.1
wsgiref==0.1.2
(.env)➜  mvp  

Running nosetests -P also causes the same error. I'm at a loss here, spent quite some time searching on google with no luck.

If I comment out the import requests line, nosetests runs just fine.

mvp is a minimal project I created to reproduce the error. I can push it to github if needed.


Solution

  • Make sure that the version of python that nosetests is installed on is the same one that requests is installed on.