0

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...?

Abe
  • 22,738
  • 26
  • 82
  • 111
  • You can use `pytest` and `pytest-flask` for general Flask testing. See [this answer](http://stackoverflow.com/questions/23988853/how-to-mock-set-system-date-in-pytest) for `datetime.datetime.now()` spoofing. – Harrison Grodin Feb 26 '17 at 06:43

2 Answers2

1

You can substitute datetime.now() with a mock implementation. For example in Python 3 there's the unittest.mock which implements this approach.

mshrbkv
  • 309
  • 1
  • 5
0

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.

Abe
  • 22,738
  • 26
  • 82
  • 111