Skip to content

Commit

Permalink
make Section objects arbitarily nestable
Browse files Browse the repository at this point in the history
  • Loading branch information
Samuel Walladge committed Dec 25, 2017
1 parent 0ff3146 commit 1aba372
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
8 changes: 8 additions & 0 deletions piqueserver/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,14 @@ class Section():
def __init__(self, store, name):
self.store = store
self.name = name
self.sections = {}
self.options = {}

def _validate_all(self):
for option in self.options.values():
option.validate(option.get())
for section in self.sections.values():
section._validate_all()

def get_dict(self):
return self.store.get_dict().get(self.name, {})
Expand All @@ -135,6 +138,11 @@ def set(self, name, value):
section[name] = value
self.store.set(self.name, section)

def section(self, name):
section = Section(self, name)
self.sections[name] = section
return section

def option(self, name, cast=None, default=None, validate=None):
option = Option(self, name, default, cast, validate)
self.options[name] = option
Expand Down
9 changes: 6 additions & 3 deletions tests/example_config/simple.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ name = "piqueserver instance"
game_mode = "ctf"
port = 4567

[passwords]
admin = ["adminpass1", "adminpass2", "adminpass3"]
moderator = ["modpass"]
[passwords]
admin = ["adminpass1", "adminpass2", "adminpass3"]
moderator = ["modpass"]

[squad]
respawn_time = 32
size = 5

[server.things]
thing1 = "something"
16 changes: 16 additions & 0 deletions tests/piqueserver/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,19 @@ def test_json(self):
# "name" : "piqueserver instance",
name = config.option('name')
self.assertEqual(name.get(), 'piqueserver instance')

def test_more_nested(self):
f = 'tests/example_config/simple.toml'
config.load_from_file(open(f))

server_config = config.section('server')
port = server_config.option('port')
self.assertEqual(port.get(), 4567)

thing_config = server_config.section('things')
self.assertEqual(thing_config.option('thing1').get(), 'something')

thing2 = thing_config.option('thing2')
thing2.set('something else')

self.assertEqual(thing_config.get_dict(), {'thing1': 'something', 'thing2': 'something else'})

0 comments on commit 1aba372

Please sign in to comment.