class TestRegisteringDataSource(unittest.TestCase):
    """
    Tests for `RegisteringDataSource`.
    """
    def setUp(self):
        self.temp_directory = mkdtemp(suffix=TestRegisteringDataSource.__name__)
        self.source = StubRegisteringDataSource(self.temp_directory, int)
        self.source.is_data_file = MagicMock(return_value=True)

    def tearDown(self):
        self.source.stop()
        shutil.rmtree(self.temp_directory)

        listenable = registration_event_listenable_map[int]
        for listener in listenable.get_listeners():
            listenable.remove_listener(listener)

    def test_extract_data_from_file(self):
        listener = MagicMock()
        registration_event_listenable_map[int].add_listener(listener)

        rule_file_location = self._create_data_file_in_temp_directory()
        with open(rule_file_location, 'w') as file:
            file.write("from hgicommon.data_source import register\n"
                       "register(123)\n"
                       "register(456)")

        loaded = self.source.extract_data_from_file(rule_file_location)

        listener.assert_has_calls([
            call(RegistrationEvent(123, RegistrationEvent.Type.REGISTERED)),
            call(RegistrationEvent(456, RegistrationEvent.Type.REGISTERED))
        ])
        self.assertEqual(loaded, [123, 456])

    def test_extract_data_from_file_with_corrupted_file(self):
        rule_file_location = self._create_data_file_in_temp_directory()
        with open(rule_file_location, 'w') as file:
            file.write("~")

        logging.root.setLevel(level=logging.ERROR)
        self.assertRaises(Exception, self.source.extract_data_from_file, rule_file_location)

    def test_extract_data_from_file_with_wrong_file_extension(self):
        rule_file_location = self._create_data_file_in_temp_directory()
        new_rule_file_location = rule_file_location + "c"
        os.rename(rule_file_location, new_rule_file_location)

        logging.root.setLevel(level=logging.ERROR)
        self.assertRaises(Exception, self.source.extract_data_from_file, new_rule_file_location)

    def _create_data_file_in_temp_directory(self) -> str:
        """
        Creates a data file in the temp directory used by this test.
        :return: the file path of the created file
        """
        temp_file_location = mkstemp()[1]
        rule_file_location = "%s.py" % temp_file_location
        os.rename(temp_file_location, rule_file_location)
        return rule_file_location
 def setUp(self):
     self.temp_directory = mkdtemp(suffix=TestRegisteringDataSource.__name__)
     self.source = StubRegisteringDataSource(self.temp_directory, int)
     self.source.is_data_file = MagicMock(return_value=True)