0

This is function to get version and using with open to read file from file path location.

def get_version(self):
    try:
        with open("file_path") as openfile:
            for line in openfile:
                sline = line.split()
                for row, column in enumerate(sline):
                    if column == "version=":
                        version = sline[row+1].strip('"')
    return version
James
  • 32,991
  • 4
  • 47
  • 70
sid
  • 1
  • 1
  • 1
  • 1
    Please format your code properly with correct indentation. – Vivek Mehta Feb 12 '20 at 08:10
  • And also this is only a part of your function because I don't see `except` block. – Charnel Feb 12 '20 at 08:11
  • Hi @sid, and welcome! It looks like there are a few similar questions, about unit testing builtin functions such as `open()`. Have a look [here](https://stackoverflow.com/q/5237693/222529) as a starting point. – Jir Feb 12 '20 at 08:17
  • except block is handled in UT part – sid Feb 12 '20 at 08:22

1 Answers1

5

You can use unittest.mock.mock_open(mock=None, read_data=None) to mock the open function.

E.g.

main.py:

class MyClass:
    def get_version(self):
        version = ''
        with open("file_path") as openfile:
            for line in openfile:
                sline = line.split()
                for row, column in enumerate(sline):
                    if column == "version=":
                        version = sline[row+1].strip('"')

        return version

test_main.py:

from main import MyClass
import unittest
from unittest.mock import mock_open, patch


class TestMain(unittest.TestCase):
    def test_get_version(self):
        m = mock_open(read_data='version= 1.0.0')
        with patch('builtins.open', m) as mocked_open:
            myclass_instace = MyClass()
            version = myclass_instace.get_version()
            self.assertEqual(version, '1.0.0')
            m.assert_called_with('file_path')


if __name__ == '__main__':
    unittest.main()

unit test results with 100% coverage:

.
----------------------------------------------------------------------
Ran 1 test in 0.011s

OK
Name                                      Stmts   Miss  Cover   Missing
-----------------------------------------------------------------------
src/stackoverflow/60183706/main.py           10      0   100%
src/stackoverflow/60183706/test_main.py      14      0   100%
-----------------------------------------------------------------------
TOTAL                                        24      0   100%

Python version: Python 3.7.5

Lin Du
  • 88,126
  • 95
  • 281
  • 483