Skip to content
Snippets Groups Projects
Commit 78508b67 authored by James Graham's avatar James Graham
Browse files

Investigating JSON config files

parent ffb87277
No related branches found
No related tags found
No related merge requests found
import json
class DuplicateSectionError(Exception):
"""
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)
class Record(dict):
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, item):
return self[item]
class CFG:
def __init__(self, filename):
with open(filename) as f:
try:
self._json = json.load(f, object_hook=Record)
except ValueError:
raise DuplicateSectionError()
def __getitem__(self, item):
return Record(self._json[item])
def __contains__(self, item):
return item in self._json
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass
{"SOL":{
"beads":[
{"name":"W", "type":"P4", "atoms":["OW", "HW1", "HW2"]}
],
"bonds":[
]
}}
{"SOL":{
"beads":[
{"name":"W", "type":"P4", "atoms":["OW", "HW1", "HW2"]}
],
"bonds":[
]
}}
{"SOL":{
"beads":[
{"name":"W", "type":"P4", "atoms":["OW", "HW1", "HW2"]}
],
"bonds":[
]
}}
import unittest
from pycgtool.parsers.json import CFG, DuplicateSectionError
class TestParsersJson(unittest.TestCase):
def test_cfg_with(self):
with CFG("test/data/water.json"):
pass
def test_cfg_get_section(self):
with CFG("test/data/water.json") as cfg:
self.assertTrue("SOL" in cfg)
self.assertEqual(1, len(cfg["SOL"].beads))
bead = cfg["SOL"].beads[0]
self.assertEqual("W", bead.name)
self.assertEqual("P4", bead.type)
self.assertEqual(["OW", "HW1", "HW2"], bead.atoms)
self.assertEqual(0, len(cfg["SOL"].bonds))
def test_cfg_duplicate_error(self):
with self.assertRaises(DuplicateSectionError):
CFG("test/data/twice.json")
@unittest.expectedFailure
def test_include_file(self):
with CFG("test/data/martini.json") as cfg:
self.assertTrue("DOPC" in cfg)
self.assertTrue("GLY" in cfg)
if __name__ == '__main__':
unittest.main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment