def test_python_render(assert_pixels_equal, tmp_path):
    """Test rendering with the Python API."""
    base_url = str(resource_path('dummy.html'))
    html_string = '<body><img src=pattern.png>'
    css_string = '''
        @page { margin: 2px; size: 8px }
        body { margin: 0; font-size: 0 }
        img { image-rendering: pixelated }

        @media screen { img { transform: rotate(-90deg) } }
    '''
    html = FakeHTML(string=html_string, base_url=base_url)
    css = CSS(string=css_string)

    png_bytes = html.write_png(stylesheets=[css])
    pdf_bytes = html.write_pdf(stylesheets=[css])
    assert png_bytes.startswith(b'\211PNG\r\n\032\n')
    assert pdf_bytes.startswith(b'%PDF')
    check_png_pattern(assert_pixels_equal, png_bytes)

    png_file = FakeFile()
    html.write_png(png_file, stylesheets=[css])
    assert png_file.getvalue() == png_bytes
    pdf_file = FakeFile()
    html.write_pdf(pdf_file, stylesheets=[css])
    assert pdf_file.getvalue().startswith(b'%PDF')

    png_path = tmp_path / '1.png'
    pdf_path = tmp_path / '1.pdf'
    html.write_png(png_path, stylesheets=[css])
    html.write_pdf(pdf_path, stylesheets=[css])
    assert png_path.read_bytes() == png_bytes
    assert pdf_path.read_bytes().startswith(b'%PDF')

    png_path = tmp_path / '2.png'
    pdf_path = tmp_path / '2.pdf'
    with png_path.open('wb') as png_fd:
        html.write_png(png_fd, stylesheets=[css])
    with pdf_path.open('wb') as pdf_fd:
        html.write_pdf(pdf_fd, stylesheets=[css])
    assert png_path.read_bytes() == png_bytes
    assert pdf_path.read_bytes().startswith(b'%PDF')

    x2_png_bytes = html.write_png(stylesheets=[css], resolution=192)
    check_png_pattern(assert_pixels_equal, x2_png_bytes, x2=True)

    screen_css = CSS(string=css_string, media_type='screen')
    rotated_png_bytes = html.write_png(stylesheets=[screen_css])
    check_png_pattern(assert_pixels_equal, rotated_png_bytes, rotated=True)

    assert FakeHTML(
        string=html_string, base_url=base_url, media_type='screen'
    ).write_png(
        stylesheets=[io.BytesIO(css_string.encode())]
    ) == rotated_png_bytes
    assert FakeHTML(
        string=f'<style>{css_string}</style>{html_string}',
        base_url=base_url, media_type='screen'
    ).write_png() == rotated_png_bytes
Test rendering with the Python API.
tests/test_api.py