Skip to content

Commit

Permalink
Merge pull request #18 from glasnt/feature/android
Browse files Browse the repository at this point in the history
Stars test
  • Loading branch information
glasnt authored Mar 14, 2021
2 parents 5994c7e + 6c74332 commit a796ed9
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 18 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ jobs:
fail-fast: false
matrix:
python-version:
- "3.8"
- "3.9"
- "3.x"

steps:
- uses: actions/checkout@v2
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ venv/*
.egg*
dist/*
*.html

test/images/stars_image.png
test/output/*
30 changes: 21 additions & 9 deletions ih/chart.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import click
from textwrap import dedent
from pathlib import Path

import os
from tabulate import tabulate
Expand Down Expand Up @@ -29,20 +30,27 @@
GUIDECOL = (0, 0, 0, 0)


def debug_data(image_name, scale, colors, palette_name, chartimage, fileformat="html"):
def nicename(image_name):
if hasattr(image_name, "name"):
image_name = image_name.name
return Path(image_name).name



def debug_data(image_name, scale, colors, palette_name, chartimage, colorsused, fileformat="html"):
import pkg_resources

ih_version = pkg_resources.require("ih")[0].version
data = [
f"Image: {image_name}",
f"Image: {nicename(image_name)}",
f"Scale: {scale}x",
f"Image size: {chartimage.height} x {chartimage.width}",
f"Palette: {palette_name}",
f"Colors: {colors}",
f"Colors used: {colorsused} (of possible {colors})",
f"ih version: {ih_version}",
]
if fileformat == "html":
return f'<div class="debug">' + "<br>".join(data) + "</div>"
return f'<div class="debug">' + "<br />".join(data) + "</div>"
else:
return "\n".join(data)

Expand Down Expand Up @@ -85,7 +93,7 @@ def get_legend(chartimage):
rgb = x[1]
h = helpers.rgb2hex(rgb)
star = STARS[idx % len(STARS)]
sclass = helpers.star_class(star)
sclass = helpers.col_class(h)

# Choose the best text colour
if (rgb[0] * 0.299 + rgb[1] * 0.587 + rgb[2] * 0.114) > 186:
Expand All @@ -100,6 +108,7 @@ def get_legend(chartimage):


def generate_html_chart(
image_name,
chartimage,
palette_name,
pal,
Expand All @@ -108,7 +117,8 @@ def generate_html_chart(
data="",
):

html = ['<html><meta charset="UTF-8">']
html = [f'<html><meta charset="UTF-8" /><title>ih - {nicename(image_name)}</title>']
html.append('<link rel="icon" href="data:image/svg+xml,%3csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22%3e%3ctext y=%22.9em%22 font-size=%2290%22%3e%f0%9f%a7%b6%3c/text%3e%3c/svg%3e" />')

with open(helpers.base_path("styling").joinpath("styling.css")) as s:
html.append("<style>")
Expand Down Expand Up @@ -145,12 +155,12 @@ def generate_html_chart(

html.append(".%s { background-color: %s; color: %s }" % (x, y["bg"], y["c"]))
if not render:
html.append('.%s::after { content: "%s" }' % (x, y["star"]))
html.append('.%s::after { content: "%s\ufe0e" }' % (x, y["star"]))

if not render:
html.append(
'.%s::after { content: "%s" }'
% (helpers.star_class(helpers.WHITESTAR), helpers.WHITESTAR)
% (helpers.col_class(helpers.WHITECOL), helpers.WHITESTAR)
)

html.append("</style>")
Expand Down Expand Up @@ -354,11 +364,13 @@ def chart(
palette_name=palette_name,
chartimage=chartimage,
fileformat=fileformat,
colorsused=len(sorted(chartimage.getcolors())),
)

if fileformat == "html":
chart = generate_html_chart(
chartimage,
image_name=image_name,
chartimage=chartimage,
palette_name=palette_name,
pal=pal,
render=render,
Expand Down
22 changes: 15 additions & 7 deletions ih/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
"◀",
"♠",
"✿",
"⟘",
"⟒",
"⚉",
"♣",
"▷",
Expand All @@ -27,15 +25,22 @@
"❤",
"⟙",
"✾",
"∀",
"⊕",
"♥",
"⇨",
"⚇",
"◼",
"⁋",
"⬣",
"^",
"&",
"=",
"|",
"#",
]

WHITESTAR = "·"
WHITECOL = "#ffffff"


def rgb2hex(pix):
Expand Down Expand Up @@ -66,10 +71,10 @@ def color_cell(
else:
td = "span"

if color == "#ffffff":
if color == WHITECOL:
star = WHITESTAR

classes = f"s {star_class(star)}"
classes = f"s {col_class(color)}"
if center:
classes += " center"
if guide[1]:
Expand All @@ -80,8 +85,11 @@ def color_cell(
return f'<{td} class="{classes}"></{td}>'


def star_class(star):
return f"u{hex(ord(star))[2:]}"
#def star_class(star):
# return f"u{hex(ord(star))[2:]}"

def col_class(col):
return f"u-{col[1:].lower()}"


def base_path(path):
Expand Down
1 change: 1 addition & 0 deletions test/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pytest-tldr
beautifulsoup4
1 change: 1 addition & 0 deletions test/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def runner(args, print_output=False, image=TEST_PNG, output=None):
print(result.output)
assert result.exit_code == 0
assert output in result.output
return output


def test_image():
Expand Down
66 changes: 66 additions & 0 deletions test/test_html.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from click.testing import CliRunner
from pathlib import Path
from PIL import Image, ImageDraw
from bs4 import BeautifulSoup as bs

from ih.cli import main
from ih.palette import get_palette
from ih import helpers


from test_cli import runner, TEST_OUTPUT

s = 1 #square
length = 8
stars_image = "stars_image.png"

def test_stars():
# Build a unique image, with enough colours to use all stars and then some
stars = len(helpers.STARS)
w = length + 1
h = int(stars/length) + 1

img = Image.new('RGB', (w, h))
draw = ImageDraw.Draw(img)

# Draw palette from file
palette = [tuple(x['rgb']) for x in get_palette("floss")][:(w*h)]

ct = 0
for i in range(0, w):
for j in range(0, h):
c = palette[ct]
ct += 1
draw.polygon([(i,j),(i+s, j), (i, j+s), (i+s, j+s)], fill=c)

path = Path(TEST_OUTPUT).parent.joinpath("images").joinpath(stars_image)
img.save(path)

# Generate Chart
output = runner(["-p", "floss", "-c", 256], image=str(path))

# Parse HTML into beautifulsoup
html = Path(TEST_OUTPUT).joinpath(output)
with open(html) as f:
soup = bs(f, "html.parser")

# Pull legend from HTML
rows = soup.find("table", {"class": "legend"}).find_all("tr")

# Can't compare Tags, so cast and sort
def stringy(l):
return sorted([str(x) for x in l])

# Assert all rows in legend unique
assert stringy(rows) == stringy(list(set(rows)))

# Assert all elements in star column are unique
stars = [ x.find('td') for x in rows ]
assert stringy(stars) == stringy(list(set(stars)))

# Assert colour count matches expectations
starrows = len(rows) - 1 # remove header from counter
assert starrows == ct

# Assert colour count matches shown
assert str(starrows) in soup.find("div", {"class": "debug"}).text

0 comments on commit a796ed9

Please sign in to comment.