Example #1
0
def test_write_json_creates_dirs_if_necessary(
    tmp_path: Path, sync_filesystem: SyncFilesystem
) -> None:
    """It should create directories as necessary to reach the path."""
    path = tmp_path / "foo" / "bar" / "baz"
    sync_filesystem.write_json(path, {"foo": "hello", "bar": 0})

    assert path.with_suffix(".json").read_text() == """{"foo": "hello", "bar": 0}"""
Example #2
0
def test_write_json_raises_encode_error(
    tmp_path: Path, sync_filesystem: SyncFilesystem
) -> None:
    """It should raise a FileEncodeError if object cannot be encoded to JSON."""
    path = tmp_path / "foo"

    with pytest.raises(FileEncodeError, match="ellipsis is not JSON serializable"):
        sync_filesystem.write_json(path, {"nope": ...})
Example #3
0
def test_write_json_encodes_and_writes_obj(
    tmp_path: Path, sync_filesystem: SyncFilesystem
) -> None:
    """It should encode and write a JSON object to a file."""
    path = tmp_path / "foo"
    sync_filesystem.write_json(path, {"foo": "hello", "bar": 0})

    assert path.with_suffix(".json").read_text() == """{"foo": "hello", "bar": 0}"""
Example #4
0
def test_write_json_when_custom_encoder_raises(
    tmp_path: Path, mock_encode_json: MagicMock, sync_filesystem: SyncFilesystem
) -> None:
    """It should raise a FileEncodeError if the custom encoder raises."""
    path = tmp_path / "foo"
    obj = {"foo": "hello", "bar": 0}
    mock_encode_json.side_effect = Exception("oh no")

    with pytest.raises(FileEncodeError, match="oh no"):
        sync_filesystem.write_json(path, obj, encode_json=mock_encode_json)
Example #5
0
def test_write_json_with_custom_encoder(
    tmp_path: Path, mock_encode_json: MagicMock, sync_filesystem: SyncFilesystem
) -> None:
    """It should encode and write a file using a custom encoder."""
    path = tmp_path / "foo"
    obj = {"foo": "hello", "bar": 0}
    mock_encode_json.return_value = "I just met you"

    sync_filesystem.write_json(path, obj, encode_json=mock_encode_json)

    assert path.with_suffix(".json").read_text() == "I just met you"
    mock_encode_json.assert_called_with(obj)