What is a good way to open configs or files during unit test in python?
<p>I am wondering what is a good way to read config or local file during the unit testing.</p>

<p>I think it could be either to write the test config file during time. For example:</p>

<pre><code>def setUp(self):
    self.config = ConfigParser.RawConfigParser()
    self.config.add_section('TestingSection')
    self.config.set('TestingSection', 'x', '1')

    with open('local_file.txt', 'w') as f:
        f.write('testing_value')
</code></pre>

<p>or files could be prepared before testing, and we just open them during testing, for example:</p>

<pre><code>def setUp(self):
    self.config = ConfigParser.RawConfigParser()
    self.config('local_config_file_path')

    with open('local_file.txt', 'r') as f:
        self.testing_value = f.read()
</code></pre>

<p>I am not sure which is the better way to read files during the unit testing, and hope some experts can help me.</p>

<p>If you have better approach of it, please share with me.</p>

<p>Thank you.</p>

<p>A good way is to not have to open them at all.</p>

<p>For your functions relying on a config file, you could create a fake object that implements the required methods that your particular function relies on.  It might just be a <code>get</code> method, that supports getting a "section".</p>

<p>This is exploiting <a href="https://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a>.  Your python functions don't care what the actual object they are getting, AS LONG as it implements the config parser methods it expects.</p>

<p>At some point you have to test the "edge" of your application, the entry point.  I'm guessing that the entry point function is executed and it loads and parses the config file from the file system.  A single test should be able to test this, as config parser is already tested, in python core. </p>

<p>In this test I would create a <a href="https://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile" rel="nofollow">named temporary file</a>, and use that files path as input into your main function, to make sure that it can at least execute without error.  This may technically be an integration test as it interacts with the filesystem.  </p>

python unit-testing python-unittest