Malgi
Malgi

Reputation: 730

How to write a unit test for a function that accesses a global dictionary created from a csv file?

I have a process_persons() Python function that accesses a global dictionary as follows:

def process_persons():
    for k, v in person_dict.items():
        # do some processing

def main():

    global person_dict        
    person_dict = {}
    reader = csv.reader(open('person_file.csv', 'r'))
    for row in reader:
        key = (row[0], row[1])
        person_dict[key] = row[2]

I have written a unit test like this:

def test_process_persons(self):
    process_persons()
    # assert that the processing is done right!

But i get the error: NameError: global name 'person_dict' is not defined. Any help is appreciated.

Please note that I cannot change the methods' signatures that i am testing!

Upvotes: 1

Views: 650

Answers (3)

Tobias Gustafsson
Tobias Gustafsson

Reputation: 297

Not exactly sure what your're trying to achive but I would probably do something like this given that the signature of the function under test is frozen.

def process_persons():
    for k, v in person_dict.items():
        # do some processing

person_dict = {}
if __name__ == '__main__':
    reader = csv.reader(open('person_file.csv', 'r'))
    for row in reader:
        key = (row[0], row[1])
        person_dict[key] = row[2]

You need to define the person_dict somewhere. Stating that it is global does not define it. global is used when you want to assign to a variable that has been defined on module level from within a function. If you did not specify global, a new, local, variable would be created in the function that would shadow the global variable. Then, when the function exits, your newly created variable would go out of scope, be garbage collected and forgotten about to no use.

Now that you have the person_dict defined on the module level you can simply assign to it from your test code before calling process_persons to vary the input data.

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36043

NameError: global name 'person_dict' is not defined

Well, that's because you didn't define it. How is it supposed to know what it is? You say person_dict[key] = row[2] but that doesn't automatically make it a dictionary. You have to initialise it with a value, e.g.

person_dict = {}

Which says it's an empty dictionary.

There is also no need for the global declaration. You're executing this as the top level of the file (i.e. not inside a function or a class) so it can be worked with normally.

Upvotes: 1

Aaron
Aaron

Reputation: 2305

I believe it's quite literally undefined. Please try replacing global person_dict with:

person_dict = {}

Upvotes: 0

Related Questions