python helper函数_用Python中的helper函数对ABC进行单元测试
我想知道是否可以在Python的測試環境中更改helper函數。我的應用程序結構如下:app/
trader/
__init__.py
strategies/
__init__.py
base_strategy.py
util.py
models/
__init__.py
base_model.py
tests/
__init__.py
strategies/
__init__.py
stub_strategy.py
test_strategies.py
models/
__init__.py
stub_model.py
其中每個base_*.py是一個抽象基類,從tests目錄中的每個stub_*.py文件繼承而來。在我的util.py文件中,有一個helper函數,它可以查看trader/strategies/models目錄并注冊所有可用的模型:
^{pr2}$
現在我的問題是:在我的BaseTradingStrategy-類中,我有一個方法,它使用existing_alpha_models列表來檢查模型是否存在。在from abc import ABC, abstractmethod
from .util import existing_alpha_models
class BaseTradingStrategy(ABC):
"""BaseTrading Code comes here"""
@abstractmethod
def some_abs_method(self):
raise NotImplementedError
def register_model(self, model_name):
if model_name not in existing_alpha_models:
raise ValueError
對于單元測試,我已經創建了存根類,它們不在trader/strategies/models目錄中,因此沒有在existing_alpha_models列表中注冊。當我想用pytest測試ABC的功能時,許多測試都失敗了,因為檢查模型可用性的方法失敗了。一個簡單的解決方案是將存根類放在我的應用程序的trader目錄中,但我寧愿將我的測試代碼與應用程序的其余部分分開。我可能還可以將existing_alpha_models作為基類的屬性,但是除了讓測試通過之外,我并不認為這樣做有什么意義。有沒有一種方法可以在existing_alpha_models中注入存根類進行單元測試,這樣ABC的測試在不改變基類的情況下不會失敗嗎?在
------------編輯------------------
我現在有兩個我的測試代碼的工作版本。一個是使用@hoefling的verison,我只需將alpha_models添加到existing_alpha_models列表中:from tests.strategies import StubTradingStrategy
from tests.strategies.alpha_models import StubModel, StubModel2, StubModel3
from trader.strategies.util import existing_alpha_models
existing_alpha_models.extend(["StubModel", "StubModel2", "StubModel3"])
還有一個版本,我將模型添加到alpha_models模塊并重新加載2個模塊:import importlib
from trader.strategies import alpha_models
from tests.strategies.alpha_models import StubModel, StubModel2, StubModel3
setattr(alpha_models, "StubModel", StubModel)
setattr(alpha_models, "StubModel2", StubModel2)
setattr(alpha_models, "StubModel3", StubModel3)
from nutrader.strategies import util
import nutrader.strategies.base_strategy
importlib.reload(util)
importlib.reload(nutrader.strategies.base_strategy)
from tests.strategies import StubTradingStrategy
第二個版本的優點是它允許我實際測試util代碼,但是它也在我的測試代碼中引入了潛在的風險,因為某些模塊存在2個版本,這在生產環境中不是這樣。這是個好主意,還是應該在測試環境的第一個版本中保留它?在
總結
以上是生活随笔為你收集整理的python helper函数_用Python中的helper函数对ABC进行单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: xpath helper用法
- 下一篇: 耦合是什么?如何做到解耦?