Skip to content

Commit 25323bf

Browse files
authored
fix: Accept a path object as an override file path (#572)
<!-- TERMAG_PR_BODY_BEGIN --> **Requirements** - [x] I have added test coverage for new or changed functionality - [x] I have followed the repository's [pull request submission guidelines](../blob/main/CONTRIBUTING.md#submitting-pull-requests) - [ ] I have validated my changes against all supported platform versions - [x] Sync/async parity: matching changes made to `async_*` siblings (or N/A). N/A: `LDClient` and `AsyncLDClient` use the same `FileOverrideSourceBuilder`. **Related issues** - Bugbot finding on #529: #529 (comment) **Describe the solution you've provided** `FileOverrideSourceBuilder` accepted one path as a `str`, or a list of paths. A single `pathlib.Path`, or any other `os.PathLike`, was passed to `list()`. A path object is not iterable, so the constructor raised `TypeError: 'PosixPath' object is not iterable`. The Bugbot finding describes a different failure, a path split into its components that fails every reload, but that cannot happen. The constructor raises before a client exists. The constructor now treats a `str` or an `os.PathLike` as a single path, and converts every path with `os.fspath`. A path that does not name a string path raises `TypeError` from the constructor, with a message that names the value. That includes `bytes` (given alone, in a list, or named by a path object), an `int`, and `None`. `bytes` and `bytearray` count as single values, so a bare `bytes` path is named whole instead of being read as a sequence of integers. The type hint is `Sequence` rather than `List`, so that type checkers accept a list of path objects but not a set, whose order is not fixed. The docstring says that paths may be path objects. Tests cover: - a single path object; - a list of path objects, which already worked; - a path object whose string form differs from its path, as with `os.DirEntry`; - a source that loads a file given as a path object; - the rejection of each of the values above. Each of six broken variants of the constructor fails at least one of these tests, including the original code and a variant that converts with `str()` instead of `os.fspath`. **Describe alternatives you've considered** Leaving the builder to accept only strings, as its type hint said. `pathlib` is the usual way to build paths, a list of path objects already worked, and the error did not say what was wrong. **Additional context** This PR is stacked on #530, the top of the overrides stack, so that the approved PRs below it do not change. Retarget it as the PRs below it merge. The review of this change found three existing gaps that this PR leaves alone: - An empty path resolves to the working directory, and its reads keep failing. - In polling mode, a path that contains a NUL character makes the source fail to start, so the client runs without overrides. In watching mode, the reload fails and keeps retrying. - The file data sources treat a tuple of paths differently from a list. Testing: `mypy ldclient`, `isort --check` and `pycodestyle` pass locally. The test suite passes (2,111 tests). It was run without the Redis, DynamoDB and Consul store integration tests, which need servers that were not running. CI runs only for PRs based on `main` or `feat/**`, so it will not run on this PR until it is retargeted. <!-- TERMAG_PR_BODY_END --> <!-- termag: box=i-0575d1c54853058d7 project=Overrides --> <sub>Opened from termag</sub> <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Overview** > Fixes a constructor bug where a **single** `pathlib.Path` (or other `os.PathLike`) was passed to `list()`, causing `TypeError: 'PosixPath' object is not iterable`. > > `FileOverrideSourceBuilder` now wraps a lone `str`, `bytes`/`bytearray`, or `PathLike` as one path, normalizes every entry with `os.fspath()` (so objects like `os.DirEntry` use their filesystem path, not `str()`), and stores string paths. Invalid inputs (`bytes` paths, ints, `None`, path objects that do not resolve to a `str`) fail fast with an explicit `TypeError`. Type hints use `Sequence` plus `PathLike` so callers can pass path objects while unordered collections like `set` are discouraged. > > New tests cover single/list path objects, `__fspath__` behavior, invalid types, and loading overrides from a path object. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 154b5b8. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 4b5a4b5 commit 25323bf

2 files changed

Lines changed: 88 additions & 6 deletions

File tree

‎ldclient/integrations/overrides.py‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
import math
3030
import os
3131
import threading
32-
from typing import List, Optional, Union
32+
from typing import List, Optional, Sequence, Union
3333

3434
from ldclient.config import DataSourceBuilderConfig, OverrideSourceBuilder
3535
from ldclient.impl.integrations.files.filedata import (
@@ -103,14 +103,29 @@ class FileOverrideSourceBuilder(OverrideSourceBuilder):
103103
system.
104104
"""
105105

106-
def __init__(self, paths: Union[str, List[str]]):
106+
def __init__(self, paths: Union[str, 'os.PathLike[str]', Sequence[Union[str, 'os.PathLike[str]']]]):
107107
"""
108108
:param paths: the files to load overrides from, as a single path or a list of paths.
109-
The order is significant: it determines which file wins under the duplicate keys
110-
handling when the same key appears in more than one file. Relative paths are
111-
resolved against the current working directory when the source is built.
109+
Each path is a string or a path object such as :class:`pathlib.Path`. The order is
110+
significant: it determines which file wins under the duplicate keys handling when the
111+
same key appears in more than one file. Relative paths are resolved against the
112+
current working directory when the source is built.
113+
:raises TypeError: when a path is neither a string nor a path object that names a string
114+
path
112115
"""
113-
self.__paths: List[str] = [paths] if isinstance(paths, str) else list(paths)
116+
# bytes and bytearray are single values too, so that they get the error below instead of
117+
# being read as a sequence of integers.
118+
if isinstance(paths, (str, bytes, bytearray, os.PathLike)):
119+
paths = [paths]
120+
self.__paths: List[str] = []
121+
for path in paths:
122+
try:
123+
name: object = os.fspath(path)
124+
except TypeError:
125+
name = None
126+
if not isinstance(name, str):
127+
raise TypeError("file paths for the file-based override source must be strings or path objects; got %r" % (path,))
128+
self.__paths.append(name)
114129
self.__duplicate_keys_handling = DuplicateKeysHandling.FAIL
115130
self.__change_detection = ChangeDetection.POLLING
116131
self.__poll_interval = self.DEFAULT_POLL_INTERVAL

‎ldclient/testing/integrations/test_file_override_source.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,66 @@ def test_builder_accepts_a_single_path_string(tmp_path):
122122
assert source._paths == [path]
123123

124124

125+
def test_builder_accepts_a_single_path_object(tmp_path):
126+
path = tmp_path / 'overrides.json'
127+
source = FileOverrideSourceBuilder(path).build(SDKConfig('SDK_KEY'))
128+
assert isinstance(source, _FileOverrideSource)
129+
assert source._paths == [str(path)]
130+
131+
132+
def test_builder_accepts_a_list_of_path_objects(tmp_path):
133+
paths = [tmp_path / 'a.json', tmp_path / 'b.json']
134+
source = FileOverrideSourceBuilder(paths).build(SDKConfig('SDK_KEY'))
135+
assert isinstance(source, _FileOverrideSource)
136+
assert source._paths == [str(path) for path in paths]
137+
138+
139+
class LabeledPath:
140+
"""A path object whose string form is not its path, as with :class:`os.DirEntry`."""
141+
142+
def __init__(self, path):
143+
self._path = path
144+
145+
def __fspath__(self):
146+
return self._path
147+
148+
def __str__(self):
149+
return '<LabeledPath>'
150+
151+
152+
@pytest.mark.parametrize('as_list', [False, True], ids=['single', 'list'])
153+
def test_builder_uses_the_file_system_path_of_a_path_object(tmp_path, as_list):
154+
path = os.path.join(str(tmp_path), 'overrides.json')
155+
paths = [LabeledPath(path)] if as_list else LabeledPath(path)
156+
source = FileOverrideSourceBuilder(paths).build(SDKConfig('SDK_KEY'))
157+
assert isinstance(source, _FileOverrideSource)
158+
assert source._paths == [path]
159+
160+
161+
@pytest.mark.parametrize(
162+
'paths',
163+
[
164+
b'/overrides.json',
165+
bytearray(b'/overrides.json'),
166+
[b'/overrides.json'],
167+
LabeledPath(b'/overrides.json'),
168+
[LabeledPath(b'/overrides.json')],
169+
[42],
170+
[None],
171+
],
172+
ids=['bytes', 'bytearray', 'bytes in a list', 'path object naming bytes', 'path object naming bytes in a list', 'int', 'none'],
173+
)
174+
def test_builder_rejects_a_path_that_is_not_a_string_or_path_object(paths):
175+
with pytest.raises(TypeError, match='file paths for the file-based override source must be strings or path objects'):
176+
FileOverrideSourceBuilder(paths)
177+
178+
179+
def test_builder_names_a_rejected_bytes_path_whole():
180+
with pytest.raises(TypeError) as excinfo:
181+
FileOverrideSourceBuilder(b'/overrides.json')
182+
assert "b'/overrides.json'" in str(excinfo.value)
183+
184+
125185
def test_builder_resolves_relative_paths():
126186
source = FileOverrideSourceBuilder(['relative/overrides.json']).build(SDKConfig('SDK_KEY'))
127187
assert isinstance(source, _FileOverrideSource)
@@ -256,6 +316,13 @@ def test_source_loads_initial_data_synchronously(tmp_path, sources):
256316
assert snapshot[0]['flag1'].is_override is False, "the source supplies unmarked definitions; the SDK marks them"
257317

258318

319+
def test_source_loads_a_file_given_as_a_path_object(tmp_path, sources):
320+
path = tmp_path / 'overrides.json'
321+
write_file(str(path), '{"flagValues": {"flag1": true}}')
322+
_, sink = build_source(sources, path)
323+
assert flag_values(sink.require_snapshot()) == {'flag1': True}
324+
325+
259326
@yaml_required
260327
def test_source_loads_yaml(tmp_path, sources):
261328
path = os.path.join(str(tmp_path), 'overrides.yaml')

0 commit comments

Comments
 (0)