Skip to content

Commit

Permalink
image: resolve abolute path from src
Browse files Browse the repository at this point in the history
  • Loading branch information
pared committed May 3, 2022
1 parent 369396f commit 8f42a00
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 7 deletions.
14 changes: 13 additions & 1 deletion src/dvc_render/image.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os

from .base import Renderer


Expand All @@ -22,15 +24,25 @@ class ImageRenderer(Renderer):

def partial_html(self) -> str:
div_content = []
output_dir = self.properties.get("out", None)
for datapoint in self.datapoints:
src = datapoint[self.SRC_FIELD]

if (
not src.startswith("data:image;base64")
and os.path.isabs(src)
and output_dir
):
src = os.path.relpath(src, output_dir)

div_content.append(
f"""
<div
style="border:1px dotted black;margin:2px;display:
inline-block;
overflow:hidden;margin-left:8px;">
<p>{datapoint[self.TITLE_FIELD]}</p>
<img src="{datapoint[self.SRC_FIELD]}">
<img src="{src}">
</div>
"""
)
Expand Down
55 changes: 49 additions & 6 deletions tests/test_image.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os

import pytest

from dvc_render.image import ImageRenderer
Expand All @@ -23,21 +25,62 @@ def test_matches(extension, matches):
assert ImageRenderer.matches(filename, {}) == matches


def test_render(tmp_dir):
tmp_dir.gen("workspace_file.jpg", b"content")
@pytest.mark.parametrize("output_dir", [None, "/output/dir"])
@pytest.mark.parametrize(
"src", ["relpath.jpg", "data:image;base64,encoded_image"]
)
def test_render(output_dir, src):
datapoints = [
{
"filename": "file.jpg",
"rev": "workspace",
"src": src,
}
]

html = ImageRenderer(
datapoints, "file.jpg", out=output_dir
).generate_html()

assert "<p>file.jpg</p>" in html
assert f'<img src="{src}">' in html


@pytest.mark.parametrize(
"output_dir,img_path,expected_path",
[
(
os.path.join("output", "path"),
os.path.join("output", "path", "with", "static"),
os.path.join("with", "static"),
),
(
os.path.join("output", "one", "path"),
os.path.join("output", "second", "path"),
os.path.join("..", "..", "second", "path"),
),
],
)
def test_render_evaluate_relative_path(
tmp_dir, output_dir, img_path, expected_path
):
abs_output_dir = tmp_dir / output_dir
abs_img_path = tmp_dir / img_path

datapoints = [
{
"filename": "file.jpg",
"rev": "workspace",
"src": "workspace_file.jpg",
"src": str(abs_img_path),
}
]
filename = "file.jpg"

html = ImageRenderer(datapoints, filename).generate_html()
html = ImageRenderer(
datapoints, "file.jpg", out=abs_output_dir
).generate_html()

assert "<p>file.jpg</p>" in html
assert '<img src="workspace_file.jpg">' in html
assert f'<img src="{expected_path}">' in html


def test_render_empty():
Expand Down

0 comments on commit 8f42a00

Please sign in to comment.