Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions modmesh/track/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
39 changes: 39 additions & 0 deletions tests/test_timeseries_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
# POSSIBILITY OF SUCH DAMAGE.

import io
import os
import pathlib
import tempfile
import unittest

import numpy as np
Expand Down Expand Up @@ -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):
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not look like related to the fix. Please share with us why do you want to include it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file path can be either a string or a os.PathLike instance. This test is added is to explicitly test if the DataFrame can accept str type text file path.

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)
Loading