1

I'm studying how to use mocking in my unit test program.

Now I have a SafeConfigParser object and I want to test what I write is correct.

After google the mocking usage of SafeConfigParser, I already know how to test the read of SafeConfigParser. But I still don't know how to verify the write of SafeConfigParser.

My idea is:

  1. Make a empty buffer.
  2. Consider a method that can set the buffer to SafeConfigParser.
  3. Call the function which include SafeConfigParser.write()
  4. Verify the buffer with my answer.

My program which need to be tested is like following:

def write_tokens_to_config(self): """Write token values to the config """ parser = SafeConfigParser() with open(self.CONFIG_PATH) as fp: parser.readfp(fp) if not parser.has_section('Token'): parser.add_section('Token') parser.set('Token', 'access_token', self._access_token) parser.set('Token', 'refresh_token', self._refresh_token) with open(self.CONFIG_PATH, 'wb') as fp: parser.write(fp) 

P.S. You can check the read part from this url: http://www.snip2code.com/Snippet/4347/

1 Answer 1

1

I finally find out a solution :).

I modify my program(ex: program.py) to the followings:

class Program(): def __init__(self): self._access_token = None self._refresh_token = None self.CONFIG_PATH = 'test.conf' def write_tokens_to_config(self): """Write token value to the config """ parser = SafeConfigParser() parser.read(self.CONFIG_PATH) if not parser.has_section('Token'): parser.add_section('Token') parser.set('Token', 'access_token', self._access_token) parser.set('Token', 'refresh_token', self._refresh_token) with open(self.CONFIG_PATH, 'wb') as f: parser.write(f) 

And my test program like this:

class TestMyProgram(unittest.TestCase): def setUp(self): from program import Program self.program = Program() def test_write_tokens_to_config(self): from mock import mock_open from mock import call self.program._access_token = 'aaa' self.program._refresh_token = 'bbb' with mock.patch('program.ConfigParser.SafeConfigParser.read'): m = mock_open() with mock.patch('__builtin__.open', m, create=True): self.program.write_tokens_to_config() m.assert_called_once_with(self.program.CONFIG_PATH, 'wb') handle = m() handle.write.assert_has_calls( [ call('[Token]\n'), call('access_token = aaa\n'), call('refresh_token = bbb\n'), ] ) 

Ref: http://docs.python.org/dev/library/unittest.mock#mock-open

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.