feat: improve campus bike discovery and add independent live preview
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const modules = ['map.js', 'map-account.js', 'map-orders.js', 'map-history.js', 'map-subscriptions.js', 'map-rental.js', 'map-utils.js', 'map-sharing.js', 'map-boot.js'];
|
||||
module.exports = modules.map(name => fs.readFileSync(path.join(__dirname, '../static/js', name), 'utf8')).join('\n');
|
||||
@@ -0,0 +1,27 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const vm = require('node:vm');
|
||||
const fs = require('node:fs');
|
||||
const source = fs.readFileSync(require('node:path').join(__dirname,'../static/js/api-client.js'),'utf8');
|
||||
|
||||
test('submission lock prevents duplicates while preserving the next editor state', async () => {
|
||||
const context={window:{},AbortController,Promise,setTimeout,clearTimeout};
|
||||
vm.createContext(context);vm.runInContext(source,context);
|
||||
let resolve, count=0;
|
||||
const button={textContent:'保存修改',disabled:false,setAttribute(){},removeAttribute(){}};
|
||||
const work=()=>{count++; return new Promise(done=>{resolve=()=>{button.textContent='添加规则';done('saved');};});};
|
||||
const first=context.window.AppAPI.run('save-rule',button,work);
|
||||
const second=context.window.AppAPI.run('save-rule',button,work);
|
||||
await Promise.resolve();assert.equal(count,1);assert.equal(button.disabled,true);
|
||||
resolve();assert.deepEqual(await Promise.all([first,second]),['saved','saved']);
|
||||
assert.equal(button.disabled,false);assert.equal(button.textContent,'添加规则');
|
||||
});
|
||||
test('request deadline aborts once and never retries a mutation', async () => {
|
||||
let deadline, calls=0;
|
||||
const context={window:{},AbortController,Promise,setTimeout:fn=>{deadline=fn;return 1;},clearTimeout(){},fetch:(_,options)=>{
|
||||
calls++;return new Promise((_,reject)=>options.signal.addEventListener('abort',()=>{const e=new Error();e.name='AbortError';reject(e);}));
|
||||
}};
|
||||
vm.createContext(context);vm.runInContext(source,context);
|
||||
const result=context.window.AppAPI.fetch('/api/order/unlock',{method:'POST'});
|
||||
deadline();await assert.rejects(result,/请求超时/);assert.equal(calls,1);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const BikeData = require('../static/js/bike-data.js');
|
||||
|
||||
test('missing, empty, invalid and zero batteries remain distinct', () => {
|
||||
for (const value of [null, undefined, '', ' ', true, 'NaN', Infinity, -1, 101]) {
|
||||
assert.equal(BikeData.electric({electric_quantity:value}), null);
|
||||
}
|
||||
assert.equal(BikeData.electric({electric_quantity:0,electricQuantity:90}), 0);
|
||||
assert.equal(BikeData.electric({electric_quantity:'45'}), 45);
|
||||
});
|
||||
test('occupancy and faults take priority; low charge is consistent for strings and numbers', () => {
|
||||
assert.equal(BikeData.state({state:'1',status:'1',electric_quantity:10}), 'inuse');
|
||||
assert.equal(BikeData.state({state:4,status:0,electric_quantity:10}), 'locked');
|
||||
assert.equal(BikeData.state({state:2,status:0,electric_quantity:10}), 'reserved');
|
||||
assert.equal(BikeData.state({state:1,status:0,electric_quantity:10}), 'lowbattery');
|
||||
assert.equal(BikeData.labels[BikeData.state({state:1,status:0,electric_quantity:10})], '低电量');
|
||||
assert.equal(BikeData.state({state:99,status:0}), 'unknown');
|
||||
});
|
||||
test('plate validation supports actual five and eight digit formats only', () => {
|
||||
for (const value of ['50301','51201','30000193']) assert.equal(BikeData.validCode(value), true);
|
||||
for (const value of ['1234','123456','30000193e0','-51201','51 201','12345']) assert.equal(BikeData.validCode(value), false);
|
||||
assert.equal(BikeData.kind({code:'51001'}), 'small');
|
||||
assert.equal(BikeData.kind({code:'51101'}), 'big');
|
||||
assert.equal(BikeData.kind({code:'30000193'}), 'red');
|
||||
});
|
||||
test('filtering preserves unknown batteries only when no minimum is requested', () => {
|
||||
const bike={state:1,status:0,code:'51201'};
|
||||
assert.equal(BikeData.matches(bike,{onlyAvailable:true,minElectric:0,kind:'big'}),true);
|
||||
assert.equal(BikeData.matches(bike,{onlyAvailable:true,minElectric:20,kind:'big'}),false);
|
||||
assert.equal(BikeData.matches({...bike,electric_quantity:25},{onlyAvailable:true,minElectric:20,kind:'big'}),true);
|
||||
assert.equal(BikeData.matches({...bike,status:1,electric_quantity:80},{onlyAvailable:true,minElectric:20}),false);
|
||||
assert.ok(BikeData.distance({lat:36.53,lng:116.78},{lat:36.531,lng:116.78}) > 110);
|
||||
assert.equal(BikeData.distance(null,{lat:36.53,lng:116.78}),null);
|
||||
});
|
||||
@@ -60,8 +60,8 @@ check("freshness stale 为数字", isinstance(d["stale_seconds"], int))
|
||||
r = client.get("/api/history/stats?days=1").get_json()["data"]
|
||||
check("stats days=1 回显", r["days"] == 1)
|
||||
check("stats 24桶", "00" in r["hourly_distribution"] and "23" in r["hourly_distribution"])
|
||||
expected_states = {"available", "used", "locked", "reserved", "low"}
|
||||
check("stats 桶含5状态", set(r["hourly_distribution"]["08"].keys()) == expected_states)
|
||||
expected_states = {"available", "used", "locked", "reserved", "low", "unknown"}
|
||||
check("stats 桶含6状态", set(r["hourly_distribution"]["08"].keys()) == expected_states)
|
||||
|
||||
# ---- stats days=30 ----
|
||||
r = client.get("/api/history/stats?days=30").get_json()["data"]
|
||||
@@ -100,7 +100,7 @@ check("days=0 收敛1", r["days"] == 1)
|
||||
Path(handle.name).unlink(missing_ok=True)
|
||||
print(f"RESULT: {{'FAIL' if failures else 'ALL PASS'}} ({{len(failures)}} failures)")
|
||||
sys.exit(1 if failures else 0)
|
||||
'''.replace("{root}", str(ROOT).replace("\\", "\\\\"))
|
||||
'''.replace("{root}", str(ROOT).replace("\\", "\\\\")).replace("{{", "{").replace("}}", "}")
|
||||
|
||||
|
||||
def test_history_30d_contract():
|
||||
@@ -109,4 +109,4 @@ def test_history_30d_contract():
|
||||
cwd=str(ROOT))
|
||||
out = (r.stdout or "") + (r.stderr or "")
|
||||
print(out[-4000:] if len(out) > 4000 else out)
|
||||
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
||||
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
||||
|
||||
@@ -3,7 +3,7 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8');
|
||||
const source = require('./frontend-source.cjs');
|
||||
const loadingCode = source.slice(source.indexOf(' let mapRequest = null;'), source.indexOf(' // ========== 手动刷新'));
|
||||
const badgeCode = source.slice(source.indexOf(' function mapSnapshotNow()'), source.indexOf(' function showToast(msg)'));
|
||||
|
||||
@@ -29,6 +29,7 @@ function environment() {
|
||||
clearTimeout: id => timers.delete(id),
|
||||
renderMap: result => renders.push(result), setupClusterListener() {}, showLoginGate() {},
|
||||
showToast: message => notices.push(message), friendlyError: error => error.message,
|
||||
apiFetch: (...args) => context.fetch(...args),
|
||||
fetch: () => { context.fetchCount++; return new Promise(done => { resolve = done; }); }, fetchCount: 0
|
||||
};
|
||||
vm.createContext(context); vm.runInContext(loadingCode + badgeCode, context);
|
||||
|
||||
@@ -3,7 +3,7 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8');
|
||||
const source = require('./frontend-source.cjs');
|
||||
|
||||
async function environment({ dependencies = true } = {}) {
|
||||
const elements = new Map(), requests = [], notices = [], events = {};
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Preview/live routing and authenticated editor/pagination contracts in a subprocess."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def test_preview_and_live_feature_contract():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
env = {**os.environ, "XBNIU_PREVIEW": "1", "XBNIU_DB_PATH": str(Path(directory) / "preview.db"), "PYTHONDONTWRITEBYTECODE": "1"}
|
||||
script = r'''
|
||||
from unittest.mock import patch
|
||||
import db
|
||||
db.init_db()
|
||||
import app
|
||||
from preview_data import seed_preview
|
||||
seed_preview()
|
||||
c=app.app.test_client()
|
||||
assert c.get('/healthz').json == {'status':'ok','mode':'preview'}
|
||||
login=c.post('/api/auth/login',json={'email':'demo@preview.local','password':'preview123'}).json
|
||||
h={'Authorization':'Bearer '+login['data']['token']}
|
||||
with patch('wechat.request_with_user_auth',side_effect=AssertionError('Demo called upstream')):
|
||||
bikes=c.get('/api/map?type=3',headers=h).json['data']['bicycleStation']
|
||||
assert len(bikes)==28
|
||||
assert c.post('/api/order/unlock',headers=h,json={'code':'51201'}).json['rtn_code']==0
|
||||
assert c.get('/api/order/status',headers=h).json['has_order']
|
||||
assert c.post('/api/order/return',headers=h,json={}).json['rtn_code']==0
|
||||
assert not c.get('/api/order/status',headers=h).json['has_order']
|
||||
assert c.post('/api/auth/save_token',headers=h,json={'token_id':'real'}).status_code==403
|
||||
page1=c.get('/api/user/orders?limit=20',headers=h).json
|
||||
page2=c.get('/api/user/orders?limit=20&offset=20',headers=h).json
|
||||
assert page1['total']==68 and page1['has_more'] and len(page1['data'])==20
|
||||
assert not ({x['id'] for x in page1['data']} & {x['id'] for x in page2['data']})
|
||||
assert all(x['shared'] for x in c.get('/api/user/orders?source=shared',headers=h).json['data'])
|
||||
assert c.get('/api/user/orders?from=2026-11-05&to=2026-11-01',headers=h).status_code==400
|
||||
rules=c.get('/api/subscribe/rules',headers=h).json['data'];rule=rules[0]
|
||||
parking=c.get('/api/campus/locations',headers=h).json['data']
|
||||
location=next(p for p in parking if p['kind']=='parking' and p['id']!=rule['location_id'])
|
||||
updated=c.put('/api/subscribe/rules/'+str(rule['id']),headers=h,json={'location_id':location['id'],'time':'12:34','weekday':3,'min_electric':40,'auto_unlock':False,'notify_enabled':True})
|
||||
assert updated.json['rtn_code']==0,updated.json
|
||||
saved=c.get('/api/subscribe/rules',headers=h).json['data'][0]
|
||||
assert saved['minute_of_day']==754 and saved['location_id']==location['id'] and saved['min_electric']==40
|
||||
assert saved['last_run_status']=='success'
|
||||
assert c.put('/api/subscribe/rules/'+str(rule['id']),headers=h,json={'min_electric':90,'max_electric':20}).status_code==400
|
||||
session=c.post('/api/preview/session').json
|
||||
live={'Authorization':'Bearer '+session['data']['token']}
|
||||
assert not c.get('/api/user/orders',headers=live).json['data']
|
||||
assert not c.get('/api/subscribe/rules',headers=live).json['data']
|
||||
with patch('wechat.request_with_user_auth',return_value={'rtn_code':0,'data':{'bicycleStation':[]}}) as upstream:
|
||||
assert c.get('/api/map?type=3',headers=live).json['rtn_code']==0
|
||||
assert c.get('/api/map?type=3',headers=live).json['rtn_code']==0
|
||||
assert upstream.call_count==1, 'live map cache should coalesce requests'
|
||||
assert upstream.call_args.args[0] != 1, 'live requests must use private test account credentials'
|
||||
assert c.put('/api/subscribe/rules/'+str(rule['id']),headers=live,json={'enabled':False}).json['rtn_code']==404
|
||||
with patch('wechat.request_with_user_auth',return_value={'rtn_code':0,'data':{'order_id':'REAL-TEST'}}) as upstream:
|
||||
assert c.post('/api/bicycle',headers=live,json={'code':'51201'}).json['rtn_code']==0
|
||||
assert upstream.call_count==1
|
||||
with patch('email_utils.smtplib.SMTP',side_effect=AssertionError('Demo SMTP')):
|
||||
from email_utils import send_email
|
||||
assert send_email('demo@preview.local','test','body') is True
|
||||
from bike_data import classify,battery
|
||||
assert classify(1,0,10)=='low' and classify(1,1,10)=='used' and classify(4,0,10)=='locked'
|
||||
assert battery(None) is None and battery(0)==0
|
||||
print('PASS: demo isolation, real test account routing, pagination, subscription ownership and full edits')
|
||||
'''
|
||||
result = subprocess.run([sys.executable, "-X", "utf8", "-c", script], cwd=root, env=env, capture_output=True, text=True, timeout=60)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
@@ -4,10 +4,8 @@ import unittest
|
||||
|
||||
class RingAllFrontendAuthTests(unittest.TestCase):
|
||||
def test_ring_all_request_sends_session_token(self):
|
||||
source = (
|
||||
Path(__file__).resolve().parents[1] / "static" / "js" / "map.js"
|
||||
).read_text(encoding="utf-8")
|
||||
request_block = source.split('fetch("/api/ring_all"', 1)[1].split(");", 1)[0]
|
||||
source = (Path(__file__).resolve().parents[1] / "static/js/map-account.js").read_text(encoding="utf-8")
|
||||
request_block = source.split('apiFetch("/api/ring_all"', 1)[1].split(");", 1)[0]
|
||||
|
||||
self.assertIn('"Authorization": `Bearer ${authToken}`', request_block)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user