Skip to content

Commit

Permalink
Merge pull request #398 from eumiro/pathib
Browse files Browse the repository at this point in the history
Use pathlib
  • Loading branch information
liZe authored Aug 20, 2023
2 parents 7468122 + e967434 commit d9ce00a
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 84 deletions.
5 changes: 2 additions & 3 deletions cairosvg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"""

import os
import sys
from pathlib import Path

Expand All @@ -15,9 +14,9 @@
else:
# Frozen with something else (py2exe, etc.)
# See https://github.com/Kozea/WeasyPrint/pull/269
ROOT = Path(os.path.dirname(sys.executable))
ROOT = Path(sys.executable).parent
else:
ROOT = Path(os.path.dirname(__file__))
ROOT = Path(__file__).resolve().parent

VERSION = __version__ = (ROOT / 'VERSION').read_text().strip()

Expand Down
4 changes: 2 additions & 2 deletions cairosvg/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"""

import argparse
import os
import sys
from pathlib import Path

from . import SURFACES, VERSION

Expand Down Expand Up @@ -72,7 +72,7 @@ def main(argv=None, stdout=None, stdin=None):
kwargs['url'] = options.input
output_format = (
options.format or
os.path.splitext(options.output)[1].lstrip('.') or
Path(options.output).suffix.lstrip('.') or
'pdf').upper()

