如果不等于真实值则发出警报 num_steps

Alert if not equal to the true value num_steps

我不太擅长 "unittest" 话题。我想创建一个单元测试以便说 "Hey body, this is the wrong (or right) answer because blabla!"。我需要进行单元测试,因为我花了 3 MF 周才找到为什么机器学习模型中的预测不起作用!因此,我希望以后避免此类错误。

问题:

  1. 如何让代码在 len(X) - len(pred_values) 不等于 num_step 时提醒我?
  2. 我是否需要创建单元测试文件来收集所有单元测试,例如unittest.py?
  3. 我们需要将单元测试放在远离主代码的地方吗?

1. 测试代码可以通过断言的方式提醒您。在你的测试中,你可以使用 self.assertEqual()

self.assertEqual(len(X) - len(pred_values), num_step)

2. 是的,您通常会将 TestCase 类 收集到前缀为 test_ 的模块中。因此,如果被测代码位于名为 foo.py 的模块中,您可以将测试放在 test_foo.py 中。 在 test_foo.py 中,您可以创建多个 TestCase 类 将相关测试组合在一起。

3. 将测试与主代码分开是个好主意,尽管这不是强制性的。您可能想要分离测试的原因包括(引用自文档):

  • The test module can be run standalone from the command line.
  • The test code can more easily be separated from shipped code.
  • There is less temptation to change test code to fit the code it tests without a good reason.
  • Test code should be modified much less frequently than the code it tests.
  • Tested code can be refactored more easily.
  • Tests for modules written in C must be in separate modules anyway, so why not be consistent?
  • If the testing strategy changes, there is no need to change the source code.

official docs 中有更多信息。