samedi 20 janvier 2018

Pytest with argparse: how to test user is prompted for confirmation?

I'd got a little CLI tool, and would like to test that the user is prompted to confirm a choice. The (paraphrased) code looks like:

import sys
import argparse


def confirm():
    notification_str = "Please respond with 'y' or 'n'"
    while True:
        choice = input("Confirm [Y/n]?").lower()
        if choice in 'yes' or not choice:
            return True
        if choice in 'no':
            return False
        print(notification_str)


def parse_args(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--destructive', action='store_true')
    return parser.parse_args()


def main():
    args = parse_args(sys.argv[1:])
    if args.destructive:
        if not confirm():
            sys.exit()
    do_stuff(args)

How do I make it so I can test that the confirmation prompt is showing up in the CLI? I am using pytest as my framework.

I want to make sure that:

  1. The confirmation shows up when the destructive flag is set
  2. It doesn't show up when it isn't

I'd be using the following code in another file:

import pytest
from module_name import main


def test_user_is_prompted_when_destructive_flag_is_set():
    sys.argv['', '-d']
    main()
    assert _  # What the hell goes here?


def test_user_is_not_prompted_when_destructive_flag_not_set():
    sys.argv['',]
    main()
    assert _  # And here too?

Aucun commentaire:

Enregistrer un commentaire