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!

5
  • 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. Commented Apr 13, 2016 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([]). Commented Apr 13, 2016 at 17:23
  • You're going to have to show exactly how you are setting up and running the test. Commented Apr 13, 2016 at 17:53
  • You were right. I had the access to the global variable distinct_persons! The test data was not correct. Commented Apr 13, 2016 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. Commented Oct 30, 2019 at 10:55

0

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.