Let the configuration object handle comments and blank lines

- Configuration : Use a parallel list of lines to recreate comments and blank lines
 - Test : Improve the test for configuration objects (checking removal, addition, modification). All tests are activated again, and they will use the environment variable 'HOME' to determine the home directory of the user
This commit is contained in:
LeMagnesium 2016-03-16 22:53:36 +01:00
parent 9bf45cf1b6
commit 25f9847b7d
2 changed files with 301 additions and 197 deletions

View File

@ -10,63 +10,108 @@ import os
#from errors import ConfigurationFormatError
class Configuration:
def __init__(self, file):
self.data = dict()
self.read(file)
self.file = file
def __init__(self, file):
self.data = dict()
self.lines = []
self.read(file)
self.file = file
def __contains__(self, key):
return key in self.data
def __contains__(self, key):
return key in self.data
def __getitem__(self, key):
return self.data.get(key)
def __getitem__(self, key):
return self.data.get(key)
def __delitem__(self, key):
del self.data[key]
def __delitem__(self, key):
del self.data[key]
def __len__(self):
return len(self.data)
def __len__(self):
return len(self.data)
def __setitem__(self, key, val):
self.data[key] = val
def __setitem__(self, key, val):
self.data[key] = val
def read(self, file=None):
buffer = open(file or self.file)
for line in buffer.readlines():
line = line.strip("\r\n")
k = line.split("=")
def read(self, file=None):
try:
buffer = open(file or self.file)
except Exception:
return
if len(k) < 2:
continue
i = -1
for line in buffer.readlines():
i += 1
line = line.strip("\r\n")
data = " = ".join(k[1:]).strip()
if len(line) == 0:
self.lines.append((0,))
continue
if data == "true" or data == "1":
data = True
elif line[0] == '#':
self.lines.append((1, line[1:]))
continue
elif data == "false" or data == "0":
data = False
k = line.split("=")
data = " = ".join(k[1:]).strip()
self.data[k[0].strip()] = data
if data == "true" or data == "1":
data = True
def write(self, file=None):
try:
f = open(file or self.file, "w")
except Exception as err:
return None
elif data == "false" or data == "0":
data = False
for key in self.data:
f.write("{0} = {1}\n".format(key, self.data[key]))
elif data.isdigit():
data = int(data)
f.close()
return True
elif data.isdecimal():
data = float(data)
@classmethod
def open_world(cls, dir):
try:
open(dir + "/world.mt")
except Exception as err:
return None
self.data[k[0].strip()] = data
self.lines.append((2, k[0].strip()))
return cls(dir + "/world.mt")
def write(self, file=None):
try:
f = open(file or self.file, "w")
except Exception as err:
return None
#for key in self.data:
# f.write("{0} = {1}\n".format(key, self.data[key]))
for t in self.lines:
#t = self.lines[i]
if t[0] == 0:
f.write('\n')
continue
elif t[0] == 1:
f.write("#{}\n".format(t[1]))
continue
elif t[0] == 2:
if not self.data.get(t[1]):
del self.lines[self.lines.index(t)]
continue
f.write("{0} = {1}\n".format(t[1], self.data[t[1]]))
continue
for key in self.data:
if (2, key) in self.lines:
continue
f.write("{0} = {1}\n".format(key, self.data[key]))
self.lines.append((2,key))
f.close()
return True
@classmethod
def open_world(cls, dir):
try:
open(dir + "/world.mt")
except Exception as err:
return None
return cls(dir + "/world.mt")

View File

