From 16c80aa215df0a11f83652c3956e56c7a5e51517 Mon Sep 17 00:00:00 2001 From: "Zong-han, Xie" Date: Sun, 17 May 2026 21:06:28 +0800 Subject: [PATCH] Relate to issue-786 1. Modify DataFrame code to accept os.PathLike csv paths. 2. Add tests to explicitly test if dataframe can accept paths from `pathlib` as well as a string 3. Enhance the exception raise to explicitly indicates the files are not found. 4. Add tests to test raised Exception type as well as the error message. --- modmesh/track/dataframe.py | 6 +++-- tests/test_timeseries_dataframe.py | 39 ++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) 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)