Python: How to apply mock in dataclass?

Asked

Viewed 32 times

0

I have following code :

import unittest
import unittest.mock as mock
from dataclasses import dataclass

@dataclass
class Config:
    system: str = platform.system().lower()

class TestConfig(unittest.TestCase):
    def test_Config_linux(self):
        system = 'linux'
        with mock.patch('platform.system', return_value=system), \
                mock.patch.dict(os.environ, {'INCOLUMEPY_SYSTEM': system}):

            op_cfg = configure.Config()
            self.assertEqual(system, op_cfg.system)

    def test_Config_win(self):
        system = 'windows'
        with mock.patch('platform.system', return_value=system), \
                mock.patch.dict(os.environ, {'INCOLUMEPY_SYSTEM': system}):
            config()
            op_cfg = configure.Config()
            self.assertEqual(system, op_cfg.system)

    def test_Config_mac(self):
        system = 'mac'
        with mock.patch('platform.system', return_value=system), \
                mock.patch.dict(os.environ, {'INCOLUMEPY_SYSTEM': system}):
            op_cfg = configure.Config()
            self.assertEqual(system, op_cfg.system)

In this specific case the instance dataclass ignores the parameters passed via mock and reads the operating system.

How can I get around this situation?

1 answer

1

This is because the class body is executed at the time of file interpretation, and you mock after that has happened (too late). My suggestion is to make the mock directly from your dataclass:

with patch.object(Config, 'system', 'linux'):
    print(Config.system)  # linux

Browser other questions tagged

You are not signed in. Login or sign up in order to post.