d10_cs_generator/tests/test_build.py

237 lines
17 KiB
Python

import json
from pathlib import Path
import re
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import build
class BuildTests(unittest.TestCase):
def test_all_variants_and_themes(self):
for variant in ('base', 'cyberpunk'):
for theme in ('parchment', 'night'):
with self.subTest(variant=variant, theme=theme), tempfile.TemporaryDirectory() as tmp:
files = build.build(variant, theme, Path(tmp))
self.assertEqual(set(files), {p.name for p in Path(tmp).iterdir()})
info = json.loads(files['build-info.json'])
self.assertEqual(info['variant'], variant)
self.assertGreater(info['skills'], 10)
self.assertIn('repeating_', files['sheet.html'])
self.assertIn('sheet-rolltemplate-d10skillcheck', files['sheet.html'])
self.assertIn('class="sheet-roll-values"', files['sheet.html'])
self.assertIn('class="sheet-roll-value">{{result}}', files['sheet.html'])
self.assertIn('.sheet-rolltemplate-d10skillcheck .inlinerollresult', files['sheet.css'])
self.assertIn('color: #20242b !important; background: #ffffff !important', files['sheet.css'])
self.assertIn('class="sheet-stat-grid"', files['sheet.html'])
self.assertIn('1d@{dice}cs1cf@{dice}', files['sheet.html'])
self.assertIn('1d10cs1cf10', files['sheet.html'])
self.assertIn('class="sheet-skill-head"', files['sheet.html'])
self.assertEqual(files['sheet.html'].count('class="sheet-page sheet-page-'), 2 if variant == 'base' else 3)
self.assertIn('name="attr_d10_tab" value="skills"', files['sheet.html'])
self.assertIn('name="attr_d10_theme_choice"', files['sheet.html'])
self.assertIn(f'.sheet-theme-state[value="{theme}"] ~ .sheet-d10', files['sheet.css'])
self.assertNotIn('name="act_tab_core"', files['sheet.html'])
self.assertLess(files['sheet.html'].index('01</span>'), files['sheet.html'].index('class="sheet-tab-nav"'))
self.assertLess(files['sheet.html'].index('02</span>'), files['sheet.html'].index('class="sheet-tab-nav"'))
self.assertIn('.sheet-tab-state[value="skills"] ~ .sheet-page-skills', files['sheet.css'])
self.assertIn('.sheet-tab-state[value="core"] ~ .sheet-page-skills', files['sheet.css'])
self.assertEqual(files['sheet.html'].count('class="sheet-skill-row'), info['skills'])
if variant == 'base':
markup = files['sheet.html']
self.assertIn('<option value="parchment"', markup)
self.assertIn('<option value="night"', markup)
self.assertNotIn('<option value="bluecore"', markup)
self.assertNotIn('.sheet-theme-state[value="bluecore"]', files['sheet.css'])
self.assertNotIn('name="act_tab_other"', markup)
self.assertEqual(markup.count('class="sheet-skill-pane sheet-skill-pane-'), 4)
self.assertLess(markup.index('name="attr_general_skilllevel_Perfection"'), markup.index('class="sheet-skill-pane sheet-skill-pane-free"'))
for tab, section in (('fight', 'general-combat-skills'), ('free', 'skills'),
('magic', 'magic-skills'), ('equipment', 'equipment')):
self.assertIn(f'name="act_skill_tab_{tab}"', markup)
self.assertIn(f'.sheet-skill-tab-state[value="{tab}"] ~ .sheet-skill-pane-{tab}', files['sheet.css'])
self.assertLess(markup.index(f'class="sheet-skill-pane sheet-skill-pane-{tab}"'),
markup.index(f'class="repeating_{section}"'))
self.assertEqual(markup.count(f'class="repeating_{section}"'), 1)
else:
self.assertEqual(files['sheet.html'].count('class="sheet-skill-pane sheet-category-pane-'), 3)
self.assertIn('name="attr_d10_category_tab" value="physique"', files['sheet.html'])
for tab in ('physique', 'intellectuelles', 'social'):
self.assertIn(f'.sheet-category-tab-state[value="{tab}"] ~ .sheet-category-pane-{tab}', files['sheet.css'])
self.assertNotIn('name="act_category_tab_arsenal"', files['sheet.html'])
combat_page = files['sheet.html'].split('class="sheet-page sheet-page-combat"', 1)[1].split('class="sheet-page sheet-page-skills"', 1)[0]
self.assertIn('name="attr_d10_arsenal_tab"', combat_page)
self.assertIn('class="repeating_distance"', combat_page)
self.assertIn('class="repeating_melee"', combat_page)
self.assertIn('class="repeating_consommable"', combat_page)
for section in ('distance', 'melee', 'consommable'):
self.assertIn(f'name="act_arsenal_tab_{section}"', files['sheet.html'])
self.assertEqual(files['sheet.html'].count(f'class="repeating_{section}"'), 1)
for action in ('firesingle', 'fireburst', 'fireauto', 'reload', 'damage'):
self.assertIn(f'name="act_{action}"', files['sheet.html'])
self.assertIn('name="attr_ammo_current"', files['sheet.html'])
self.assertIn('<span class="sheet-weapon-status" name="attr_weapon_status"></span>', files['sheet.html'])
self.assertIn('name="attr_damage_per_success"', files['sheet.html'])
self.assertIn('d10<${threshold}cs1cf10', files['sheet.html'])
self.assertNotIn('D10_WEAPON_DIAGNOSTIC', files['sheet.html'])
self.assertIn('{{#ammo_info}}<div class="sheet-roll-detail">Chargeur :', files['sheet.html'])
self.assertEqual(files['sheet.html'].count('name="attr_rmax"'), 2)
self.assertNotIn('name="attr_attack_dice"', files['sheet.html'])
contacts = re.search(r'<fieldset class="repeating_contacts-skills">(.*?)</fieldset>',
files['sheet.html'], re.DOTALL)
self.assertIsNotNone(contacts)
self.assertNotIn('attr_attribute_select', contacts.group(1))
self.assertNotIn('Caractéristique', contacts.group(1))
self.assertIn('>Show</button>', contacts.group(1))
self.assertIn('&amp;{template:d10contact}', contacts.group(1))
self.assertIn('sheet-rolltemplate-d10contact', files['sheet.html'])
consumables = re.search(r'<fieldset class="repeating_consommable">(.*?)</fieldset>',
files['sheet.html'], re.DOTALL)
self.assertIsNotNone(consumables)
self.assertIn('>Show</button>', consumables.group(1))
self.assertIn('&amp;{template:d10consumable}', consumables.group(1))
for field in ('name', 'quantity', 'notes'):
self.assertIn(f'@{{{field}}}', consumables.group(1))
self.assertIn('<rolltemplate class="sheet-rolltemplate-d10consumable">', files['sheet.html'])
self.assertIn('Quantité : {{quantity}}', files['sheet.html'])
self.assertIn('.sheet-d10 .sheet-stat-grid { display: grid;', files['sheet.css'])
self.assertIn('.sheet-d10 .sheet-skill-head, .sheet-d10 .sheet-skill-row { display: grid;', files['sheet.css'])
self.assertIn('.sheet-d10 .sheet-body-maps { display: grid; grid-template-columns: repeat(2,minmax(0,1fr));', files['sheet.css'])
self.assertIn('.sheet-d10 .sheet-zone-body { top: 112px;', files['sheet.css'])
self.assertIn('-moz-appearance: textfield', files['sheet.css'])
self.assertIn('::-webkit-inner-spin-button', files['sheet.css'])
self.assertNotIn('Ravenous', files['sheet.html'])
self.assertIn('--d10-accent:', files['sheet.css'])
self.assertEqual(files, build.build(variant, theme, Path(tmp)))
build.build(variant, theme, Path(tmp), check=True)
(Path(tmp) / 'sheet.css').write_text('stale', encoding='utf-8')
with self.assertRaisesRegex(ValueError, 'stale'):
build.build(variant, theme, Path(tmp), check=True)
def test_attributes_referenced_by_generated_rolls(self):
for variant in ('base', 'cyberpunk'):
with tempfile.TemporaryDirectory() as tmp:
markup = build.build(variant, 'parchment', Path(tmp))['sheet.html']
declared = set(re.findall(r'name="attr_([A-Za-z0-9_-]+)"', markup))
referenced = set(re.findall(r'@\{([A-Za-z0-9_-]+)\}', markup))
self.assertFalse(referenced - declared - {'character_id'}, referenced - declared)
self.assertEqual(len(declared), len(set(declared)))
self.assertIn('<summary>Échanges JSON</summary>', markup)
self.assertIn('value="!d10-export --id @{character_id}"', markup)
self.assertIn('value="!d10-import --replace --id @{character_id} --handout ?{ID du handout personnage}"', markup)
self.assertIn('base-Force', declared)
self.assertIn('Life_Points', declared)
if variant == 'cyberpunk':
self.assertIn('Initiative', declared)
self.assertNotIn('general_attack_threshold', declared)
self.assertNotIn('base_damage_dices', declared)
self.assertNotIn('exal_damage_dices', declared)
self.assertNotIn('general_item_weapon1', declared)
self.assertNotIn('Jets de combat', markup)
self.assertNotIn('Armes équipées', markup)
self.assertIn('class="sheet-combat-field sheet-combat-field-initiative"', markup)
self.assertIn('Life_Points_head', declared)
self.assertIn('repeating_distance', markup)
self.assertIn('class="sheet-body-maps"', markup)
self.assertIn('class="sheet-map-card sheet-map-health"', markup)
self.assertIn('class="sheet-map-card sheet-map-armor"', markup)
for kind in ('health', 'armor'):
image = f'robotman_{kind}_r.png'
self.assertIn(f'src="{build.DEFAULT_ASSET_BASE_URL}{image}"', markup)
self.assertEqual(build.ASSETS.joinpath(image).read_bytes(),
Path(tmp, image).read_bytes())
for location in build.LOCATIONS:
for prefix in ('Life_Points', 'Armor_Protection_Points', 'Armor_Integrity_Points'):
self.assertEqual(markup.count(f'name="attr_{prefix}_{location}"'), 1)
self.assertEqual(markup.count(f'name="attr_Armor_Integrity_Points_{location}_maximum"'), 1)
else:
self.assertIn('general_attack_threshold', declared)
self.assertIn('general_item_weapon1', declared)
self.assertIn('Jets de combat', markup)
self.assertIn('Armes équipées', markup)
self.assertNotIn('class="sheet-body-maps"', markup)
self.assertNotIn('robotman_health_r.png', markup)
def test_theme_is_visual_only(self):
for variant in ('base', 'cyberpunk'):
with self.subTest(variant=variant), tempfile.TemporaryDirectory() as tmp:
one = build.build(variant, 'parchment', Path(tmp))
two = build.build(variant, 'night', Path(tmp))
def normalize(markup, theme):
markup = markup.replace(f'theme-{theme}', 'theme-compiled').replace(' selected', '')
return re.sub(r'(class="sheet-theme-state" name="attr_d10_theme" value=")[^"]+',
r'\1compiled', markup)
self.assertEqual(normalize(one['sheet.html'], 'parchment'), normalize(two['sheet.html'], 'night'))
self.assertNotEqual(one['sheet.css'], two['sheet.css'])
def test_corporate_theme_selector(self):
themes = build.read_yaml(build.DATA / 'themes.yaml')['themes']
self.assertEqual(len(themes), 20)
self.assertEqual(themes['parchment']['name'], 'Parchemin')
self.assertEqual(themes['night']['name'], 'Nuit')
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaisesRegex(ValueError, 'unknown theme for base'):
build.build('base', 'bluecore', Path(tmp))
def luminance(color):
channels = [int(color[index:index + 2], 16) / 255 for index in (1, 3, 5)]
linear = [value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4
for value in channels]
return sum(value * weight for value, weight in zip(linear, (0.2126, 0.7152, 0.0722)))
for key, palette in themes.items():
with self.subTest(theme=key), tempfile.TemporaryDirectory() as tmp:
accent, panel = luminance(palette['accent']), luminance(palette['panel'])
self.assertGreaterEqual((max(accent, panel) + 0.05) / (min(accent, panel) + 0.05), 4.5)
files = build.build('cyberpunk', key, Path(tmp))
self.assertIn(f'<option value="{key}" selected>', files['sheet.html'])
self.assertIn(f'>{palette.get("name", key)}</option>', files['sheet.html'])
self.assertIn(f'.sheet-theme-state[value="{key}"] ~ .sheet-d10', files['sheet.css'])
self.assertIn(f'--d10-background: {palette["background"]}', files['sheet.css'])
self.assertIn(f'--d10-figure-filter: {build.figure_filter(palette["background"])}', files['sheet.css'])
build.build('cyberpunk', key, Path(tmp), check=True)
def test_hosted_image_urls(self):
with tempfile.TemporaryDirectory() as tmp:
files = build.build('cyberpunk', 'parchment', Path(tmp),
asset_base_url='https://example.org/d10/assets')
self.assertIn('src="https://example.org/d10/assets/robotman_health_r.png"', files['sheet.html'])
self.assertIn('src="https://example.org/d10/assets/robotman_armor_r.png"', files['sheet.html'])
build.build('cyberpunk', 'parchment', Path(tmp), check=True,
asset_base_url='https://example.org/d10/assets')
with self.assertRaisesRegex(ValueError, 'missing or stale'):
build.build('cyberpunk', 'parchment', Path(tmp), check=True)
with self.assertRaisesRegex(ValueError, 'HTTPS'):
build.build('cyberpunk', 'parchment', Path(tmp), asset_base_url='http://example.org')
local = build.build('cyberpunk', 'parchment', Path(tmp), asset_base_url='')
self.assertIn('src="robotman_health_r.png"', local['sheet.html'])
def test_rejects_bad_data(self):
source = build.read_yaml(build.DATA / 'sheet_model.yaml')
skills = build.read_yaml(build.DATA / 'cyberpunk_skills.yaml')
theme = build.read_yaml(build.DATA / 'themes.yaml')['themes']['night']
model = {**source['variants']['cyberpunk'], 'version': 1}
build.validate(model, skills, theme)
bad = {'sections': [{'id': 'test', 'name': 'Test', 'groups': [{'name': 'Test', 'skills': [
{'id': 'one', 'name': 'One'}, {'id': 'one', 'name': 'Duplicate'}]}]}]}
with self.assertRaisesRegex(ValueError, 'duplicate skill'):
build.validate({**model, 'skill_category_tabs': False}, bad, theme)
with self.assertRaisesRegex(ValueError, 'at least two unique'):
build.validate(model, bad, theme)
with self.assertRaisesRegex(ValueError, 'invalid theme color'):
build.validate(model, skills, {**theme, 'accent': 'red'})
with self.assertRaisesRegex(ValueError, 'unsupported health location'):
build.validate({**model, 'health_locations': ['tail']}, skills, theme)
broken_weapons = [{**block, 'fields': [field for field in block['fields'] if field != 'ammo_current']}
if block['id'] == 'distance' else block for block in model['repeating']]
with self.assertRaisesRegex(ValueError, 'invalid weapon fields'):
build.validate({**model, 'repeating': broken_weapons}, skills, theme)
base = {**source['variants']['base'], 'version': 1}
base_skills = build.read_yaml(build.DATA / 'base_skills.yaml')
with self.assertRaisesRegex(ValueError, 'each skill group and repeating section exactly once'):
build.validate({**base, 'skill_tabs': base['skill_tabs'][:-1]}, base_skills, theme)
if __name__ == '__main__':
unittest.main()