I am having difficulty understanding how to unit test a function that relies on input from the CLI using argparse. How do I properly setup the unit test? Allowing my code to help illustrate...
My arg parsing:
parser = argparse.ArgumentParser()
parser.add_argument('--date_flag', type=str, choices=['P', 'C'],
help='Helps script determine which month date to check for. Previous or current month.')
args = parser.parse_args()
My function:
def create_filename_to_watch() -> str:
"""
Creates a filename string to search for given which date flag ('P' or 'C') was passed.
:return: A string value that represents the file name to watch for.
"""
current_month_year = datetime.date.today().replace(day=1)
previous_month_year = current_month_year - datetime.timedelta(days=1)
if args.date_flag == 'P':
name_to_watch_for = feed_metadata[4].replace('YYYYMM', previous_month_year.strftime('%Y%m'))
else:
name_to_watch_for = feed_metadata[4].replace('YYYYMM', current_month_year.strftime('%Y%m'))
return name_to_watch_for
My goal is to write a unit test using Python unittest to evaluate the correct string is returned given when both a 'P' or 'C' is passed on the CLI. I don't understand how to control the CLI from inside the unit test to get the function to execute the correct conditional.
CodePudding user response:
As @chepner suggested in a comment, you need to pass in the value of args.date_flag and possibly monkey patch the datetime functions to give you repeatable values.
Whenever you are using global values, the tests are harder to write because the scope of the test grows.