@ -13,207 +13,266 @@ from io import BytesIO
from schematics import Schematic
def testMapBlockLoad():
file = minetest.map.MapVessel("./map.sqlite")
for i in range(-4096, 4096):
res, code = file.read(i)
if not res:
continue
else:
mapb = file.load(i)
print("Read and loaded {0}: {1}".format(i, mapb), end = " \r")
file = minetest.map.MapVessel("./map.sqlite")
for i in range(-4096, 4096):
res, code = file.read(i)
if not res:
continue
else:
mapb = file.load(i)
print("Read and loaded {0}: {1}".format(i, mapb), end = " \r")
print(" -> There are in total {0} mapblocks in the map".format(len(file.get_all_mapblock_ids())), end = (' ' * 20) + '\n')
print(" --> Test successful")
print(" -> There are in total {0} mapblocks in the map".format(len(file.get_all_mapblock_ids())), end = (' ' * 20) + '\n')
print(" --> Test successful")
def testEndians():
assert(minetest.utils.readS8(BytesIO(b"\xf8")) == -8)
print(" -> readS8: OK")
assert(minetest.utils.readS16(BytesIO(b"\x9f\xff")) == -24577)
print(" -> readS16: OK")
assert(minetest.utils.readS32(BytesIO(b"\xf0\x00\x00\x00")) == -268435456)
print(" -> readS32: OK")
assert(minetest.utils.readS8(BytesIO(b"\xf8")) == -8)
print(" -> readS8: OK")
assert(minetest.utils.readS16(BytesIO(b"\x9f\xff")) == -24577)
print(" -> readS16: OK")
assert(minetest.utils.readS32(BytesIO(b"\xf0\x00\x00\x00")) == -268435456)
print(" -> readS32: OK")
assert(minetest.utils.readU8(BytesIO(b"\xf8")) == 248)
print(" -> readU8: OK")
assert(minetest.utils.readU16(BytesIO(b"\x9f\xff")) == 40959)
print(" -> readU16: OK")
assert(minetest.utils.readU32(BytesIO(b"\xf0\x00\x00\x00")) == 4026531840)
print(" -> readU32: OK")
assert(minetest.utils.readU8(BytesIO(b"\xf8")) == 248)
print(" -> readU8: OK")
assert(minetest.utils.readU16(BytesIO(b"\x9f\xff")) == 40959)
print(" -> readU16: OK")
assert(minetest.utils.readU32(BytesIO(b"\xf0\x00\x00\x00")) == 4026531840)
print(" -> readU32: OK")
print(" --> Test successful")
print(" --> Test successful")
def testGetNode():
db = minetest.map.MapInterface("./map.sqlite")
db = minetest.map.MapInterface("./map.sqlite")
u = random.randint(500, 2000)
k = random.randint(40,400)
u = random.randint(500, 2000)
k = random.randint(40,400)
db.set_maxcachesize(k)
print(" -> Maximum cache size set to {0} mapblocks".format(k))
db.set_maxcachesize(k)
print(" -> Maximum cache size set to {0} mapblocks".format(k))
s = time.time()
for i in range(u):
pos = minetest.utils.Pos({'x': random.randint(-300, 300), 'y': random.randint(-300, 300), 'z': random.randint(-300, 300)})
assert(db.get_node(pos).get_name() != "")
s = time.time()
for i in range(u):
pos = minetest.utils.Pos({'x': random.randint(-300, 300), 'y': random.randint(-300, 300), 'z': random.randint(-300, 300)})
assert(db.get_node(pos).get_name() != "")
if len(db.interface.cache) == db.get_maxcachesize():
endstr = " (MAX)\r"
else:
endstr = " \r"
if len(db.interface.cache) == db.get_maxcachesize():
endstr = " (MAX)\r"
else:
endstr = " \r"
print("[{0}/{1}] Cache size: {2}".format(i, u, len(db.interface.cache)), end = endstr)
print("[{0}/{1}] Cache size: {2}".format(i, u, len(db.interface.cache)), end = endstr)
assert(len(db.interface.cache) <= db.get_maxcachesize())
assert(len(db.interface.cache) <= db.get_maxcachesize())
print(" -> ~{0:.4f}ms per call to get_node".format((time.time()-s)*1000/u), end = " \n")
print(" --> Test successful")
print(" -> ~{0:.4f}ms per call to get_node".format((time.time()-s)*1000/u), end = " \n")
print(" --> Test successful")
def testSetNode():
db = minetest.map.MapInterface("./map.sqlite")
f = open("./dump.bin", "w")
dummy = minetest.nodes.Node("default:nyancat")
s = time.time()
u = 100
db = minetest.map.MapInterface("./map.sqlite")
f = open("./dump.bin", "w")
dummy = minetest.nodes.Node("default:nyancat")
s = time.time()
u = 100
for y in range(1, u+1):
db.set_node(minetest.utils.Pos({'x': 0, 'y': y, 'z': 0}), dummy)
for y in range(1, u+1):
db.set_node(minetest.utils.Pos({'x': 0, 'y': y, 'z': 0}), dummy)
print(" -> {0} nyan cats placed".format(u))
print(" -> {0}ms per call to set_node".format((time.time()-s)/u*1000))
s = time.time()
db.save()
print(" -> database saving took {0}s".format(time.time()-s))
print(" --> Test successful")
print(" -> {0} nyan cats placed".format(u))
print(" -> {0}ms per call to set_node".format((time.time()-s)/u*1000))
s = time.time()
db.save()
print(" -> database saving took {0}s".format(time.time()-s))
print(" --> Test successful")
def invManip():
db = minetest.map.MapInterface("./map.sqlite")
pos = minetest.utils.Pos({'x': 0, 'y': 0, 'z': 0})
chest = db.get_meta(pos)
inv = chest.get_inventory()
db = minetest.map.MapInterface("./map.sqlite")
pos = minetest.utils.Pos({'x': 0, 'y': 0, 'z': 0})
chest = db.get_meta(pos)
inv = chest.get_inventory()
print(" -> Testing inventory in node at {0}".format(pos))
print(" ~~> Node's name is {0}".format(db.get_node(pos).get_name()))
if inv.is_empty("main"):
print(" ~~> Inventory is empty")
else:
print(" ~~> Inventory is not empty")
print(" -> Testing inventory in node at {0}".format(pos))
print(" ~~> Node's name is {0}".format(db.get_node(pos).get_name()))
if inv.is_empty("main"):
print(" ~~> Inventory is empty")
else:
print(" ~~> Inventory is not empty")
print(" ~~> Size of 'main' list is {0} slots".format(inv.get_size("main")))
print(" --> Test successful")
print(" ~~> Size of 'main' list is {0} slots".format(inv.get_size("main")))
print(" --> Test successful")
def testSchematics():
# Import from file
schem = minetest.schematics.Schematic("/home/lymkwi/.minetest/games/minetest_game/mods/default/schematics/apple_tree_from_sapling.mts")
print(" -> Schematic : {0}".format(schem))
# Import from file
schem = minetest.schematics.Schematic(os.environ["HOME"] + "/.minetest/games/minetest_game/mods/default/schematics/apple_tree_from_sapling.mts")
print(" -> Schematic : {0}".format(schem))
# Export to BytesStream & file
assert(schem.export().read())
print(" -> Export : OK")
s = time.time()
schem.export_to_file("test.mts")
print(" ~~> File export : {0}s".format(time.time()-s))
assert(open("test.mts"))
# Export to BytesStream & file
assert(schem.export().read())
print(" -> Export : OK")
s = time.time()
schem.export_to_file("test.mts")
print(" ~~> File export : {0}s".format(time.time()-s))
assert(open("test.mts"))
# Map export
db = minetest.map.MapInterface("./map.sqlite")
s = time.time()
schem = db.export_schematic(minetest.utils.Pos(), minetest.utils.Pos({"x": -100, "y": 10, "z": 100}))
s = time.time() - s
assert(schem.export().read())
print(" -> Schematic exportation : OK")
print(" ~~> Exportation took {0}s".format(s))
schem.export_to_file("test.mts")
# Map export
db = minetest.map.MapInterface("./map.sqlite")
s = time.time()
schem = db.export_schematic(minetest.utils.Pos(), minetest.utils.Pos({"x": -100, "y": 10, "z": 100}))
s = time.time() - s
assert(schem.export().read())
print(" -> Schematic exportation : OK")
print(" ~~> Exportation took {0}s".format(s))
schem.export_to_file("test.mts")
# Get node
node = schem.get_node(minetest.utils.Pos({"x": 0, "y": 0, "z": 0})).get_name()
assert(node != "")
print(" -> Node in (0,0,0) is {0}".format(node))
# Get node
node = schem.get_node(minetest.utils.Pos({"x": 0, "y": 0, "z": 0})).get_name()
assert(node != "")
print(" -> Node in (0,0,0) is {0}".format(node))
# Import
s = time.time()
db.import_schematic(minetest.utils.Pos({"x": 100, "y": 100, "z": 100}), schem)
print(" -> Importation in map took {0}s".format(time.time() - s))
# Import
s = time.time()
db.import_schematic(minetest.utils.Pos({"x": 100, "y": 100, "z": 100}), schem)
print(" -> Importation in map took {0}s".format(time.time() - s))
print(" -> {0} mapblock(s) to be saved".format(len(db.mod_cache)))
s = time.time()
db.save()
print(" -> Saving took {0}s".format(time.time() - s))
print(" --> Test successful")
print(" -> {0} mapblock(s) to be saved".format(len(db.mod_cache)))
s = time.time()
db.save()
print(" -> Saving took {0}s".format(time.time() - s))
print(" --> Test successful")
def testMapBlockInit():
# Open the db
db = minetest.map.MapInterface("./map.sqlite")
# Open the db
db = minetest.map.MapInterface("./map.sqlite")
# Override
print(" -> Init mapblock at (0,0,0)")
db.init_mapblock(0, override = True)
# Override
print(" -> Init mapblock at (0,0,0)")
db.init_mapblock(0, override = True)
print(" -> Saving..")
db.save()
db.unload_mapblock(0)
print(" -> Saving..")
db.save()
db.unload_mapblock(0)
# Seek node at (0,0,0)
print(" -> Assertion about node at (0,0,0)")
assert(db.get_node(minetest.utils.Pos()).get_name() == "air")
print(" -> Assertion succeeded")
print(" --> Test successful")
# Seek node at (0,0,0)
print(" -> Assertion about node at (0,0,0)")
assert(db.get_node(minetest.utils.Pos()).get_name() == "air")
print(" -> Assertion succeeded")
print(" --> Test successful")
def testConfiguration():
# Open the file
dir = os.environ["HOME"] + "/.minetest/worlds/world"
print("-> Trying to open {0}".format(dir))
conf = minetest.config.Configuration.open_world(dir)
if not conf:
print("=> No conf found")
return
# Open the file
dir = os.environ["HOME"] + "/.minetest/worlds/world"
print(" -> Testing world configuration first")
print(" ~~> Trying to open {0}(/world.mt)".format(dir))
conf = minetest.config.Configuration.open_world(dir)
if not conf:
print("=> No conf found")
return
print("-> The world's backend is {0}".format(conf["backend"]))
print("-> There are {0} configuration keys in the file".format(len(conf)))
if "load_mod_mesecon" in conf and conf["load_mod_mesecon"]:
print("-> You have mesecon installed and set to be loaded")
else:
print("-> You do not have mesecon installed, or it is disabled")
print(" ~~> The world's backend is {0}".format(conf["backend"]))
print(" ~~> There are {0} configuration keys in the file".format(len(conf)))
if "load_mod_mesecon" in conf and conf["load_mod_mesecon"]:
print(" ~~> You have mesecon installed and set to be loaded")
else:
print(" ~~> You do not have mesecon installed, or it is disabled")
print(" -> Testing minetest.conf second")
conf = minetest.config.Configuration(os.environ["HOME"] + "/.minetest/minetest.conf")
if not conf:
print(" ~~> File not opened")
return
print(" ~~> The admin's name is {0}".format(conf["name"] or "unknown"))
print(" ~~> The last server you joined was at {0}:{1}".format(conf["address"], conf["port"] or '?????'))
print(" ~~> The last selected world is located at {0}".format(conf["selected_world_path"]))
print(" -> Checking write abilities.. ")
fixed_map_seed = random.randint(0, 100000000)
conf["fixed_map_seed"] = fixed_map_seed
print(" ~~> Fixed map seed to {0}".format(fixed_map_seed))
assert(conf.write())
print(" ~~> Configuration written")
conf = None
print(" ~~> Object thrown away")
newconf = minetest.config.Configuration(os.environ["HOME"] + "/.minetest/minetest.conf")
print(" ~~> Checking fixed_map_seed...")
print(" ~~> fixed_map_seed = {0}".format(newconf["fixed_map_seed"]))
assert(newconf["fixed_map_seed"] == fixed_map_seed)
print(" ~~> Assertion passed")
newconf = None
print(" ~~> Checking item removal")
conf = minetest.config.Configuration(os.environ["HOME"] + "/.minetest/minetest.conf")
name = conf["name"]
del conf["name"]
conf.write()
conf = minetest.config.Configuration(os.environ["HOME"] + "/.minetest/minetest.conf")
assert(not conf["name"])
print(" ~~> Item 'name' removed correctly")
conf = None
print(" ~~> Checking item insertion")
conf = minetest.config.Configuration(os.environ["HOME"] + "/.minetest/minetest.conf")
conf["name"] = name
conf.write()
conf = None
print(" ~~> Name inserted back")
conf = minetest.config.Configuration(os.environ["HOME"] + "/.minetest/minetest.conf")
print(" ~~> Name is '{}'".format(conf["name"]))
assert(conf["name"] == name)
print(" ~~> Assertion passed")
conf = None
print(" --> Test successful")
def main():
print("=> Configuration Test")
testConfiguration()
""" print("=> MapBlockLoad Test")
s = time.time()
testMapBlockLoad()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> Tests will begin now")
time.sleep(3)
print("=> Signed Endians")
s = time.time()
testEndians()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> MapBlockLoad Test")
s = time.time()
testMapBlockLoad()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> get_node Test")
s = time.time()
testGetNode()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> Signed Endians")
s = time.time()
testEndians()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> set_node")
s = time.time()
testSetNode()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> get_node Test")
s = time.time()
testGetNode()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> inventory manipulation (WIP)")
s = time.time()
invManip()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> set_node")
s = time.time()
testSetNode()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> schematic manipulation (WIP)")
s = time.time()
testSchematics()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> inventory manipulation (WIP)")
s = time.time()
invManip()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> schematic manipulation")
s = time.time()
testSchematics()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> MapBlock init")
s = time.time()
testMapBlockInit()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> Configuration Test (WIP)")
s = time.time()
testConfiguration()
print(" => Test took {0:.10f}s".format(time.time()-s))
print("=> MapBlock init")
s = time.time()
testMapBlockInit()
print(" => Test took {0:.10f}s".format(time.time()-s))"""
if __name__ == "__main__":
main()
main()