Files
HowDoYouConvert/verify_batch_1.py

115 lines
3.3 KiB
Python

import urllib.request
import re
import math
import time
calculators = [
{
"url": "acres-to-square-feet",
"factor": 43560,
"method1": "multiply"
},
{
"url": "angstroms-to-nanometers",
"factor": 0.1,
"method1": "multiply"
},
{
"url": "apothecary-ounces-to-grams",
"factor": 31.1034768,
"method1": "multiply"
},
{
"url": "astronomical-units-to-light-years",
"factor": 0.0000158125074,
"method1": "multiply"
},
{
"url": "atmosphere-to-mmhg",
"factor": 760,
"method1": "multiply"
}
]
def extract_values_from_js(html_content):
# Added [eE\-\+] support for scientific notation (e.g., 1.5812e-05)
match1 = re.search(r'let val2.*?val1\s*([*\/\&#0-9;x]+)\s*([0-9.eE\-\+]+);', html_content)
match2 = re.search(r'let val1.*?val2\s*([*\/\&#0-9;x]+)\s*([0-9.eE\-\+]+);', html_content)
return match1, match2
def clean_op(op_str):
if "*" in op_str or "*" in op_str or "x" in op_str.lower():
return "*"
elif "/" in op_str or "/" in op_str:
return "/"
return op_str
def test_math(val_in, target_factor, op):
if op == "*":
return val_in * target_factor
else:
return val_in / target_factor
all_passed = True
print("Starting Bidirectional Verification Process...\n")
for calc in calculators:
base_url = f"https://howdoyouconvert.com/calculator/{calc['url']}/?ao_noptimize=1" # Bypass Autoptimize cache
print(f"Testing: {base_url}")
req = urllib.request.Request(base_url, headers={'User-Agent': 'Mozilla/5.0'})
try:
resp = urllib.request.urlopen(req)
html = resp.read().decode('utf-8')
except Exception as e:
print(" [FAIL] Could not load page:", e)
all_passed = False
continue
m1, m2 = extract_values_from_js(html)
if not m1 or not m2:
print(" [FAIL] Could not locate the injected JavaScript formulas.")
all_passed = False
continue
op1, factor1 = m1.groups()
op2, factor2 = m2.groups()
op1 = clean_op(op1)
op2 = clean_op(op2)
factor1 = float(factor1)
factor2 = float(factor2)
# 1. Forward Test
test_val1 = 10.0
expected_v2 = test_math(test_val1, calc["factor"], "*" if calc["method1"] == "multiply" else "/")
actual_v2 = test_math(test_val1, factor1, op1)
if not math.isclose(expected_v2, actual_v2, rel_tol=1e-5):
print(f" [FAIL] Forward Test mismatch! Expected {expected_v2}, got {actual_v2}")
all_passed = False
else:
print(f" [PASS] Forward Test: 10 {op1} {factor1} = {actual_v2}")
# 2. Reverse Test
test_val2 = actual_v2
expected_v1 = test_val1
actual_v1 = test_math(test_val2, factor2, op2)
if not math.isclose(expected_v1, actual_v1, rel_tol=1e-5):
print(f" [FAIL] Reverse Test mismatch! Expected {expected_v1}, got {actual_v1}")
all_passed = False
else:
print(f" [PASS] Reverse Test: {test_val2} {op2} {factor2} = {actual_v1}")
print("")
time.sleep(0.5)
if all_passed:
print("✅ Verification Complete: All 5 calculators passed bidirectional testing accurately.")
else:
print("❌ Verification Failed: One or more calculators failed math tolerances.")