2017-07-15 153 views
0

我對編程有些新鮮感,到目前爲止,我的大部分程序都是單一的目錄事務,但現在我想嘗試更大的東西,而且我無法使導入工作。我使用pytest來創建我的單元測試,並且在我的test_foo.py文件中的單元測試定義之後,我一直使用獨立測試腳本。這工作正常,直到我添加__init__.py文件。如果使用import card as crd test_card.py進口卡pytest需要與python shell不同的導入語句有時

文件安排1

StackOverflow 
| card.py 
| test_card.py 

結果:無論以下命令挨一個ImportError

$ python3 test_card.py 
$ pytest 

文件的安排2

StackOverflow 
| __init__.py 
| card.py 
| test_card.py 

結果:如果我離開import語句一樣,$ python3 test_card.py仍然有效,但$ pytest遭受的導入錯誤。

如果我改用import StackOverflow.card as crd pytest重新開始工作,但由於ImportError,我無法將其作爲腳本運行。

我意識到在本例中我不需要__init__.py文件,但它只是大型程序的一部分。還有人指出,第二項進口聲明顯然是錯誤的。那麼我怎樣才能用pytest來處理原始的import語句?

card.py的全文:

#Created by Patrick Cunfer 
#2017-07-15 


class Card(object): 
    def __init__(self, value, suit): 
     ''' 
     Sets the card's value and suit 
     param value: An integer from 1 to 13 
     param suit: A character representing a suit 
     ''' 
     self.value = value 
     self.suit = suit 


    def __str__(self): 
     return str(self.value) + " of " + str(self.suit) 

的test_card.py

#Created by Patrick Cunfer 
#2017-07-15 


# First one breaks pytest, second one breaks shell 
# import card as crd 
# import StackOverflow.card as crd 


def test_Card(): 
    test = crd.Card(5, 'S') 
    assert test.value == 5 
    assert test.suit == 'S' 
    assert str(test) == "5 of S" 
    del test 


if __name__ == "__main__": 
    #Unit test found a bug? Lets isolate it! 

    print("Test 1") 
    test = crd.Card(5, 'S') 

    print(test.suit) 
    print("Expect 'S'") 
    print() 

    #etc. 

回答

0

全文如果你想使用__init__.py你的情況,你有追加的父目錄的路徑StackOverflow到sys,如下:

import sys 
project_dir = 'path to the parent dir of StackOverflow' 
sys.path.append(project_dir) 

然後你將能夠使用import StackOverflow.card as crd


您當前import StackOverflow.card as crd語句的意思是,你有一個名爲StackOverflowStackOverflow目錄本身內部的其他目錄; import語句是假設你的目錄結構看起來是這樣的(這不是你的情況下):

StackOverflow 
    | test_card.py 
    | StackOverflow 
     | __init__.py 
     | card.py 

不管怎樣,在你的情況,你不需要使用__init__.py,因爲你是內導入另一個腳本您從中導入的相同目錄。 __init__.py通常用於在目錄之外導入腳本。

在此link中,您可以找到有關如何使用__init__.py文件的文檔。

+0

我知道我不需要這個例子的init文件,但是對於我的真實程序,我是這樣做的。 –

+0

我的回答是否解決了您的問題或錯誤? – otayeby

+0

部分地,它解決了我對於應該如何使用import語句的困惑,但它沒有解決pytest在以這種方式使用時不起作用的事實。我的文件結構看起來不像你的回答描述(我重新檢查)。 –