문제

I am trying to run my automated tests on Python, and I keep running into an import error. My Directory Hierarchy is as follows:

TestingPractice
  - bin
  - README.txt
  - setup.py
  - TestingPractice
      - __init__.py
      - main.py
  - tests
      - __init__.py
      - test_main.py

Now when I cd to the top TestingPractice, and run nosetests, I get that my method created in main.py is undeclared, even when importing TestingPractice.main

main.py:

def total_hours(hours):
    sum = 0
    for hour in hours:
        sum += hour
    return sum

test_main.py:

# Test the hour computation. 
from nose.tools import *
import TestingPractice.main

def test_hours():
    to_test = [8,8,7,8] # 31
    assert_equal(total_hours(to_test), 31)

when running nosetests:

/Documents/Developer/Python/TestingPractice/tests/test_main.py", line 7, in test_hours
    assert_equal(total_hours(to_test), 31)
NameError: global name 'total_hours' is not defined

I have tried many different paths for the import, even the relative importing (which caused the relative importing error) and also tried export PYTHONPATH=. to no avail.

도움이 되었습니까?

해결책 2

I was, for some weird reason, not telling Python how to import the function. While a little, obvious fix, I missed it.

Here it is:

in the test_main.py I had to do:

from TestingPractice.main import total_hours

Then, while in the working directory of the top TestingPractice, nosetests worked as supposed to.

다른 팁

Simply do not "cd to the TestingPractice", stay at root of your project and run your tests from there.

I was in past having exactly the same problem, trying to make all test cases runnable from test directory or even better from anywhere. But such a requirements is usually a nonsense and following a rule: run your tests from root of your project works very well - in fact it brings clarity to all your testing code and testing and you will love it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top