簡體   English   中英

pytest:源文件和測試文件在另一個目錄中

[英]pytest: source files and test files in a different directory

我有一個項目,其中包含源代碼和測試代碼。 源代碼存儲在一個目錄中,而我的測試存儲在另一個目錄中。

root
  |- src
  | |- pkg
  | | | - __init__.py
  | | | - src1.py
  | | | - src2.py
  |- test
  | |- tests_for_pkg
  | | | - __init__.py
  | | | - first_test.py
  | | | - second_test.py

運行測試時,需要將所有源代碼導入_test.py文件中。

from pkg.src1 import src1
from pkg.src2 import src2

我想使用python -m pytest <tests>或運行腳本一次運行所有測試,但是我一直在獲取有關導入的錯誤。

我之前在Eclipse IDE中遇到了Python路徑問題,因此我選擇使用相對路徑,並根據文件夾結構中的相對路徑將它們作為外部庫添加到Python路徑中。

例如,我的包含路徑為:

../src/pkg

如何在Python命令行中/作為Python腳本實現這樣的相對路徑?

編輯:使用提供的鏈接,我能夠通過添加conftest.py文件並附加我的代碼的位置來使我的測試工作。

但是,我的實際項目具有大量的源代碼樹,如下所示:

root
| - projectdir
| | - projectone
| | | - datedir
| | | | - trunk
| | | | | - sd
| | | | | | - code
| | | | | | | src
| | | | | | | - pkg
| | | | | | | | - __init__.py
| | | | | | | | - src1.py
| | | | | | | | - src2.py
| | | | | | - model
| | | | | | | - testdir
| | | | | | | | - testware
| | | | | | | | | - unittest_pkg
| | | | | | | | | | - test
| | | | | | | | | | | - tests_for_pkg
| | | | | | | | | | | | - first_test.py
| | | | | | | | | | | | - second_test.py

conftest.py第一個源代碼樹(允許我從測試目錄運行測試):

import sys
sys.path.append('..\..\src')

conftest.py第二個源代碼樹(無法從任何目錄運行任何測試):

import sys
sys.path.append('..\..\..\..\..\..\..\code\src')

當我使用與以前完全相同的方法時,它不起作用。 conftest.py是否可以搜索src目錄有限制?

編輯:從這個問題的幫助下解決了。

我最終制作了一個批處理腳本,該腳本查找以test.py結尾的所有文件並運行它們。

@echo off
for /r %%i in (*test.py) do (
    setlocal
    set PYTHONPATH=../../../src/pkg
    python -m pytest --junitxml=%%~pi/JUnit_%%~ni.xml %%i
    endlocal
)

@RD /S /Q .pytest_cache 

為什么在運行pytest之前不將當前目錄添加到PYTHONPATH

export PYTHONPATH="$PYTHONPATH:$PWD"

或者,您可以通過以下方式將目錄添加到test .py的PYTHONPATH中:

import sys
import os
sys.path.append(os.path.abspath('../src/pkg'))

暫無
暫無

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

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