1

I am writing a unit test for the following function:

def _parse_args():
    parser = argparse.ArgumentParser(
        description='Script to configure appliance.'
    )
    parser.add_argument('--config_file',
                        help='Path to a JSON configuration file') 
    print parser.parse_args()
    return parser.parse_args()

When I run the function when no config file is given then (verified using the print statement in the function above): parser.parse_args()=Namespace(config_file=None)

In my unit test I run the function with no config file given and include an assertEquals:

self.assertEquals(my_script._parse_args(), 'Namespace(config_file=None)')

But this produces the AssertionError:

AssertionError: Namespace(config_file=None) != 'Namespace(config_file=None)'

If I change the unit test to without the quotation marks:

self.assertEquals(my_script._parse_args(), Namespace(config_file=None))

I get a NameError:

NameError: global name 'Namespace' is not defined

Clearly using quotations is not the correct way to do this but how do I get it to assert that Namespace(config_file=None) is occurring?

0

3 Answers 3

1

Change

self.assertEquals(my_script._parse_args(), Namespace(config_file=None))

to

self.assertEquals(my_script._parse_args(), argparse.Namespace(config_file=None))

Namespace is an attribute of the argparse module which you imported. You did not import Namespace on its own.

Demo for executing your code with no arguments:

print _parse_args() == argparse.Namespace(config_file=None) # True
Sign up to request clarification or add additional context in comments.

Comments

1

Check the config_file attribute of the returned Namespace object.

self.assertIsNone(my_script._parse_args().config_file)

Comments

0

Your function _parse_args() returns a Namespace object, not a string representation of it, that you get by calling print parser.parse_args().

Let's look at your function:

def _parse_args():
    #some code
    print parser.parse_args()    <-- prints the string representation of the Namespace object 'Namespace(config_file=None)'
    return parser.parse_args()   <-- returns the Namespace object

For the object returned you can use the dot notation, to access attributes it's holding:

my_script._parse_args().config_file

and assert if it is not None:

self.assertIsNone(my_script._parse_args().config_file)

Or you can create any Namespace object by calling its constructor:

argparse.Namespace (config_file = None, another_arg='some value')

and use it in assertEqual:

self.assertEqual(my_script._parse_args(), argparse.Namespace (config_file = None))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.