Initial project source

这个提交包含在:
apple
2026-11-20 15:32:57 +08:00
当前提交 fb47c07f7c
共修改 8405 个文件,包含 806907 行新增和 0 行删除
+130
查看文件
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Read/query only BI acceptance. No SQL, source scan, migrations, permissions or fixtures are mutated."""
import argparse
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
def request(base, token, path, payload=None):
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}
if os.environ.get('AIXUN_BI_CLIENT_ID'):
headers['clientid'] = os.environ['AIXUN_BI_CLIENT_ID']
req = urllib.request.Request(base + path, headers=headers,
data=None if payload is None else json.dumps(payload).encode('utf-8'))
try:
with urllib.request.urlopen(req, timeout=50) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error:
try:
return error.code, json.load(error)
except (ValueError, TypeError):
return error.code, {}
def assert_query(status, body, case):
"""No transport error, unknown result or authentication expiry counts as the expected policy rejection."""
code = body.get('code')
result = body.get('data') or {}
if case['expect'] == 'DENIED':
denied = status == 403 or code in (403, 149103)
denied = denied or (status == 200 and code == 200 and result.get('state') == 'UNAVAILABLE'
and not result.get('rows') and any(term in result.get('message', '')
for term in case.get('messageContains', [])))
if not denied:
raise ValueError('expected explicit permission or policy denial')
return {'state': 'PASS', 'case': case['name'], 'returnedRows': 0}
if status != 200 or code != 200 or result.get('state') != 'SUCCEEDED' or result.get('truncated'):
raise ValueError('query did not return a complete successful result')
if not result.get('observedAt') or result.get('columns') != case['columns']:
raise ValueError('result evidence or columns mismatch')
rows = sorted((json.dumps(row, ensure_ascii=False, sort_keys=True) for row in result.get('rows', [])))
expected = sorted((json.dumps(row, ensure_ascii=False, sort_keys=True) for row in case['rows']))
if rows != expected:
raise ValueError('fixture result mismatch')
if 'pivotTotals' in case:
totals = result.get('pivotTotals')
expected_totals = case['pivotTotals']
if not isinstance(totals, dict) or totals.get('scope') != 'ALL_FILTERED':
raise ValueError('source pivot totals missing')
for key in ('rowField', 'columnField', 'measure', 'scope', 'grandTotal'):
if key not in totals or totals[key] != expected_totals[key]:
raise ValueError('source pivot total value mismatch')
for key in ('rowTotals', 'columnTotals'):
if not isinstance(totals.get(key), list) or sorted(json.dumps(row, sort_keys=True) for row in totals[key]) \
!= sorted(json.dumps(row, sort_keys=True) for row in expected_totals[key]):
raise ValueError('source pivot total groups mismatch')
return {'state': 'PASS', 'case': case['name'], 'returnedRows': len(rows)}
def run(base, manifest):
source_id = manifest['sourceId']
if not isinstance(source_id, str) or not re.fullmatch(r'[1-9][0-9]{0,18}', source_id):
raise ValueError('sourceId must be an exact string')
if not manifest.get('databaseName') or len(manifest['cases']) > 20:
raise ValueError('fixture scope or cases invalid')
token = os.environ['AIXUN_BI_TOKEN']
status, body = request(base, token, '/api/integration/v1/data-sources/' + source_id)
source = body.get('data') or {}
if status != 200 or body.get('code') != 200 or str(source.get('id')) != source_id \
or source.get('type') not in ('MYSQL', 'MARIADB') or source.get('databaseName') != manifest['databaseName']:
raise ValueError('selected registered test source could not be verified')
expected_tables = manifest['nativeTables']
if set(expected_tables.values()) != {'dg_bi_semantic_orders', 'dg_bi_semantic_departments'}:
raise ValueError('exact two fixture tables required')
for table_id, table_name in expected_tables.items():
if not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', table_id):
raise ValueError('table must be an observed Native UUID')
status, body = request(base, token, '/api/governance/v1/metadata-catalog/TABLE/' + table_id + '?sourceId=' + source_id)
observed = (body.get('data') or {}).get('item') or {}
if status != 200 or body.get('code') != 200 or observed.get('externalId') != table_id or observed.get('name') != table_name:
raise ValueError('fixture Native table does not belong to selected source')
reports = []
for case in manifest['cases']:
if not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', case['objectId']) \
or not isinstance(case['version'], int) or case['version'] < 0 \
or case.get('tokenEnv', 'AIXUN_BI_TOKEN') not in ('AIXUN_BI_TOKEN', 'AIXUN_BI_READER_TOKEN'):
raise ValueError('case identity invalid')
selected_token = os.environ[case.get('tokenEnv', 'AIXUN_BI_TOKEN')]
status, body = request(base, token, '/api/dataproduct/v1/bi/objects/' + case['objectId'])
observed = body.get('data') or {}
spec = observed.get('spec') or {}
if status != 200 or body.get('code') != 200 or observed.get('version') != case['version'] or observed.get('kind') != 'DATASET' or not spec.get('semantic'):
raise ValueError('saved semantic analysis version not verified')
dataset_ids = [spec['sourceDatasetId']] + [d['sourceDatasetId'] for d in spec['semantic']['dimensions']]
for dataset_id in dataset_ids:
if not isinstance(dataset_id, str) or not re.fullmatch(r'[1-9][0-9]{0,18}', dataset_id):
raise ValueError('dataset identity invalid')
status, body = request(base, token, '/api/dataproduct/v1/dataset-publications/' + dataset_id)
dataset = (body.get('data') or {}).get('dataset') or {}
if status != 200 or body.get('code') != 200 or dataset.get('sourceRef') not in {'table:' + table_id for table_id in expected_tables}:
raise ValueError('analysis references a non-fixture source')
status, body = request(base, selected_token, '/api/dataproduct/v1/bi/objects/' + case['objectId'] + '/query', {'version': case['version']})
reports.append(assert_query(status, body, case))
return reports
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base', default='http://127.0.0.1:28000/prod-api')
parser.add_argument('--manifest', required=True)
parser.add_argument('--execute', action='store_true')
args = parser.parse_args()
parsed = urllib.parse.urlparse(args.base)
if parsed.scheme not in ('http', 'https') or parsed.hostname not in ('127.0.0.1', 'localhost') \
or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path != '/prod-api':
raise SystemExit('Only the project local /prod-api gateway is allowed')
try:
with open(args.manifest, encoding='utf-8') as stream:
manifest = json.load(stream)
if not args.execute:
print(json.dumps({'state': 'NOT_RUN', 'cases': len(manifest.get('cases', [])), 'reason': 'requires deployed source identities and explicit --execute'}))
else:
print(json.dumps({'state': 'PASS', 'cases': run(args.base.rstrip('/'), manifest)}, ensure_ascii=False))
except Exception as error:
print(json.dumps({'state': 'FAILED', 'errorType': type(error).__name__, 'reason': 'query evidence mismatch or dependency unavailable; credentials and response withheld'}))
sys.exit(1)