def test_confirm_match(self): name, expected = 'Simple prompt', 'expected' with capture(prompts=[('%s \(again\)' % name, expected), (name, expected)]) as c: value = prompt(name, confirm=True) self.assertEqual(value, expected)
def prompt(self): return cli.prompt(self.message, **self.kwargs)
def test_boolean_no(self): name = 'Bool prompt' with capture(prompts=[(name, 'n')]) as c: value = prompt(name, type=bool) self.assertEqual(value, False)
def test_boolean_yes(self): name = 'Bool prompt' with capture(prompts=[(name, 'yes')]) as c: value = prompt(name, type=bool) self.assertEqual(value, True)
def test_string_default(self): name = 'Simple prompt' with capture(prompts=[(name, '\n')]) as c: value = prompt(name, default='default value') self.assertEqual(value, 'default value')
def test_string_empty_allowed(self): name = 'Simple prompt' with capture(prompts=[(name, '\n')]) as c: value = prompt(name, empty=True) self.assertEqual(value, None)
def test_string(self): with capture(prompts=[('Simple prompt', 'simple value')]) as c: value = prompt('Simple prompt') self.assertEqual(value, 'simple value')
def prompt(message, empty=False, hidden=False, type=str, default=None, allowed=None, true_choices=TRUE_CHOICES, false_choices=FALSE_CHOICES, max_attempt=3, confirm=False): """Prompt user for value. :param str message: The prompt message. :param bool empty: Allow empty value. :param bool hidden: Hide user input. :param type type: The expected type. :param mixed default: The default value. :param tuple allowed: The allowed values. :param tuple true_choices: The accpeted values for True. :param tuple false_choices: The accepted values for False. :param int max_attempt: How many times the user is prompted back in case of invalid input. :param bool confirm: Enforce confirmation. """ from manager import Error if allowed is not None and empty: allowed = allowed + ('', '\n') if type is bool: allowed = true_choices + false_choices if allowed is not None: message = "%s [%s]" % (message, ", ".join(allowed)) if default is not None: message = "%s (default: %s) " % (message, default) handler = raw_input if hidden: handler = getpass.getpass attempt = 0 while attempt < max_attempt: try: value = process_value( handler("%s : " % message), empty=empty, type=type, default=default, allowed=allowed, true_choices=true_choices, false_choices=false_choices, ) break except: attempt = attempt + 1 if attempt == max_attempt: raise Error('Invalid input') if confirm: confirmation = prompt("%s (again)" % message, empty=empty, hidden=hidden, type=type, default=default, allowed=allowed, true_choices=true_choices, false_choices=false_choices, max_attempt=max_attempt) if value != confirmation: raise Error('Values do not match') return value