def setUp(self): with open("simple.json", "w") as fp: fp.write(""" {"home": "mydata", "processes": 4, "force": true, "extra": ["foo", "bar"], "expires": "2014-10-15", "lastrun": "2014-10-15 14:32:07"} """) with open("complex.json", "w") as fp: fp.write(""" {"home": "mydata", "processes": 4, "force": true, "extra": ["foo", "bar"], "mymodule": {"force": false, "extra": ["foo", "baz"], "expires": "2014-10-15", "arbitrary": { "nesting": { "depth": "works" } } }, "extramodule": {"unique": true} } """) self.simple = JSONFile("simple.json") self.complex = JSONFile("complex.json")
class TestJSONFile(unittest.TestCase, TestConfigSourceHelper): supported_types = (str, int, bool, list) def setUp(self): with open("simple.json", "w") as fp: fp.write(""" {"home": "mydata", "processes": 4, "force": true, "extra": ["foo", "bar"], "expires": "2014-10-15", "lastrun": "2014-10-15 14:32:07"} """) with open("complex.json", "w") as fp: fp.write(""" {"home": "mydata", "processes": 4, "force": true, "extra": ["foo", "bar"], "mymodule": {"force": false, "extra": ["foo", "baz"], "expires": "2014-10-15", "arbitrary": { "nesting": { "depth": "works" } } }, "extramodule": {"unique": true} } """) self.simple = JSONFile("simple.json") self.complex = JSONFile("complex.json") def tearDown(self): os.unlink("simple.json") os.unlink("complex.json") def test_get(self): self.assertEqual(self.simple.get("home"), "mydata") self.assertEqual(self.simple.get("processes"), 4) self.assertEqual(self.simple.get("force"), True) self.assertEqual(self.simple.get("extra"), ['foo', 'bar']) self.assertEqual(self.simple.get("expires"), "2014-10-15") self.assertEqual(self.simple.get("lastrun"), "2014-10-15 14:32:07") def test_typed(self): for key in self.simple.keys(): # JSON can type ints, bools and lists if key in ("processes", "force", "extra"): self.assertTrue(self.simple.typed(key)) else: self.assertFalse(self.simple.typed(key)) def test_write(self): self.maxDiff = None cfg = LayeredConfig(self.complex) cfg.mymodule.expires = date(2014, 10, 24) # calling write for any submodule will force a write of the # entire config file LayeredConfig.write(cfg.mymodule) want = """{ "extra": [ "foo", "bar" ], "extramodule": { "unique": true }, "force": true, "home": "mydata", "mymodule": { "arbitrary": { "nesting": { "depth": "works" } }, "expires": "2014-10-24", "extra": [ "foo", "baz" ], "force": false }, "processes": 4 }""" with open("complex.json") as fp: got = fp.read().replace("\r\n", "\n") self.assertEqual(want, got)