簡體   English   中英

從腳本目錄的外部運行帶有tail.run(…)的python腳本會導致AttributeError:'module'對象沒有屬性'tests'

[英]Running a python script with nose.run(…) from outside of the script's directory results in AttributeError: 'module' object has no attribute 'tests'

我有一個帶有幾個子目錄的python應用程序。 每個子目錄都有其自己的tests.py文件。

我通過創建一個調用nose.run(...)的腳本run_unit_tests.py ,使用nose一次運行所有這些文件中的所有run_unit_tests.py nose.run(...)

如果我位於包含run_unit_tests.py的目錄中,則一切正常。 但是,如果我在文件系統上的其他位置,則它將失敗,並出現AttributeError:'module'對象沒有屬性'tests'。

這類似於我的目錄結構:

MyApp/
    foo/
        __init__.py
        tests.py
        bar/
            __init__.py
            tests.py
    run_unit_tests.py

在我的run_unit_tests.py

class MyPlugin(Plugin):
    ...

if __name__ == '__main__':
    nose.run(argv=['', 'foo.tests', '--with-my-plugin'])
    nose.run(argv=['', 'foo.bar.tests', '--with-my-plugin'])

如果我在頂部MyApp目錄中運行run_unit_tests.py ,則一切正常。

但是,如果我在文件系統上的其他文件夾中運行腳本時,腳本將失敗並顯示:

======================================================================
ERROR: Failure: AttributeError ('module' object has no attribute 'tests')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/apps/Python/lib/python2.7/site-packages/nose/loader.py", line 407, in loadTestsFromName
    module = resolve_name(addr.module)
  File "/apps/Python/lib/python2.7/site-packages/nose/util.py", line 322, in resolve_name
    obj = getattr(obj, part)
AttributeError: 'module' object has no attribute 'tests'

實際上,如果我將以下內容添加到run_unit_tests.py ,則可以正常工作:

import os
os.chdir('/path/to/MyApp')

我可以在鼻子腳本中進行哪些更改,以便可以從目錄外部運行腳本?

實際上,您在這里要小心。 因為發生這種情況的原因是,您在測試中的導入是針對/path/to/MyApp

因此,當您從該工作目錄運行測試時,相對於作為項目源的目錄,所有單元測試文件都將導入。 如果您更改目錄並從另一個位置運行,則該目錄現在成為您的根目錄,並且導入肯定會失敗。

這可能會帶來不同的意見,但是我通常會確保我的資源都來自同一項目根。 因此,如果我們在這里:

MyApp/
    foo/
        __init__.py
        tests.py
        bar/
            __init__.py
            tests.py
    run_unit_tests.py

我將在MyApp運行所有內容

此外,我會考慮創建一個tests目錄,並將所有測試放在該目錄中,以使導入更易於管理並更好地分離代碼。 但是,這只是一個意見,請不要覺得這是必需的。 無論對您有什么用,請繼續使用。

希望這可以幫助。

暫無
暫無

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

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