2017-02-12 78 views
1

問題上的單元測試

目標在Python單元測試:目標是在calculator.py使用的PyUnit在testCalc.py單元測試的simpleCalc對象。
問題:當testCalc從項目中的單獨目錄運行時,無法將calculator.py中的simpleCalc對象成功導入到testCalc.py中。
背景:testCalc.py中的單元測試與calculator.py包含在同一個目錄中時運行得很好,但是當我將它移動到單獨的文件夾中並嘗試導入calculator.py中定義的simpleCalc對象時,我收到一個錯誤。我正在嘗試學習如何在一個簡單的項目中使用pyUnit單元測試框架,而且我明顯錯過了如何在分層目錄結構中導入用於單元測試的模塊的基本知識。下面介紹的基本calculator_test項目是我創建實踐的一個簡單項目。您可以在本帖末尾看到我已經瀏覽過的所有帖子。
終極問題:如何將simpleCalc對象導入testCalc.py,其目錄層次結構如下所述?導入模塊正常使用的PyUnit

Github上:https://github.com/jaybird4522/calculator_test/tree/unit_test

這裏是我的目錄結構:

calculator_test/ 
    calculatorAlgo/ 
     __init__.py 
     calculator.py 
    test_calculatorAlgo/ 
     __init__.py 
     testCalc.py 
     testlib/ 
      __init__.py 
      testcase.py 

這裏的calculator.py文件,該文件描述了simpleCalc對象我想要的單元測試:

# calculator.py 

class simpleCalc(object): 

    def __init__(self): 
     self.input1 = 0 
     self.input2 = 0 

    def set(self, in1, in2): 
     self.input1 = in1 
     self.input2 = in2 

    def subtract(self, in1, in2): 
     self.set(in1, in2) 
     result = self.input1 - self.input2 
     return result 

這裏的testCalc.py文件,其中包含單元測試:

# testCalc.py 

import unittest 
from calculatorAlgo.calculator import simpleCalc 

class testCalc(unittest.TestCase): 

    # set up the tests by instantiating a simpleCalc object as calc 
    def setUp(self): 
     self.calc = simpleCalc() 

    def runTest(self): 
     self.assertEqual(self.calc.subtract(7,3),4) 

if __name__ == '__main__': 
    unittest.main() 

我一直在運行帶有簡單的命令單元測試文件:

testCalc.py

我已經嘗試什麼到目前爲止

第一次嘗試
我試圖簡單地導入simpleCalc對象基於它位於目錄結構中:

# testCalc.py 

import unittest 
from .calculatorAlgo.calculator import simpleCalc 

class testCalc(unittest.... 

並且得到此錯誤:
ValueError異常:嘗試在非包

第二次嘗試
相對導入我試圖導入它沒有相對引用:

# testCalc.py 

import unittest 
import simpleCalc 

class testCalc(unittest.... 

而得到這個錯誤:
導入錯誤:沒有模塊名爲simpleCalc

第三次嘗試
基於這篇文章,http://blog.aaronboman.com/programming/testing/2016/02/11/how-to-write-tests-in-python-project-structure/,我試着創建一個名爲testcase的單獨的基類。py可以做相對進口。

# testcase.py 

from unittest import TestCase 
from ...calculator import simpleCalc 

class BaseTestCase(TestCase): 
    pass 

而且改變了我的進口testCalc.py

# testCalc.py 

import unittest 
from testlib.testcase import BaseTestCase 

class testCalc(unittest.... 

而得到這個錯誤:
ValueError異常:試圖相對進口超出頂層包

其他資源
這裏是我已經通過無效的一些帖子:
Import a module from a relative path
python packaging for relative imports
How to fix "Attempted relative import in non-package" even with __init__.py
Python importing works from one folder but not another
Relative imports for the billionth time

最終,我覺得我只是缺少一些基本的東西,甚至有很多的研究之後。這感覺就像一個常見的設置,並且我希望有人能告訴我,我做錯了什麼,以及它可能幫助他人避免將來出現此問題。

回答

0

裏面的testCalc.py文件,添加以下內容。

import sys 
import os 

sys.path.append(os.path.abspath('../calculatorAlgo')) 
from calculator import simpleCalc 
+0

我添加了缺少一個斜槓。 – benjamin

+0

它不工作 – Crystal

+0

爲我工作!謝謝@benjamin – jaybird4522