"""Tests for sorting every list of trails, and for sketching trails with no track on maps from their start (and end) points. Sort parity: the Python order (facets.sort_records) is compared with a Python re-implementation of the app.js comparator over the rendered rows' data-* attributes, for each of the eight keys, so the check needs no browser. """ import copy import html import os import re import sys import unittest from functools import cmp_to_key WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, WEB) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import build # noqa: E402 from olt import browse, docs, facets, hike, home, records, trail # noqa: E402 from test_hike import GH, fake # noqa: E402 def make(id_, name, km=100, days=None, climb=None, coverage=1.0, **kw): rec = fake(1, km=km, **kw) rec["id"], rec["name"] = id_, name if days is not None: rec["hike"] = dict(rec.get("hike") or {}, days=days) if climb is not None: rec["derived"]["elevation"] = {"ascent_m": climb, "coverage": coverage} return rec def ids(recs): return [r["id"] for r in recs] def row_data(rec): """The data-* values of a rendered row, as the script reads them.""" row = home.entry(rec) attrs = dict(re.findall(r'data-(\w+)="([^"]*)"', row.split("\n", 1)[0])) return {k: html.unescape(v) for k, v in attrs.items()} def _cmp(a, b): return (a > b) - (a < b) def js_compare(x, y, key): """compareEntries in app.js, restated over parsed data-* strings.""" if key == "name": return _cmp(x["name"], y["name"]) if key == "name-desc": return _cmp(y["name"], x["name"]) if key.startswith("climb"): xc = None if x["climb"] == "" else float(x["climb"]) yc = None if y["climb"] == "" else float(y["climb"]) if xc is None or yc is None: if xc is None and yc is None: return _cmp(x["name"], y["name"]) return 1 if xc is None else -1 return (_cmp(yc, xc) if key == "climb-desc" else _cmp(xc, yc)) or _cmp(x["name"], y["name"]) field = "km" if key.startswith("length") else "days" order = _cmp(float(y[field]), float(x[field])) if key.endswith("-desc") else _cmp(float(x[field]), float(y[field])) return order or _cmp(x["name"], y["name"]) FIXTURES = [ make("b-trail", "B Trail", km=300, days=[10, 20], climb=5000), make("a-trail", "The A Trail", km=100, days=[5, 20], climb=9000), make("c-trail", "C Trail", km=300, days=[3, 8]), # no climb make("d-trail", "D Trail", km=50, days=[30, 40], climb=1000, coverage=0.5), # climb hidden make("e-trail", "E Trail", km=900, days=[60, 90], climb=9000), ] class SortKeysTest(unittest.TestCase): def test_options_in_order_and_wording(self): self.assertEqual([label for _, label in facets.SORTS], [ "Name, A to Z", "Name, Z to A", "Length, longest first", "Length, shortest first", "Time, quickest first", "Time, slowest first", "Climb, most first", "Climb, least first"]) select = home.sort_select("length-asc") self.assertIn('Sort by', select) self.assertIn('', select) self.assertEqual([m for m in re.findall(r'