0

I am trying to write an unit test for a function that deals with the argparsers from the users.

My function:

def __init_parser() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description='Parsing arguments...',
    )

    parser.add_argument('--task_id', '-t', dest='task_id', action="store", type=str, required=True)

    return parser.parse_args()

Test

@pytest.mark.parametrize('task_id', ('--task_id', '-t'))
def test__init_parser_with_job_id(capsys, task_id):

    args = __init_parser()

The error _jb_pytest_runner.py: error: the following arguments are required: --task_id/-t

How can I achieve this passing the number of task_id in the body of the test function?

2
  • 1
    Problem is that unittest also looks at sys.argv. Commented Aug 19, 2022 at 7:34
  • you are correct, I replied my question mocking the sys.argv Commented Aug 19, 2022 at 8:09

1 Answer 1

1

As the comment of @hpaulj, the function looks for the argv, so in this case it is necessary to mock it and then proceed with the asserts.

def test__init_parser(monkeypatch):
    task_id = '258'

    with mock.patch.object(sys, 'argv', ['startup.py', '--task_id', '258'):
        args = __init_parser()
        job_id = getattr(args, 'task_id')
        assert task_id == '258'
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.