Datasets:
Download scripts/test_run_eval.py from Lilambd/empire-eval: direct link, hf CLI and curl.
- Browser
- Download file 8.69 kB
-
https://huggingface.co/datasets/Lilambd/empire-eval/resolve/main/scripts/test_run_eval.py
- Command line
-
hf download hf://datasets/Lilambd/empire-eval/scripts/test_run_eval.py
-
curl -L -o test_run_eval.py https://huggingface.co/datasets/Lilambd/empire-eval/resolve/main/scripts/test_run_eval.py
8.69 kB
| """Offline tests for run_eval.py (urlopen is mocked; no network). | |
| usage: python scripts/test_run_eval.py | |
| """ | |
| import io, json, os, subprocess, sys, tempfile, unittest, urllib.error | |
| from unittest import mock | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| ROOT = os.path.dirname(HERE) | |
| sys.path.insert(0, HERE) | |
| import run_eval as R # noqa: E402 | |
| class FakeResp(io.BytesIO): | |
| def __enter__(self): | |
| return self | |
| def __exit__(self, *a): | |
| return False | |
| def fake(obj): | |
| return FakeResp(json.dumps(obj).encode()) | |
| def args(*extra): | |
| return R.parse_args(['--qa', os.path.join(ROOT, 'data', 'dev'), '--out', '/dev/null', *extra]) | |
| class Extract(unittest.TestCase): | |
| def test_cases(self): | |
| E = R.extract_answer | |
| self.assertEqual(E('Let me think.\nThe table says...\nAnswer: 5601.25'), '5601.25') | |
| self.assertEqual(E('**Answer:** Kino'), 'Kino') | |
| self.assertEqual(E('final answer: true\n'), 'true') | |
| self.assertEqual(E('42'), '42') | |
| self.assertEqual(E('```json\n["VEN", "LBN"]\n```'), '["VEN", "LBN"]') | |
| self.assertEqual(E('[\n "a",\n "b"\n]'), '[ "a", "b" ]') | |
| self.assertEqual(E('reasoning\n\nnull'), 'null') | |
| self.assertEqual(E(''), '') | |
| self.assertIsNone(E(None)) | |
| class Requests(unittest.TestCase): | |
| def test_anthropic(self): | |
| a = args('--provider', 'anthropic', '--system', 'be brief') | |
| seen = {} | |
| def urlopen(req, timeout=None): | |
| seen['url'], seen['body'], seen['h'], seen['t'] = req.full_url, json.loads(req.data), dict(req.header_items()), timeout | |
| return fake({'content': [{'type': 'thinking', 'thinking': 'x'}, {'type': 'text', 'text': 'Answer: 7'}]}) | |
| with mock.patch.dict(os.environ, {'ANTHROPIC_API_KEY': 'sk-test'}), mock.patch('urllib.request.urlopen', urlopen): | |
| raw = R.make_caller(a, {})({'id': 'q1', 'prompt': 'P'}) | |
| self.assertEqual(raw, 'Answer: 7') | |
| self.assertEqual(seen['url'], 'https://api.anthropic.com/v1/messages') | |
| self.assertEqual(seen['body'], {'model': 'claude-sonnet-5-5', 'max_tokens': 512, 'temperature': 0.0, | |
| 'system': 'be brief', 'messages': [{'role': 'user', 'content': 'P'}]}) | |
| h = {k.lower(): v for k, v in seen['h'].items()} | |
| self.assertEqual(h['x-api-key'], 'sk-test') | |
| self.assertEqual(h['anthropic-version'], '2023-06-01') | |
| self.assertEqual(h['content-type'], 'application/json') | |
| self.assertEqual(seen['t'], 120.0) | |
| def test_openai_compatible(self): | |
| a = args('--provider', 'openai', '--base-url', 'http://localhost:8000/v1/', '--model', 'qwen', '--temperature', '-1') | |
| seen = {} | |
| def urlopen(req, timeout=None): | |
| seen['url'], seen['body'], seen['h'] = req.full_url, json.loads(req.data), {k.lower(): v for k, v in req.header_items()} | |
| return fake({'choices': [{'message': {'role': 'assistant', 'content': 'null'}}]}) | |
| with mock.patch.dict(os.environ, {'OPENAI_API_KEY': 'k'}), mock.patch('urllib.request.urlopen', urlopen): | |
| raw = R.make_caller(a, {})({'id': 'q1', 'prompt': 'P'}) | |
| self.assertEqual(raw, 'null') | |
| self.assertEqual(seen['url'], 'http://localhost:8000/v1/chat/completions') | |
| self.assertEqual(seen['body'], {'model': 'qwen', 'max_tokens': 512, 'messages': [{'role': 'user', 'content': 'P'}]}) | |
| self.assertEqual(seen['h']['authorization'], 'Bearer k') | |
| def test_openai_no_key_no_auth_header(self): | |
| a = args('--provider', 'openai', '--model', 'm') | |
| seen = {} | |
| def urlopen(req, timeout=None): | |
| seen['h'] = {k.lower() for k, _ in req.header_items()} | |
| return fake({'choices': [{'message': {'content': None}}]}) | |
| env = {k: v for k, v in os.environ.items() if k != 'OPENAI_API_KEY'} | |
| with mock.patch.dict(os.environ, env, clear=True), mock.patch('urllib.request.urlopen', urlopen): | |
| self.assertEqual(R.make_caller(a, {})({'id': 'q', 'prompt': 'P'}), '') | |
| self.assertNotIn('authorization', seen['h']) | |
| def test_retry_then_success_and_fatal(self): | |
| calls = [] | |
| def urlopen(req, timeout=None): | |
| calls.append(1) | |
| if len(calls) == 1: | |
| raise urllib.error.HTTPError(req.full_url, 429, 'rate', {'retry-after': '2'}, io.BytesIO(b'{}')) | |
| if len(calls) == 2: | |
| raise urllib.error.URLError('reset') | |
| return fake({'ok': 1}) | |
| sleeps = [] | |
| with mock.patch('urllib.request.urlopen', urlopen): | |
| self.assertEqual(R.post_json('http://x', {}, {}, 1, 3, 0.5, _sleep=sleeps.append), {'ok': 1}) | |
| self.assertEqual(len(calls), 3) | |
| self.assertEqual(sleeps[0], 2.0) # honours retry-after | |
| def bad(req, timeout=None): | |
| raise urllib.error.HTTPError(req.full_url, 400, 'bad', {}, io.BytesIO(b'bad request')) | |
| with mock.patch('urllib.request.urlopen', bad): | |
| with self.assertRaises(R.HTTPFail): | |
| R.post_json('http://x', {}, {}, 1, 3, 0.5, _sleep=sleeps.append) | |
| def down(req, timeout=None): | |
| raise urllib.error.HTTPError(req.full_url, 503, 'down', {}, io.BytesIO(b'')) | |
| n = len(sleeps) | |
| with mock.patch('urllib.request.urlopen', down): | |
| with self.assertRaises(R.HTTPFail): | |
| R.post_json('http://x', {}, {}, 1, 2, 0.5, _sleep=sleeps.append) | |
| self.assertEqual(len(sleeps) - n, 2) | |
| class EndToEnd(unittest.TestCase): | |
| def test_prompts_match_make_prompts(self): | |
| with tempfile.TemporaryDirectory() as d: | |
| p = os.path.join(d, 'p.jsonl') | |
| subprocess.check_call([sys.executable, os.path.join(HERE, 'make_prompts.py'), '--qa', | |
| os.path.join(ROOT, 'data', 'test'), '--out', p, '--with-context-hint'], stdout=subprocess.DEVNULL) | |
| want = {json.loads(l)['id']: json.loads(l)['prompt'] for l in open(p)} | |
| a = R.parse_args(['--qa', os.path.join(ROOT, 'data', 'test'), '--with-context-hint', '--provider', 'null', '--out', '/dev/null']) | |
| rows, _ = R.select_rows(a) | |
| self.assertEqual({r['id']: r['prompt'] for r in rows}, want) | |
| def test_sets_limit_resume_and_mocked_api_run(self): | |
| with tempfile.TemporaryDirectory() as d: | |
| out = os.path.join(d, 'pred.jsonl') | |
| argv = ['--qa', os.path.join(ROOT, 'data', 'dev'), '--provider', 'anthropic', '--sets', 'worlds-021-hibe,world-earth', | |
| '--limit', '5', '--out', out, '--concurrency', '3'] | |
| n = [] | |
| def urlopen(req, timeout=None): | |
| n.append(1) | |
| return fake({'content': [{'type': 'text', 'text': 'thinking...\nAnswer: 1'}]}) | |
| with mock.patch.dict(os.environ, {'ANTHROPIC_API_KEY': 'k'}), mock.patch('urllib.request.urlopen', urlopen): | |
| self.assertEqual(R.run(R.parse_args(argv)), 0) | |
| recs = [json.loads(l) for l in open(out)] | |
| self.assertEqual(len(recs), 5) | |
| self.assertTrue(all(set(r) == {'id', 'answer', 'raw', 'latency_ms'} and r['answer'] == '1' for r in recs)) | |
| self.assertTrue(all(r['id'].startswith(('world-earth-', 'lilambd-worlds-021-hibe-')) for r in recs)) | |
| with open(out, 'a') as f: | |
| f.write('{"id": "trunc') # simulated crash mid-line | |
| self.assertEqual(R.run(R.parse_args(argv[:-4] + ['--limit', '7', '--out', out])), 0) | |
| self.assertEqual(len(n), 7) # 5 + only the 2 new ones on resume | |
| with open(out) as f: | |
| recs = [json.loads(l) for l in f] # every line valid JSON again | |
| self.assertEqual(len({r['id'] for r in recs}), 7) | |
| def test_prompts_input_with_sets(self): | |
| with tempfile.TemporaryDirectory() as d: | |
| p, out = os.path.join(d, 'p.jsonl'), os.path.join(d, 'o.jsonl') | |
| subprocess.check_call([sys.executable, os.path.join(HERE, 'make_prompts.py'), '--qa', | |
| os.path.join(ROOT, 'data', 'test'), '--out', p], stdout=subprocess.DEVNULL) | |
| R.run(R.parse_args(['--prompts', p, '--provider', 'random-guess', '--sets', 'worlds-030-dena', '--out', out])) | |
| ids = [json.loads(l)['id'] for l in open(out)] | |
| self.assertEqual(len(ids), 60) | |
| self.assertTrue(all(i.startswith('lilambd-worlds-030-dena-') for i in ids)) | |
| if __name__ == '__main__': | |
| unittest.main(verbosity=2) | |