簡體   English   中英

pytest:如何制作專用的測試目錄

[英]pytest: how to make dedicated test directory

我想要以下項目結構:

|--folder/
|  |--tests/
|  |--project/

我們寫一個簡單的例子:

|--test_pytest/
|  |--tests/
|  |  |--test_sum.py
|  |--t_pytest/
|  |  |--sum.py
|  |  |--__init__.py

總和.py:

def my_sum(a, b):
    return a + b

test_sum.py:

from t_pytest.sum import my_sum
def test_my_sum():
    assert my_sum(2, 2) == 5, "math still works"

讓我們運行它:

test_pytest$ py.test ./
========== test session starts ===========
platform linux -- Python 3.4.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /home/step/test_pytest, inifile: 
collected 0 items / 1 errors 

================= ERRORS =================
___ ERROR collecting tests/test_sum.py ___
tests/test_sum.py:1: in <module>
    from t_pytest import my_sum
E   ImportError: No module named 't_pytest'
======== 1 error in 0.01 seconds =========

它看不到 t_pytest 模塊。 它的制作方式類似於 httpie:

https://github.com/jkbrzt/httpie/

https://github.com/jkbrzt/httpie/blob/master/tests/test_errors.py

為什么? 我該如何糾正?

另一種方法是通過在文件夾測試中添加 __init__.py 文件來使測試成為一個模塊。 最受歡迎的 python lib 請求之一https://github.com/kennethreitz/requests在他們的單元測試文件夾測試中以這種方式進行。 您不必將 PYTHONPATH 導出到您的項目來執行測試。

限制是您必須在示例項目的“test_pytest”目錄中運行 py.test 命令。

還有一件事,示例代碼中的導入行是錯誤的。 應該是

from t_pytest.sum import my_sum

謝謝你,喬恩夏普。 Py.test 沒有魔法,我需要自己讓我的包可以導入。 有一種可能的解決方案:

   $ export PYTHONPATH="${PYTHONPATH}: [Path to folder with my module]"   

( PYTHONPATH 是 sys.path 的路徑源之一)
如果我需要永久進行此更改,則需要將此字符串添加到~/.bashrc

試試這個:

# in bash/zsh shell
test_pytest$ PYTHONPATH=. pytest

# in fish shell
test_pytest$ env PYTHONPATH=. pytest

它是一樣的東西@stepuncius在點,什么這個答案是指在一個要點 我只是想把它放在一個干凈的答案中。 對於小型項目,這是一個簡單的解決方案,無需干預數據包模塊結構或setup.py等。

使用 pytest:

if __name__ == '__main__':
     import pytest
     pytest.main(['-x', 'tests', '--capture', 'sys'])

# Note: tests is the directory name

這可能有助於解決您的unittest問題

假設我們有名為run_tests.py啟動腳本

run_tests.py的代碼:

import unittest

if __name__ == '__main__':
    # use the default shared TestLoader instance
    test_loader = unittest.defaultTestLoader

    # use the basic test runner that outputs to sys.stderr
    test_runner = unittest.TextTestRunner()

    # automatically discover all tests in the current dir of the form test*.py
    # NOTE: only works for python 2.7 and later
    test_suite = test_loader.discover('./tests')

    # run the test suite
    test_runner.run(test_suite)

您只需將./tests替換為包含所有測試腳本的頂級目標目錄(絕對路徑)

你只需像這樣運行這個文件

python run_tests.py

您將能夠看到正在運行的所有測試腳本。

暫無
暫無

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

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