diff --git a/modmesh/track/dataframe.py b/modmesh/track/dataframe.py index e8844012c..193b6b74c 100644 --- a/modmesh/track/dataframe.py +++ b/modmesh/track/dataframe.py @@ -67,9 +67,11 @@ def read_from_text_file( :return: None """ - if isinstance(fname, str): + if isinstance(fname, (str, os.PathLike)): if not os.path.exists(fname): - raise Exception("Text file '{}' does not exist".format(fname)) + raise FileNotFoundError( + "Text file '{}' does not exist".format(fname) + ) fid = open(fname, 'rt') fid_ctx = contextlib.closing(fid) else: diff --git a/tests/test_timeseries_dataframe.py b/tests/test_timeseries_dataframe.py index a1a81170b..afdcf15f6 100644 --- a/tests/test_timeseries_dataframe.py +++ b/tests/test_timeseries_dataframe.py @@ -25,6 +25,9 @@ # POSSIBILITY OF SUCH DAMAGE. import io +import os +import pathlib +import tempfile import unittest import numpy as np @@ -163,3 +166,39 @@ def test_dataframe_sort(self): col_data = reordered_tsdf['DELTA_VEL[1]'] nd_arr = np.genfromtxt(io.StringIO(self.dlc_data), delimiter=',')[1:] self.assertEqual(list(col_data), list(nd_arr[:, 1])) + + def test_read_from_text_file_accepts_str_path(self): + tsdf = dataframe.DataFrame() + with tempfile.NamedTemporaryFile( + mode='w', suffix='.csv', delete=False, + ) as fh: + fh.write(self.dlc_data) + path = fh.name + try: + tsdf.read_from_text_file(path) + self.assertEqual(tsdf._columns, self.col_sol) + self.assertEqual(tsdf._index_name, 'EPOCH') + finally: + os.unlink(path) + + def test_read_from_text_file_accepts_pathlib_path(self): + tsdf = dataframe.DataFrame() + with tempfile.NamedTemporaryFile( + mode='w', suffix='.csv', delete=False, + ) as fh: + fh.write(self.dlc_data) + path = pathlib.Path(fh.name) + try: + tsdf.read_from_text_file(path) + self.assertEqual(tsdf._columns, self.col_sol) + self.assertEqual(tsdf._index_name, 'EPOCH') + finally: + path.unlink() + + def test_read_from_text_file_missing_raises_filenotfound(self): + tsdf = dataframe.DataFrame() + missing = pathlib.Path(tempfile.gettempdir()) / 'no_such_file.csv' + expected_msg = "Text file '{}' does not exist".format(missing) + with self.assertRaises(FileNotFoundError) as ctx: + tsdf.read_from_text_file(missing) + self.assertEqual(str(ctx.exception), expected_msg)