3

I have a python function that asks if user wants to use current file, or select a new one. I need to test it. Here is the function:

def file_checker(self):
    file_change = raw_input('If you want to overwite existing file ?(Y/N) ')

    if (file_change == 'y') or (file_change == 'Y') or (file_change == 'yes'):
        logging.debug('overwriting existing file')

    elif file_change.lower() == 'n' or (file_change == 'no'):
        self.file_name = raw_input('enter new file name: ')
        logging.debug('created a new file')
    else:
        raise ValueError('You must chose yes/no, exiting')
    return os.path.join(self.work_dir, self.file_name)

I've donr the part when user selects yes, but I dont know how to test the 'no' part:

def test_file_checker(self):
    with mock.patch('__builtin__.raw_input', return_value='yes'):
        assert self.class_obj.file_checker() == self.fname
    with mock.patch('__builtin__.raw_input', return_value='no'):
    #what should I do here ? 
1
  • Incidentally, wouldn't it make more sense to loop until the user selects "yes" or "no", instead of immediately exiting if the user makes a mistake? Commented Feb 6, 2014 at 14:55

1 Answer 1

2

According to mock documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable. The side_effect can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a StopIteration is raised):

So the no part can be expressed as follow:

with mock.patch('__builtin__.raw_input', side_effect=['no', 'file2']):
    assert self.class_obj.file_checker() == EXPECTED_PATH
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.