简体   繁体   English

用于对依赖时间戳的Flask应用进行单元测试的模式?

[英]Patterns for unit testing a Flask app that depends on timestamps?

I have a Flask app that's part of a task scheduling system. 我有一个Flask应用,它是任务计划系统的一部分。 The business logic in many of the routes relies on the current time. 许多路线中的业务逻辑都依赖于当前时间。

@app.route("/do_stuff")
def do_stuff():
  now = datetime.datetime.now()
  call_func(request.args.get("some_arg"), now)

I need to bring these functions under test. 我需要测试这些功能。 The tests will need to spoof timestamps, so that I can verify that the app responds properly depending on when various commands arrive. 测试将需要欺骗时间戳,以便我可以根据各种命令何时到达来验证应用程序是否正确响应。

Are there standard patterns for writing these kinds of tests in Flask? 是否有用于在Flask中编写此类测试的标准模式? I can think of a bunch of clunky, non-DRY ways to do it. 我可以想到很多笨拙的,非干燥的方法。 Wondering if there are any more elegant patterns/tools...? 想知道是否还有其他优雅的图案/工具...?

You can substitute datetime.now() with a mock implementation. 您可以用模拟实现替换datetime.now() For example in Python 3 there's the unittest.mock which implements this approach. 例如,在Python 3中,有一个unittest.mock实现了这种方法。

This works, but I'd love to find something cleaner: 这可行,但是我很想找到更清洁的东西:

@app.route("/do_stuff")
def do_stuff():
  if app.debug and request.args.get("now"):
    now = request.args.get("now")
  else:
    now = datetime.datetime.now()      
  call_func(request.args.get("some_arg"), now)

With that logic around now , I can pass an optional now argument. 有了now逻辑,我可以传递一个可选的now参数。 If we're running in debug mode, then it can override the normal logic to fetch the current time. 如果我们在调试模式下运行,则它可以覆盖常规逻辑以获取当前时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM