簡體   English   中英

放置python單元測試的位置

[英]Where to place python unittests

我有一個目錄結構如下:

DirA
    __init__.py
    MyClass.py
    unittests   <------------------directory
        MyClassTest.py

MyClassTest.py是可執行的:

import unittest
from . import MyClass    

class MyClassTestCase(unittest.TestCase):
    """ Testcase """

...
.....

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

我收到錯誤“父模塊''未加載,無法執行相對導入”的行:

from . import MyClass

我想將unittests放在被測模塊旁邊的'unittests'目錄中。 有沒有辦法做到這一點,並有權訪問我正在測試的父目錄中的所有模塊?

您是否嘗試過像這樣運行測試:

cd DirA
python -m unittest discover unittests "*Test.py"

這應該正確找到您的模塊。 請參閱測試發現

使用您想要的任何布局,具體取決於您自己的首選項以及您希望導入模塊的方式:

要查找unittests文件夾,由於名稱不是常規名稱(默認情況下單元測試腳本查找test文件夾),您可以使用unittest模塊的discover選項來告訴如何查找測試腳本:

python -m unittest discover unittests

需要注意的是,第一unittest是Python模塊,第二unittests (用s )是你的目錄,你已經把你的測試腳本。

另一種方法是使用nosetest模塊(或其他新的單元測試模塊,如pytesttox ),它們應該自動找到你的測試腳本,無論你放在哪里:

nosetests -vv

要修復導入錯誤,您應該使用完整的相對(或絕對)路徑:

from ..MyClass import MyClass # Relative path from the unittests folder
from MyClass import MyClass # Absolute path from the root folder, which will only work for some unit test modules or if you configure your unit test module to run the tests from the root

建議的結構,就是看看你的結構:

my_app
    my_pkg
        __init__.py
        module_foo.py
    test
        __init__.py
        test_module_foo.py
    main.py

my_app運行所有內容,這樣您將在測試代碼和核心代碼之間使用所有相同的模塊引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM