Python configparser.DuplicateOptionError() Examples

The following are 24 code examples of configparser.DuplicateOptionError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module configparser , or try the search function .
Example #1
Source File: outliers.py    From ee-outliers with GNU General Public License v3.0 6 votes vote down vote up
def load_analyzers():
    analyzers = list()

    for use_case_arg in settings.args.use_cases:
        for use_case_file in glob.glob(use_case_arg, recursive=True):
            if not os.path.isdir(use_case_file):
                logging.logger.debug("Loading use case %s" % use_case_file)
                try:
                    analyzers.extend(AnalyzerFactory.create_multi(use_case_file))
                except (ValueError, MissingSectionHeaderError, DuplicateSectionError, DuplicateOptionError) as e:
                    logging.logger.error("An error occured when loading %s: %s" % (use_case_file, str(e)))

    return analyzers


# pylint: disable=too-many-branches 
Example #2
Source File: settings.py    From kf2-magicked-admin with MIT License 6 votes vote down vote up
def __init__(self, config_filename, skip_setup=False, reconfigure=False):
        if not os.path.exists(config_filename) or reconfigure:
            if not reconfigure:
                info(_("No configuration was found, first time setup is "
                       "required!"))

            if not skip_setup:
                config = self.construct_config_interactive()
            else:
                config = self.construct_config_template()

            with open(config_filename, 'w') as config_file:
                config.write(config_file)

            if skip_setup:
                info(_("Guided setup was skipped, a template has been "
                       "generated."))
                die(_("Setup is not complete yet, please amend '{}' with your "
                      "server details.").format(CONFIG_PATH_DISPLAY))

        try:
            self.config = configparser.ConfigParser()
            self.config.read(config_filename)

        except configparser.DuplicateOptionError as e:
            fatal(_("Configuration error(s) found!\nSection '{}' has a "
                    "duplicate setting: '{}'.").format(e.section, e.option))
            die(CONFIG_DIE_MESG, pause=True)

        config_errors = self.validate_config(self.config)

        if config_errors:
            fatal(_("Configuration error(s) found!"))
            for error in config_errors:
                print("\t\t" + error)
            die(CONFIG_DIE_MESG, pause=True) 
Example #3
Source File: Preferences.py    From Uranium with GNU Lesser General Public License v3.0 6 votes vote down vote up
def deserialize(self, serialized: str) -> None:
        """Extract data from string and store it in the Configuration parser."""

        updated_preferences = self.__updateSerialized(serialized)
        self._parser = configparser.ConfigParser(interpolation = None)
        try:
            self._parser.read_string(updated_preferences)
        except (configparser.MissingSectionHeaderError, configparser.DuplicateOptionError, configparser.DuplicateSectionError, configparser.ParsingError, configparser.InterpolationError) as e:
            Logger.log("w", "Could not deserialize preferences file: {error}".format(error = str(e)))
            self._parser = None
            return
        has_version = "general" in self._parser and "version" in self._parser["general"]

        if has_version:
            if self._parser["general"]["version"] != str(Preferences.Version):
                Logger.log("w", "Could not deserialize preferences from loaded project")
                self._parser = None
                return
        else:
            return

        self.__initializeSettings() 
Example #4
Source File: test_utils_fontmap.py    From blockdiag with Apache License 2.0 5 votes vote down vote up
def test_fontmap_duplicated_fontentry1(self):
        _config = "[fontmap]\nsansserif: %s\nsansserif: %s\n" % \
                  (self.fontpath[0], self.fontpath[1])
        config = StringIO(_config)
        with self.assertRaises(configparser.DuplicateOptionError):
            FontMap(config) 
Example #5
Source File: fusesocconfigparser.py    From fusesoc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, config_file):
        if sys.version[0] == "2":
            CP.__init__(self)
        else:
            super().__init__()
        if not os.path.exists(config_file):
            raise Exception("Could not find " + config_file)
        f = open(config_file)
        id_string = f.readline().split("=")

        if id_string[0].strip().upper() in ["CAPI", "SAPI"]:
            self.type = id_string[0]
        else:
            raise SyntaxError("Could not find API type in " + config_file)
        try:
            self.version = int(id_string[1].strip())
        except ValueError:
            raise SyntaxError("Unknown version '{}'".format(id_string[1].strip()))

        except IndexError:
            raise SyntaxError("Could not find API version in " + config_file)
        if sys.version[0] == "2":
            exceptions = (configparser.ParsingError, configparser.DuplicateSectionError)
        else:
            exceptions = (
                configparser.ParsingError,
                configparser.DuplicateSectionError,
                configparser.DuplicateOptionError,
            )
        try:
            if sys.version[0] == "2":
                self.readfp(f)
            else:
                self.read_file(f)
        except configparser.MissingSectionHeaderError:
            raise SyntaxError("Missing section header")
        except exceptions as e:
            raise SyntaxError(e.message) 
Example #6
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_duplicateoptionerror(self):
        import pickle
        e1 = configparser.DuplicateOptionError('section', 'option', 'source',
            123)
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            pickled = pickle.dumps(e1, proto)
            e2 = pickle.loads(pickled)
            self.assertEqual(e1.message, e2.message)
            self.assertEqual(e1.args, e2.args)
            self.assertEqual(e1.section, e2.section)
            self.assertEqual(e1.option, e2.option)
            self.assertEqual(e1.source, e2.source)
            self.assertEqual(e1.lineno, e2.lineno)
            self.assertEqual(repr(e1), repr(e2)) 
Example #7
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_duplicate_option_error(self):
        error = configparser.DuplicateOptionError('section', 'option')
        self.assertEqual(error.section, 'section')
        self.assertEqual(error.option, 'option')
        self.assertEqual(error.source, None)
        self.assertEqual(error.lineno, None)
        self.assertEqual(error.args, ('section', 'option', None, None))
        self.assertEqual(str(error), "Option 'option' in section 'section' "
                                     "already exists") 
Example #8
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_case_sensitivity_conflicts(self):
        ini = textwrap.dedent("""
            [common]
            option = value
            Option = Value

            [Common]
            option = a better ${common:option}
            Option = A Better ${common:Option}

            [random]
            foo = ${common:option} redefined
            Foo = ${Common:Option} Redefined
        """).strip()
        with self.assertRaises(configparser.DuplicateOptionError):
            cf = self.fromstring(ini)

        # raw options
        cf = self.fromstring(ini, optionxform=lambda opt: opt)
        eq = self.assertEqual
        eq(cf['common']['option'], 'value')
        eq(cf['common']['Option'], 'Value')
        eq(cf['Common']['option'], 'a better value')
        eq(cf['Common']['Option'], 'A Better Value')
        eq(cf['random']['foo'], 'value redefined')
        eq(cf['random']['Foo'], 'A Better Value Redefined') 
Example #9
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_weird_errors(self):
        cf = self.newconfig()
        cf.add_section("Foo")
        with self.assertRaises(configparser.DuplicateSectionError) as cm:
            cf.add_section("Foo")
        e = cm.exception
        self.assertEqual(str(e), "Section 'Foo' already exists")
        self.assertEqual(e.args, ("Foo", None, None))

        if self.strict:
            with self.assertRaises(configparser.DuplicateSectionError) as cm:
                cf.read_string(textwrap.dedent("""\
                    [Foo]
                    will this be added{equals}True
                    [Bar]
                    what about this{equals}True
                    [Foo]
                    oops{equals}this won't
                """.format(equals=self.delimiters[0])), source='<foo-bar>')
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<foo-bar>' "
                                     "[line  5]: section 'Foo' already exists")
            self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))

            with self.assertRaises(configparser.DuplicateOptionError) as cm:
                cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<dict>': option "
                                     "'opt' in section 'Bar' already exists")
            self.assertEqual(e.args, ("Bar", "opt", "<dict>", None)) 
Example #10
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_duplicateoptionerror(self):
        import pickle
        e1 = configparser.DuplicateOptionError('section', 'option', 'source',
            123)
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            pickled = pickle.dumps(e1, proto)
            e2 = pickle.loads(pickled)
            self.assertEqual(e1.message, e2.message)
            self.assertEqual(e1.args, e2.args)
            self.assertEqual(e1.section, e2.section)
            self.assertEqual(e1.option, e2.option)
            self.assertEqual(e1.source, e2.source)
            self.assertEqual(e1.lineno, e2.lineno)
            self.assertEqual(repr(e1), repr(e2)) 
Example #11
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_duplicate_option_error(self):
        error = configparser.DuplicateOptionError('section', 'option')
        self.assertEqual(error.section, 'section')
        self.assertEqual(error.option, 'option')
        self.assertEqual(error.source, None)
        self.assertEqual(error.lineno, None)
        self.assertEqual(error.args, ('section', 'option', None, None))
        self.assertEqual(str(error), "Option 'option' in section 'section' "
                                     "already exists") 
Example #12
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_case_sensitivity_conflicts(self):
        ini = textwrap.dedent("""
            [common]
            option = value
            Option = Value

            [Common]
            option = a better ${common:option}
            Option = A Better ${common:Option}

            [random]
            foo = ${common:option} redefined
            Foo = ${Common:Option} Redefined
        """).strip()
        with self.assertRaises(configparser.DuplicateOptionError):
            cf = self.fromstring(ini)

        # raw options
        cf = self.fromstring(ini, optionxform=lambda opt: opt)
        eq = self.assertEqual
        eq(cf['common']['option'], 'value')
        eq(cf['common']['Option'], 'Value')
        eq(cf['Common']['option'], 'a better value')
        eq(cf['Common']['Option'], 'A Better Value')
        eq(cf['random']['foo'], 'value redefined')
        eq(cf['random']['Foo'], 'A Better Value Redefined') 
Example #13
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_weird_errors(self):
        cf = self.newconfig()
        cf.add_section("Foo")
        with self.assertRaises(configparser.DuplicateSectionError) as cm:
            cf.add_section("Foo")
        e = cm.exception
        self.assertEqual(str(e), "Section 'Foo' already exists")
        self.assertEqual(e.args, ("Foo", None, None))

        if self.strict:
            with self.assertRaises(configparser.DuplicateSectionError) as cm:
                cf.read_string(textwrap.dedent("""\
                    [Foo]
                    will this be added{equals}True
                    [Bar]
                    what about this{equals}True
                    [Foo]
                    oops{equals}this won't
                """.format(equals=self.delimiters[0])), source='<foo-bar>')
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<foo-bar>' "
                                     "[line  5]: section 'Foo' already exists")
            self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))

            with self.assertRaises(configparser.DuplicateOptionError) as cm:
                cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<dict>': option "
                                     "'opt' in section 'Bar' already exists")
            self.assertEqual(e.args, ("Bar", "opt", "<dict>", None)) 
Example #14
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_duplicateoptionerror(self):
        import pickle
        e1 = configparser.DuplicateOptionError('section', 'option', 'source',
            123)
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            pickled = pickle.dumps(e1, proto)
            e2 = pickle.loads(pickled)
            self.assertEqual(e1.message, e2.message)
            self.assertEqual(e1.args, e2.args)
            self.assertEqual(e1.section, e2.section)
            self.assertEqual(e1.option, e2.option)
            self.assertEqual(e1.source, e2.source)
            self.assertEqual(e1.lineno, e2.lineno)
            self.assertEqual(repr(e1), repr(e2)) 
Example #15
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_duplicate_option_error(self):
        error = configparser.DuplicateOptionError('section', 'option')
        self.assertEqual(error.section, 'section')
        self.assertEqual(error.option, 'option')
        self.assertEqual(error.source, None)
        self.assertEqual(error.lineno, None)
        self.assertEqual(error.args, ('section', 'option', None, None))
        self.assertEqual(str(error), "Option 'option' in section 'section' "
                                     "already exists") 
Example #16
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_case_sensitivity_conflicts(self):
        ini = textwrap.dedent("""
            [common]
            option = value
            Option = Value

            [Common]
            option = a better ${common:option}
            Option = A Better ${common:Option}

            [random]
            foo = ${common:option} redefined
            Foo = ${Common:Option} Redefined
        """).strip()
        with self.assertRaises(configparser.DuplicateOptionError):
            cf = self.fromstring(ini)

        # raw options
        cf = self.fromstring(ini, optionxform=lambda opt: opt)
        eq = self.assertEqual
        eq(cf['common']['option'], 'value')
        eq(cf['common']['Option'], 'Value')
        eq(cf['Common']['option'], 'a better value')
        eq(cf['Common']['Option'], 'A Better Value')
        eq(cf['random']['foo'], 'value redefined')
        eq(cf['random']['Foo'], 'A Better Value Redefined') 
Example #17
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_weird_errors(self):
        cf = self.newconfig()
        cf.add_section("Foo")
        with self.assertRaises(configparser.DuplicateSectionError) as cm:
            cf.add_section("Foo")
        e = cm.exception
        self.assertEqual(str(e), "Section 'Foo' already exists")
        self.assertEqual(e.args, ("Foo", None, None))

        if self.strict:
            with self.assertRaises(configparser.DuplicateSectionError) as cm:
                cf.read_string(textwrap.dedent("""\
                    [Foo]
                    will this be added{equals}True
                    [Bar]
                    what about this{equals}True
                    [Foo]
                    oops{equals}this won't
                """.format(equals=self.delimiters[0])), source='<foo-bar>')
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<foo-bar>' "
                                     "[line  5]: section 'Foo' already exists")
            self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))

            with self.assertRaises(configparser.DuplicateOptionError) as cm:
                cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<dict>': option "
                                     "'opt' in section 'Bar' already exists")
            self.assertEqual(e.args, ("Bar", "opt", "<dict>", None)) 
Example #18
Source File: test_settings.py    From ee-outliers with GNU General Public License v3.0 5 votes vote down vote up
def test_error_on_duplicate_key_check(self):
        self.test_settings.change_configuration_path(test_whitelist_duplicate_option_file)
        result = settings.check_no_duplicate_key()
        self.assertIsInstance(result, DuplicateOptionError) 
Example #19
Source File: test_analyzer.py    From ee-outliers with GNU General Public License v3.0 5 votes vote down vote up
def test_create_multi_with_malformed_duplicate_option_strict(self):
        self.test_settings.change_configuration_path("/app/tests/unit_tests/files/analyzer_test_01.conf")

        with self.assertRaises(configparser.DuplicateOptionError):
            AnalyzerFactory.create_multi("/app/tests/unit_tests/files/use_cases/analyzer/analyzer_multi_malformed_duplicate_option.conf") 
Example #20
Source File: settings.py    From ee-outliers with GNU General Public License v3.0 5 votes vote down vote up
def check_no_duplicate_key(self):
        """
        Method to check if some duplicates are present in the configuration

        :return: the error (that contain message with duplicate), None if no duplicate
        """
        try:
            config = configparser.RawConfigParser(interpolation=None, strict=True)
            config.optionxform = str  # preserve case sensitivity in config keys, important for derived field names
            config.read(self.args.config)
        except (configparser.DuplicateOptionError, configparser.DuplicateSectionError) as err:
            return err
        return None 
Example #21
Source File: config_parser.py    From vimiv with MIT License 4 votes vote down vote up
def parse_keys(keyfiles=None, running_tests=False):
    """Check for a keyfile and parse it.

    Args:
        keyfiles: List of keybinding files. If not None, use this list instead
            of the default files.
        running_tests: If True running from testsuite. Do not show error popup.
    Return:
        Dictionary of keybindings.
    """
    if not keyfiles:
        keyfiles = \
            ["/etc/vimiv/keys.conf",
             os.path.join(get_user_config_dir(), "vimiv/keys.conf"),
             os.path.expanduser("~/.vimiv/keys.conf")]
    # Read the list of files
    keys = configparser.ConfigParser()
    try:
        # No file for keybindings found
        if not keys.read(keyfiles):
            message = "Keyfile not found. Exiting."
            error_message(message, running_tests=running_tests)
            sys.exit(1)
    except configparser.DuplicateOptionError as e:
        message = e.message + ".\n Duplicate keybinding. Exiting."
        error_message(message, running_tests=running_tests)
        sys.exit(1)

    # Get the keybinding dictionaries checking for errors
    try:
        keys_image = keys["IMAGE"]
        keys_thumbnail = keys["THUMBNAIL"]
        keys_library = keys["LIBRARY"]
        keys_manipulate = keys["MANIPULATE"]
        keys_command = keys["COMMAND"]
    except KeyError as e:
        message = "Missing section " + str(e) + " in keys.conf.\n" \
                  "Refer to vimivrc(5) to fix your config."
        error_message(message, running_tests=running_tests)
        sys.exit(1)

    # Update the dictionaries of every window with the keybindings that apply
    # for more than one window
    def update_keybindings(sections, keydict):
        """Add keybindings from generic sections to keydict."""
        for section in sections:
            if section in keys:
                print("Section", section, "is deprecated and will be removed in"
                      " a future version.")
                keydict.update(keys[section])
    update_keybindings(["GENERAL", "IM_THUMB", "IM_LIB"], keys_image)
    update_keybindings(["GENERAL", "IM_THUMB"], keys_thumbnail)
    update_keybindings(["GENERAL", "IM_LIB"], keys_library)

    # Generate one dictionary for all and return it
    keybindings = {"IMAGE": keys_image,
                   "THUMBNAIL": keys_thumbnail,
                   "LIBRARY": keys_library,
                   "MANIPULATE": keys_manipulate,
                   "COMMAND": keys_command}
    return keybindings 
Example #22
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_source_as_bytes(self):
        """Issue #18260."""
        lines = textwrap.dedent("""
        [badbad]
        [badbad]""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateSectionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  2]: section 'badbad' "
            "already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        bad = bad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateOptionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  3]: option 'bad' in section "
            "'badbad' already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.ParsingError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "Source contains parsing errors: b'badbad'\n\t[line  2]: '= bad'"
        )
        lines = textwrap.dedent("""
        [badbad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.MissingSectionHeaderError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "File contains no section headers.\nfile: b'badbad', line: 1\n"
            "'[badbad'"
        ) 
Example #23
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def test_source_as_bytes(self):
        """Issue #18260."""
        lines = textwrap.dedent("""
        [badbad]
        [badbad]""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateSectionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  2]: section 'badbad' "
            "already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        bad = bad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateOptionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  3]: option 'bad' in section "
            "'badbad' already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.ParsingError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "Source contains parsing errors: b'badbad'\n\t[line  2]: '= bad'"
        )
        lines = textwrap.dedent("""
        [badbad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.MissingSectionHeaderError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "File contains no section headers.\nfile: b'badbad', line: 1\n"
            "'[badbad'"
        ) 
Example #24
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 4 votes vote down vote up
def test_source_as_bytes(self):
        """Issue #18260."""
        lines = textwrap.dedent("""
        [badbad]
        [badbad]""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateSectionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  2]: section 'badbad' "
            "already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        bad = bad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateOptionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  3]: option 'bad' in section "
            "'badbad' already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.ParsingError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "Source contains parsing errors: b'badbad'\n\t[line  2]: '= bad'"
        )
        lines = textwrap.dedent("""
        [badbad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.MissingSectionHeaderError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "File contains no section headers.\nfile: b'badbad', line: 1\n"
            "'[badbad'"
        )