Mocking file objects or iterables in python
Which way is proper for mocking and testing code that iters object returned by open() , using mock library? whitelist_data.py : WHITELIST_FILE = "testdata.txt" format_str = lambda s: s.rstrip().lstrip('www.') whitelist = None with open(WHITELIST_FILE) as whitelist_data: whitelist = set(format_str(line) for line in whitelist_data) if not whitelist: raise RuntimeError("Can't read data from %s file" % WHITELIST_FILE) def is_whitelisted(substr): return 1 if format_str(substr) in whitelist else 0 Here's how I try to test it. import unittest import mock TEST_DATA = """ domain1.com domain2.com