jeudi 30 janvier 2020

python: create a test for reading invalid YAML file

I am trying to create a test in Python, I want to create a mock for opening YAML file, and mock its content to be an illegal YAML and assert the exception.

I tried mocking:

    def test_illegal_yaml_file(self):
        with patch('os.path.isfile', return_value=True):
            with patch('__main__.open', mock_open(read_data='wifi_password 12345678')):
                myObj = MyClass()
                params = myObj.get_params()
                # TODO catch exception with assert here

and inside MyClass:

    def get_params(self):
        path = "configuration.yaml"
        params = None
        if os.path.isfile(path): # os.path.isfile is mocked here to be True
            params = self.get_parameters(path)
        return params

    def get_parameters(self, path):
        try:
            params = self.load_params_from_yaml(path)
        except Exception as e:
            Log.error('Invalid YAML file, error: {}'. format(e))
            return None
        return params

    @staticmethod
    def yaml_load(camera_configuration):
        return yaml.load(camera_configuration, Loader=yaml.FullLoader)

I also tried using IO straight to the inner function:

    def test_illegal_yaml_file(self):
        un_valid_yaml = io.BytesIO('param 12345678')
        params = MyClass.yaml_load(un_valid_yaml)
        self.assertIsNone(params)

and inside MyClass:

    @staticmethod
    def yaml_load(camera_configuration):
        return yaml.load(camera_configuration, Loader=yaml.FullLoader)

How can I mock it correctly so an exception of invalid YAML file is thrown?

Aucun commentaire:

Enregistrer un commentaire