Optimize class 'Log' and add class 'Conf'

main
LeoHsiao 5 years ago
parent 454308e6b2
commit d916a60341

@ -7,11 +7,11 @@ class TestCases(unittest.TestCase):
def setUp(self): def setUp(self):
os.chdir(utils.TEST_DIR) os.chdir(utils.Conf.tmp_dir)
def tearDown(self): def tearDown(self):
utils.log._buffer = [''] utils.log.buffer = ['']
def test_addmoddel(self): def test_addmoddel(self):

@ -7,38 +7,40 @@ import shutil
import subprocess import subprocess
class Conf:
# The configuration parameters for bash test # The configuration parameters for bash test
# The function configure_suite() in system_tests.py will override these parameters # The function configure_suite() in system_tests.py will override these parameters
EXIV2_DIR = os.path.normpath(os.path.join(os.path.abspath(__file__), '../../../')) exiv2_dir = os.path.normpath(os.path.join(os.path.abspath(__file__), '../../../'))
BIN_DIR = os.path.join(EXIV2_DIR, 'build/bin') bin_dir = os.path.join(exiv2_dir, 'build/bin')
DATA_DIR = os.path.join(EXIV2_DIR, 'test/data') data_dir = os.path.join(exiv2_dir, 'test/data')
TEST_DIR = os.path.join(EXIV2_DIR, 'test/tmp') tmp_dir = os.path.join(exiv2_dir, 'test/tmp')
ENCODING = 'utf-8' encoding = 'utf-8'
PLATFORM = platform.system() or 'Unknown' system_name = platform.system() or 'Unknown'
os.makedirs(TEST_DIR, exist_ok=True)
@classmethod
def init(cls):
""" Init the test environment """
os.makedirs(cls.tmp_dir, exist_ok=True)
cls.bin_files = [i.split('.')[0] for i in os.listdir(cls.bin_dir)]
class Log: class Log:
_buffer = [''] buffer = ['']
def _add_msg(self, msg): def to_str(self):
self._buffer.append(msg) return '\n'.join(self.buffer)
@property def add_msg(self, msg):
def buffer(self): self.buffer.append(msg)
return '\n'.join(self._buffer)
def info(self, msg, index=None): def info(self, msg, index=None):
self._add_msg('[INFO] {}'.format(msg)) self.add_msg('[INFO] {}'.format(msg))
def warn(self, msg): def warn(self, msg):
self._add_msg('[WARN] {}'.format(msg)) self.add_msg('[WARN] {}'.format(msg))
def error(self, msg): def error(self, msg):
self._add_msg('[ERROR] {}'.format(msg)) self.add_msg('[ERROR] {}'.format(msg))
log = Log()
def cp(src, dest): def cp(src, dest):
@ -60,27 +62,27 @@ def rm(*files):
continue continue
def cat(*files, encoding=ENCODING): def cat(*files, encoding=None):
text = '' text = ''
for i in files: for i in files:
with open(i, 'r', encoding=encoding) as f: with open(i, 'r', encoding=encoding or Conf.encoding) as f:
text += f.read() text += f.read()
return text return text
def grep(pattern, *files, encoding=ENCODING): def grep(pattern, *files, encoding=None):
result = '' result = ''
pattern = '.*{}.*'.format(pattern) pattern = '.*{}.*'.format(pattern)
for i in files: for i in files:
text = cat(i, encoding=encoding) text = cat(i, encoding=encoding or Conf.encoding)
result += '\n'.join(re.findall(pattern, text)) result += '\n'.join(re.findall(pattern, text))
return result return result
def save(text: (str, list), filename, encoding=ENCODING): def save(text: (str, list), filename, encoding=None):
if not isinstance(text, str): if not isinstance(text, str):
text = '\n'.join(text) text = '\n'.join(text)
with open(filename, 'w', encoding=encoding) as f: with open(filename, 'w', encoding=encoding or Conf.encoding) as f:
f.write(text) f.write(text)
@ -105,15 +107,15 @@ def diff(file1, file2):
def copyTestFile(src, dest=''): def copyTestFile(src, dest=''):
""" Copy one test file from DATA_DIR to TEST_DIR """ """ Copy one test file from data_dir to tmp_dir """
if not dest: if not dest:
dest = src dest = src
shutil.copy(os.path.join(DATA_DIR, src), shutil.copy(os.path.join(Conf.data_dir, src),
os.path.join(TEST_DIR, dest)) os.path.join(Conf.tmp_dir, dest))
def copyTestFiles(*files): def copyTestFiles(*files):
""" Copy one or more test files from DATA_DIR to TEST_DIR """ """ Copy one or more test files from data_dir to tmp_dir """
for i in files: for i in files:
copyTestFile(i) copyTestFile(i)
@ -124,14 +126,14 @@ def md5sum(filename):
return hashlib.md5(f.read()).hexdigest() return hashlib.md5(f.read()).hexdigest()
def runTest(cmd: str, vars_dict=dict(), expected_returncodes=[0], encoding=ENCODING) -> list: def runTest(cmd: str, vars_dict=dict(), expected_returncodes=[0], encoding=None) -> list:
""" Execute a file in the exiv2 bin directory and return its stdout. """ """ Execute a file in the exiv2 bin directory and return its stdout. """
cmd = cmd.format(**vars_dict) cmd = cmd.format(**vars_dict)
args = shlex.split(cmd) args = shlex.split(cmd)
args[0] = os.path.join(BIN_DIR, args[0]) args[0] = os.path.join(Conf.bin_dir, args[0])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=TEST_DIR) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=Conf.tmp_dir)
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
output = (stdout + stderr).decode(encoding).rstrip('\n') output = (stdout + stderr).decode(encoding or Conf.encoding).rstrip('\n')
if p.returncode not in expected_returncodes: if p.returncode not in expected_returncodes:
log.error('Failed to excute: {}'.format(cmd)) log.error('Failed to excute: {}'.format(cmd))
log.error('The expected return code is {}, but get {}'.format(str(expected_returncodes), p.returncode)) log.error('The expected return code is {}, but get {}'.format(str(expected_returncodes), p.returncode))
@ -140,26 +142,30 @@ def runTest(cmd: str, vars_dict=dict(), expected_returncodes=[0], encoding=ENCOD
return output.split('\n') if output else [] return output.split('\n') if output else []
def reportTest(testname, output: (str, list), encoding=ENCODING): def reportTest(testname, output: (str, list), encoding=None):
""" If the output of the test case is correct, this function returns None. Otherwise print its error. """ """ If the output of the test case is correct, this function returns None. Otherwise print its error. """
if not isinstance(output, str): if not isinstance(output, str):
output = '\n'.join(output) output = '\n'.join(output)
reference_file = os.path.join(DATA_DIR, '{}.out'.format(testname)) reference_file = os.path.join(Conf.data_dir, '{}.out'.format(testname))
reference_output = cat(reference_file, encoding=encoding) reference_output = cat(reference_file, encoding=encoding or Conf.encoding)
if reference_output == output: if reference_output == output:
return return
log.error('The output of the testcase mismatch the reference') log.error('The output of the testcase mismatch the reference')
output_file = os.path.join(TEST_DIR, '{}.out'.format(testname)) output_file = os.path.join(Conf.tmp_dir, '{}.out'.format(testname))
save(output, output_file, encoding=encoding) save(output, output_file, encoding=encoding or Conf.encoding)
log.info('The output has been saved to file {}'.format(output_file)) log.info('The output has been saved to file {}'.format(output_file))
log.error('diff:\n' + diff(reference_file, output_file)) log.info('diff:\n' + diff(reference_file, output_file))
raise RuntimeError(log.buffer) raise RuntimeError(log.to_str())
def ioTest(filename): def ioTest(filename):
src = os.path.join(DATA_DIR, filename) src = os.path.join(Conf.data_dir, filename)
out1 = os.path.join(TEST_DIR, '{}.1'.format(filename)) out1 = os.path.join(Conf.tmp_dir, '{}.1'.format(filename))
out2 = os.path.join(TEST_DIR, '{}.2'.format(filename)) out2 = os.path.join(Conf.tmp_dir, '{}.2'.format(filename))
runTest('iotest {src} {out1} {out2}', vars()) runTest('iotest {src} {out1} {out2}', vars())
assert md5sum(src) == md5sum(out1), 'The output file is different' assert md5sum(src) == md5sum(out1), 'The output file is different'
assert md5sum(src) == md5sum(out2), 'The output file is different' assert md5sum(src) == md5sum(out2), 'The output file is different'
Conf.init()
log = Log()

@ -202,9 +202,10 @@ def configure_suite(config_file):
) )
# Configure the parameters for bash test # Configure the parameters for bash test
utils.BIN_DIR = os.path.abspath(config['ENV']['exiv2_path']) utils.Conf.bin_dir = os.path.abspath(config['ENV']['exiv2_path'])
utils.DATA_DIR = os.path.abspath(config['paths']['data_path']) utils.Conf.data_dir = os.path.abspath(config['paths']['data_path'])
utils.TEST_DIR = os.path.abspath(config['paths']['tmp_path']) utils.Conf.tmp_dir = os.path.abspath(config['paths']['tmp_path'])
utils.Conf.init()
class FileDecoratorBase(object): class FileDecoratorBase(object):

Loading…
Cancel
Save