From e41e36b1b36abfa3c0f85c0d8d56401a5cdefa0f Mon Sep 17 00:00:00 2001
From: James Graham <J.A.Graham@soton.ac.uk>
Date: Thu, 6 Apr 2017 15:19:27 +0100
Subject: [PATCH] Add proper error message if a config file contains no
 sections

---
 pycgtool/parsers/cfg.py  | 21 +++++++++++++++++----
 test/test_parsers_cfg.py |  6 +++++-
 2 files changed, 22 insertions(+), 5 deletions(-)

diff --git a/pycgtool/parsers/cfg.py b/pycgtool/parsers/cfg.py
index 1edb079..e485b60 100644
--- a/pycgtool/parsers/cfg.py
+++ b/pycgtool/parsers/cfg.py
@@ -8,12 +8,22 @@ import os
 import collections
 
 
-class DuplicateSectionError(Exception):
+class DuplicateSectionError(KeyError):
     """
     Exception used to indicate that a section has appeared twice in a file.
     """
-    def __repr__(self):
-        return "Section {0} appears twice in file {1}.".format(*self.args)
+    def __init__(self, section, filename):
+        msg = "Section '{0}' appears twice in file '{1}'.".format(section, filename)
+        super(DuplicateSectionError, self).__init__(msg)
+
+
+class NoSectionError(KeyError):
+    """
+    Exception used to indicate that a file contains no sections.
+    """
+    def __init__(self, filename):
+        msg = "File '{0}' contains no '[]' section headers.".format(filename)
+        super(NoSectionError, self).__init__(msg)
 
 
 class CFG(collections.OrderedDict):
@@ -55,7 +65,10 @@ class CFG(collections.OrderedDict):
                     continue
 
                 toks = tuple(line.split())
-                self[curr_section].append(toks)
+                try:
+                    self[curr_section].append(toks)
+                except KeyError as e:
+                    raise NoSectionError(self.filename) from e
 
     def __enter__(self):
         return self
diff --git a/test/test_parsers_cfg.py b/test/test_parsers_cfg.py
index 442d818..1d481bd 100644
--- a/test/test_parsers_cfg.py
+++ b/test/test_parsers_cfg.py
@@ -1,6 +1,6 @@
 import unittest
 
-from pycgtool.parsers.cfg import DuplicateSectionError
+from pycgtool.parsers.cfg import DuplicateSectionError, NoSectionError
 from pycgtool.parsers import CFG
 
 
@@ -38,6 +38,10 @@ class TestParsersCFG(unittest.TestCase):
             self.assertTrue("DOPC" in cfg)
             self.assertTrue("GLY" in cfg)
 
+    def test_error_no_sections(self):
+        with self.assertRaises(NoSectionError):
+            CFG("test/data/nosections.cfg")
+
 
 if __name__ == '__main__':
     unittest.main()
-- 
GitLab