Skip to content

Commit 6724740

Browse files
Fix JSON Encoding of Path Objects to Call str() (#1436)
* Fix encoding of Path objects to call str() * Add regression tests for json_encode --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
1 parent cf06bc9 commit 6724740

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

newrelic/common/encoding_utils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import types
2929
import zlib
3030
from collections import OrderedDict
31+
from pathlib import Path
3132

3233
HEXDIGLC_RE = re.compile("^[0-9a-f]+$")
3334
DELIMITER_FORMAT_RE = re.compile("[ \t]*,[ \t]*")
@@ -66,6 +67,8 @@ def json_encode(obj, **kwargs):
6667
def _encode(o):
6768
if isinstance(o, bytes):
6869
return o.decode("latin-1")
70+
elif isinstance(o, Path):
71+
return str(o)
6972
elif isinstance(o, types.GeneratorType):
7073
return list(o)
7174
elif hasattr(o, "__iter__"):

tests/agent_unittests/test_encoding_utils.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from pathlib import Path
16+
1517
import pytest
1618

17-
from newrelic.common.encoding_utils import camel_case, snake_case
19+
from newrelic.common.encoding_utils import camel_case, json_encode, snake_case
1820

1921

2022
@pytest.mark.parametrize(
@@ -55,3 +57,27 @@ def test_camel_case(input_, expected, upper):
5557
def test_snake_case(input_, expected):
5658
output = snake_case(input_)
5759
assert output == expected
60+
61+
62+
def _generator():
63+
# range() itself is not a generator
64+
yield from range(1, 4)
65+
66+
67+
@pytest.mark.parametrize(
68+
"input_,expected",
69+
[
70+
(10, "10"),
71+
(10.0, "10.0"),
72+
("my_string", '"my_string"'),
73+
(b"my_bytes", '"my_bytes"'),
74+
({"id": 1, "name": "test", "NoneType": None}, '{"id":1,"name":"test","NoneType":null}'),
75+
(_generator(), "[1,2,3]"),
76+
(tuple(range(4, 7)), "[4,5,6]"),
77+
(Path("test/path/file.txt"), '"test/path/file.txt"'),
78+
],
79+
ids=["int", "float", "str", "bytes", "dict", "generator", "iterable", "Path"],
80+
)
81+
def test_json_encode(input_, expected):
82+
output = json_encode(input_)
83+
assert output == expected

0 commit comments

Comments
 (0)