Search code examples
pythonnosenameerror

Python - Nosetest returning name *class* not defined on only one file of many


I am trying to test a set of python files using nosetests, and running into "NameError: name 'Sentence' not defined" (note Sentence is the name of a class I want to test in the a file). I do not get this error for other files/classes being tested, and there doesn't seem to be any circular dependency issue.

Error details here:

ex48 $ nosestests
......E
======================================================================
ERROR: Failure: NameError (name 'Sentence' is not defined)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/Users/valentinblehaut/LearnPyth/ex48/tests/parser_tests.py", line 6, in <module>
    stest = Sentence()
NameError: name 'Sentence' is not defined

----------------------------------------------------------------------
Ran 7 tests in 0.007s

FAILED (errors=1)

Here is my folder structure for reference, as well as both the test (parser_tests.py) and tested (parser.py) files:

Folder structure:

+ ex48
    + bin
    + docs
    - lexicon.py
    - parser.py
    - setup.py
    + tests
            - __init__.py
            - lexicon_tests.py
            - parser_tests.py

parser.py file:

class Sentence(object):

    def __init__(self, subject, verb, object):
        self.subject = subject[1]
        self.verb = verb[1]
        self.object = object[1]

Test script for parser.py:

from nose.tools import *
from parser import *

# first create an instance of Sentence class called stest
stest = Sentence()

def test_Sentence():
    assert_equal(stest.subject, "Hi")
    assert_equal(stest.verb, "Hello")
    assert_equal(stest.object, "Howdy")

I have also tried testing only parser.py with:

ex48 $ nostests parser.py

This returns the same NameError message.

Apologies in advance for any formatting/convention errors, kindly let me know of anything I need to fix for any future posts.


Solution

  • parser.py might cause conflict as python package with same name, can you replace parser.py to some other name and also update in test script import.