SURFACES[output_format.upper()].convert(**kwargs)
Expand Down
130 changes: 52 additions & 78 deletions cairosvg/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@
"""

import io
import os
import shutil
import sys
import tempfile

import cairocffi as cairo
import pytest
Expand Down Expand Up @@ -46,7 +43,7 @@ def read_file(filename):
return file_object.read()


def test_api():
def test_api(tmp_path):
"""Test the Python API with various parameters."""
expected_content = svg2png(SVG_SAMPLE)
# Already tested above: just a sanity check:
Expand All @@ -65,34 +62,27 @@ def test_api():
svg2png(SVG_SAMPLE, write_to=file_like)
assert file_like.getvalue() == expected_content

temp = tempfile.mkdtemp()
try:
temp_0 = os.path.join(temp, 'sample_0.svg')
with open(temp_0, 'wb') as file_object:
file_object.write(SVG_SAMPLE)

# Read from a filename
assert svg2png(url=temp_0) == expected_content
assert svg2png(
url=f'file://{temp_0}') == expected_content
temp_0 = tmp_path / 'sample_0.svg'
temp_0.write_bytes(SVG_SAMPLE)

with open(temp_0, 'rb') as file_object:
# Read from a real file object
assert svg2png(file_obj=file_object) == expected_content
# Read from a filename
assert svg2png(url=str(temp_0)) == expected_content
assert svg2png(url=f'file://{temp_0}') == expected_content

temp_1 = os.path.join(temp, 'result_1.png')
with open(temp_1, 'wb') as file_object:
# Write to a real file object
svg2png(SVG_SAMPLE, write_to=file_object)
assert read_file(temp_1) == expected_content
with temp_0.open('rb') as file_object:
# Read from a real file object
assert svg2png(file_obj=file_object) == expected_content

temp_2 = os.path.join(temp, 'result_2.png')
# Write to a filename
svg2png(SVG_SAMPLE, write_to=temp_2)
assert read_file(temp_2) == expected_content
temp_1 = tmp_path / 'result_1.png'
with temp_1.open('wb') as file_object:
# Write to a real file object
svg2png(SVG_SAMPLE, write_to=file_object)
assert read_file(str(temp_1)) == expected_content

finally:
shutil.rmtree(temp)
temp_2 = tmp_path / 'result_2.png'
# Write to a filename
svg2png(SVG_SAMPLE, write_to=str(temp_2))
assert read_file(str(temp_2)) == expected_content

file_like = io.BytesIO()
try:
Expand Down Expand Up @@ -126,7 +116,7 @@ def test_low_level_api():
assert cairo.SurfacePattern(png_surface.cairo)


def test_script():
def test_script(tmp_path):
"""Test the ``cairosvg`` script and the ``main`` function."""
expected_png = svg2png(SVG_SAMPLE)[:100]
expected_pdf = svg2pdf(SVG_SAMPLE)[:100]
Expand Down Expand Up @@ -165,52 +155,36 @@ def test_main(args, exit_=False, input_=None, full=False):
sys.stdin, sys.stdout = old_stdin, old_stdout
return output if full else output[:100]

with tempfile.NamedTemporaryFile(delete=False) as file_object:
file_object.write(SVG_SAMPLE)
file_object.flush()
svg_filename = file_object.name
file_object.close()

assert test_main(['--help'], exit_=True).startswith(b'usage: ')
assert test_main(['--version'], exit_=True).strip() == (
VERSION.encode('ascii'))

assert test_main([svg_filename]) == expected_pdf
assert test_main([svg_filename, '-d', '96', '-f', 'pdf']) == (
expected_pdf)
assert test_main([svg_filename, '-f', 'png']) == expected_png
assert test_main(['-'], input_=svg_filename) == expected_pdf

# Test DPI
output = test_main([svg_filename, '-d', '10', '-f', 'png'], full=True)
image = cairo.ImageSurface.create_from_png(io.BytesIO(output))
assert image.get_width() == 40
assert image.get_height() == 50

temp = tempfile.mkdtemp()
try:
temp_1 = os.path.join(temp, 'result_1')
# Default to PDF
assert not test_main([svg_filename, '-o', temp_1])
assert read_file(temp_1)[:100] == expected_pdf

temp_2 = os.path.join(temp, 'result_2.png')
# Guess from the file extension
assert not test_main([svg_filename, '-o', temp_2])
assert read_file(temp_2)[:100] == expected_png

temp_3 = os.path.join(temp, 'result_3.png')
# Explicit -f wins
assert not test_main([svg_filename, '-o', temp_3, '-f', 'pdf'])
assert read_file(temp_3)[:100] == expected_pdf
finally:
shutil.rmtree(temp)

try:
os.remove(svg_filename)
except PermissionError:
# On Windows/NT systems, the temporary file sometimes fails to
# get deleted due to ``PermissionError`` exception. This is due
# to how Windows/NT handles the same file being opened twice at
# the same time.
pass
svg_path = tmp_path / "test.svg"
svg_path.write_bytes(SVG_SAMPLE)
svg_filename = str(svg_path)

assert test_main(['--help'], exit_=True).startswith(b'usage: ')
assert test_main(['--version'], exit_=True).strip() == (
VERSION.encode('ascii'))

assert test_main([svg_filename]) == expected_pdf
assert test_main([svg_filename, '-d', '96', '-f', 'pdf']) == expected_pdf
assert test_main([svg_filename, '-f', 'png']) == expected_png
assert test_main(['-'], input_=svg_filename) == expected_pdf

# Test DPI
output = test_main([svg_filename, '-d', '10', '-f', 'png'], full=True)
image = cairo.ImageSurface.create_from_png(io.BytesIO(output))
assert image.get_width() == 40
assert image.get_height() == 50

temp_1 = tmp_path / 'result_1'
# Default to PDF
assert not test_main([svg_filename, '-o', str(temp_1)])
assert read_file(temp_1)[:100] == expected_pdf

temp_2 = tmp_path / 'result_2.png'
# Guess from the file extension
assert not test_main([svg_filename, '-o', str(temp_2)])
assert read_file(temp_2)[:100] == expected_png

temp_3 = tmp_path / 'result_3.png'
# Explicit -f wins
assert not test_main([svg_filename, '-o', str(temp_3), '-f', 'pdf'])
assert read_file(str(temp_3))[:100] == expected_pdf
2 changes: 1 addition & 1 deletion cairosvg/url.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""

import os.path
import os
import re
from pathlib import Path
from urllib.parse import urljoin, urlparse
Expand Down

0 comments on commit d9ce00a

Please sign in to comment.