0

I have a module called backend that has the population.py Python file. The population.get_distinct_persons() stores the distinct person ids into a global set:

distinct_persons = set()

def get_distinct_persons(population):

    for person in population.persons:
        distinct_persons.add(person.person_id)

if __name__ == '__main__':

    population =  Population()
    person1 = Person(1)
    population.persons.append(person1)
    person2 = Person(2)
    population.persons.append(person2)
    get_distinct_persons(population)

I need to write a unit test for function get_distinct_persons that checks if the expected and actual distinct_persons are equal. I have seen this post Modifying global variables in Python unittest framework and know that Python mocking module can probably let me do this, but have not yet found a way that works. Please share your ideas and thoughts. Thanks!

Community
  • 1
  • 1
Malgi
  • 680
  • 1
  • 7
  • 20
  • 1
    If your unit test has access to `get_distinct_persons`, it has access to `distinct_persons`; both are names bound in the module scope. – chepner Apr 13 '16 at 17:03
  • @chepner - Thanks for your comment. But if I have get_distinct_persons(self._population) in test_get_distinct_persons(self) and then do assert_that(distinct_persons, set([1, 2])), I will get the AssertionError because the distinct_persons is set([]). – Malgi Apr 13 '16 at 17:23
  • You're going to have to show exactly how you are setting up and running the test. – chepner Apr 13 '16 at 17:53
  • You were right. I had the access to the global variable distinct_persons! The test data was not correct. – Malgi Apr 13 '16 at 18:17
  • I have a Query on the same concept.. While testing a function which updates a global variable.. how do i get the tested function access the global variable when the tested function is invoked.. I am getting a key error while the test is trying to access the global variable is the testscript. – Bikiran Das Oct 30 '19 at 10:55

0 Answers0