From 1d39cc18bf45fa40bf39b9c8a236040aad018e1d Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 25 Jul 2023 20:19:23 +0200 Subject: [PATCH] Add is_file_in_dir helper function --- freqtrade/misc.py | 7 +++++++ tests/test_misc.py | 20 +++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/freqtrade/misc.py b/freqtrade/misc.py index 350ac5eef..e715c280a 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -116,6 +116,13 @@ def file_load_json(file: Path): return pairdata +def is_file_in_dir(file: Path, directory: Path) -> bool: + """ + Helper function to check if file is in directory. + """ + return file.is_file() and file.parent.samefile(directory) + + def pair_to_filename(pair: str) -> str: for ch in ['/', ' ', '.', '@', '$', '+', ':']: pair = pair.replace(ch, '_') diff --git a/tests/test_misc.py b/tests/test_misc.py index 21c832c2c..3943e7f15 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -8,7 +8,7 @@ import pandas as pd import pytest from freqtrade.misc import (dataframe_to_json, decimals_per_coin, deep_merge_dicts, file_dump_json, - file_load_json, json_to_dataframe, pair_to_filename, + file_load_json, is_file_in_dir, json_to_dataframe, pair_to_filename, parse_db_uri_for_logging, plural, render_template, render_template_with_fallback, round_coin_value, safe_value_fallback, safe_value_fallback2) @@ -64,6 +64,24 @@ def test_file_load_json(mocker, testdatadir) -> None: assert ret +def test_is_file_in_dir(tmp_path): + + # Create a temporary directory and file + dir_path = tmp_path / "subdir" + dir_path.mkdir() + file_path = dir_path / "test.txt" + file_path.touch() + + # Test that the function returns True when the file is in the directory + assert is_file_in_dir(file_path, dir_path) is True + + # Test that the function returns False when the file is not in the directory + assert is_file_in_dir(file_path, tmp_path) is False + + file_path2 = tmp_path / "../../test2.txt" + assert is_file_in_dir(file_path2, tmp_path) is False + + @pytest.mark.parametrize("pair,expected_result", [ ("ETH/BTC", 'ETH_BTC'), ("ETH/USDT", 'ETH_USDT'),