【问题标题】:What's the correct way to test this "setUp()" function inside this class?在这个类中测试这个“setUp()”函数的正确方法是什么?
【发布时间】:2021-01-03 22:10:25
【问题描述】:

来自《Learn Algorithmic Trading-Sebastien Donadio 和 Sourav Ghosh》一书

src full code >> https://github.com/PacktPublishing/Learn-Algorithmic-Trading/tree/master/Chapter7

我应该测试一下

TradingStrategy.py

有了这个

TradingStrategy_ut.py

我必须从 TradingStrategy_ut.py 调用 setUp() 函数来初始化 TradingStrategy 类

class TestMarketSimulator(unittest.TestCase):

    def setUp(self):
        self.trading_strategy= TradingStrategy()

我已经尝试过,但我不明白如何使它工作,因为 TradingStrategy.py 文件中的 TradingStrategy 接受 3 个参数。

class TradingStrategy:
    def __init__(self, ob_2_ts, ts_2_om, om_2_ts):
        self.orders = []
        self.order_id = 0
        self.position = 0
        self.pnl = 0
        self.cash = 10000
        self.current_bid = 0
        self.current_offer = 0
        self.ob_2_ts = ob_2_ts
        self.ts_2_om = ts_2_om
        self.om_2_ts = om_2_ts

每次调用 setUp() 函数时都会出现此错误:

x = TestMarketSimulator()
x.setUp()

Traceback (most recent call last):
  File "TradingStrategy_ut.py", line 72, in <module>
    x.setUp()
  File "TradingStrategy_ut.py", line 9, in setUp
    self.trading_strategy= TradingStrategy()
TypeError: __init__() missing 3 required positional arguments: 'ob_2_ts', 'ts_2_om', and 'om_2_ts'

【问题讨论】:

  • “我必须从 TradingStrategy_ut.py 调用 setUp() 函数来初始化 TradingStrategy 类”——不,你不需要。 unittest 将处理调用它。你应该依赖 unittest 框架来处理这些东西。
  • 您无需致电setUp。您只需要提供setUp 的正确实现,包括使用正确的参数调用TradingStrategy
  • 您正在调用 TradingStrategy__init__() 方法,该方法采用这 3 个参数。似乎安装程序试图以任何方式取代__init__(),因此您可能可以完全删除该功能
  • 谢谢大家!!

标签: python python-3.x algorithmic-trading trading


【解决方案1】:

解决方案

python3 -m unittest TradingStrategy_ut.py

还有:编辑 TradingStrategy.py

在每个参数后添加

  class TradingStrategy:
        def __init__(self, ob_2_ts=None, ts_2_om=None, om_2_ts=None): 
            self.orders = []
            self.order_id = 0
            self.position = 0
            self.pnl = 0
            self.cash = 10000
            self.current_bid = 0
            self.current_offer = 0
            self.ob_2_ts = ob_2_ts
            self.ts_2_om = ts_2_om
            self.om_2_ts = om_2_ts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    相关资源
    最近更新 更多