[mod] add detail error messages on asserts

This commit is contained in:
Laurent Peuch 2019-08-04 18:48:16 +02:00
parent 1f10529209
commit f49c004a59

View file

@ -22,7 +22,7 @@ def read_file(file_path):
Keyword argument: Keyword argument:
file_path -- Path to the text file file_path -- Path to the text file
""" """
assert isinstance(file_path, basestring) assert isinstance(file_path, basestring), "Error: file_path '%s' should be a string but is of type '%s' instead" % (file_path, type(file_path))
# Check file exists # Check file exists
if not os.path.isfile(file_path): if not os.path.isfile(file_path):
@ -148,14 +148,14 @@ def write_to_file(file_path, data, file_mode="w"):
file_mode -- Mode used when writing the file. Option meant to be used file_mode -- Mode used when writing the file. Option meant to be used
by append_to_file to avoid duplicating the code of this function. by append_to_file to avoid duplicating the code of this function.
""" """
assert isinstance(data, basestring) or isinstance(data, list) assert isinstance(data, basestring) or isinstance(data, list), "Error: data '%s' should be either a string or a list but is of type '%s'" % (data, type(data))
assert not os.path.isdir(file_path) assert not os.path.isdir(file_path), "Error: file_path '%s' point to a dir, it should be a file" % file_path
assert os.path.isdir(os.path.dirname(file_path)) assert os.path.isdir(os.path.dirname(file_path)), "Error: the path ('%s') base dir ('%s') is not a dir" % (file_path, os.path.dirname(file_path))
# If data is a list, check elements are strings and build a single string # If data is a list, check elements are strings and build a single string
if not isinstance(data, basestring): if not isinstance(data, basestring):
for element in data: for element in data:
assert isinstance(element, basestring) assert isinstance(element, basestring), "Error: element '%s' should be a string but is of type '%s' instead" % (element, type(element))
data = '\n'.join(data) data = '\n'.join(data)
try: try:
@ -189,10 +189,10 @@ def write_to_json(file_path, data):
""" """
# Assumptions # Assumptions
assert isinstance(file_path, basestring) assert isinstance(file_path, basestring), "Error: file_path '%s' should be a string but is of type '%s' instead" % (file_path, type(file_path))
assert isinstance(data, dict) or isinstance(data, list) assert isinstance(data, dict) or isinstance(data, list), "Error: data '%s' should be a dict or a list but is of type '%s' instead" % (data, type(data))
assert not os.path.isdir(file_path) assert not os.path.isdir(file_path), "Error: file_path '%s' point to a dir, it should be a file" % file_path
assert os.path.isdir(os.path.dirname(file_path)) assert os.path.isdir(os.path.dirname(file_path)), "Error: the path ('%s') base dir ('%s') is not a dir" % (file_path, os.path.dirname(file_path))
# Write dict to file # Write dict to file
try: try: