# -*- coding: utf-8 -*-
"""只操作本程序创建的临时对象；全部数据为合成样本。"""
import os, sys, json, sqlite3, tempfile, pathlib, subprocess, time, socket, stat
from pathlib import Path
def emit(**kw):
    print(json.dumps(kw, ensure_ascii=False, sort_keys=True))

import shutil
PROMTOOL=os.environ.get('PROMTOOL') or shutil.which('promtool')
assert PROMTOOL, '请安装官方Prometheus 3.5.0并将promtool加入PATH或设置PROMTOOL绝对路径'
def prom_test(data, rules=None, expected_failure=False):
    with tempfile.TemporaryDirectory(prefix='ywebs-next132-b2-prom-') as d:
        p=Path(d)
        if rules is not None:
            (p/'rules.yml').write_text(json.dumps(rules),encoding='utf-8')
            data['rule_files']=['rules.yml']
        (p/'test.yml').write_text(json.dumps(data),encoding='utf-8')
        r=subprocess.run([PROMTOOL,'test','rules','test.yml'],cwd=d,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,universal_newlines=True)
        if expected_failure: assert r.returncode!=0 and 'many-to-many' in r.stdout,r.stdout
        else: assert r.returncode==0,r.stdout
        return {'returncode':r.returncode,'output':r.stdout}
rules={'groups':[{'name':'units','rules':[{'record':'demo_latency_seconds','expr':'demo_latency_ms / 1000'}]}]}
series=[{'series':'demo_latency_ms{instance="fast"}','values':'300 300'},{'series':'demo_latency_ms{instance="slow"}','values':'1000 1000'}]
checks=[{'expr':'demo_latency_seconds > .8','eval_time':'1m','exp_samples':[{'labels':'demo_latency_seconds{instance="slow"}','value':1}]},{'expr':'demo_latency_ms > .8','eval_time':'1m','exp_samples':[{'labels':'demo_latency_ms{instance="fast"}','value':300},{'labels':'demo_latency_ms{instance="slow"}','value':1000}]},{'expr':'demo_latency_seconds{instance="fast"}','eval_time':'1m','exp_samples':[{'labels':'demo_latency_seconds{instance="fast"}','value':.3}]}]
r=prom_test({'tests':[{'interval':'1m','input_series':series,'promql_expr_test':checks}]},rules); emit(correct_alerts=1,wrong_alerts=2,fast_seconds=.3,engine=r)
