简体   繁体   中英

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

I have a Flask app that's part of a task scheduling system. 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? 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. For example in Python 3 there's the unittest.mock which implements this approach.

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. If we're running in debug mode, then it can override the normal logic to fetch the current time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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