test_batch.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding:utf-8 -*-
  2. from pathlib import Path
  3. import pytest
  4. from dw_base.datax.batch import expand_ini_inputs, run_batch
  5. def test_expand_ini_inputs_single_and_dir(tmp_path: Path):
  6. d = tmp_path / 'inis'
  7. d.mkdir()
  8. (d / 'a.ini').write_text('', encoding='utf-8')
  9. (d / 'b.ini').write_text('', encoding='utf-8')
  10. (d / 'c.txt').write_text('', encoding='utf-8') # 非 .ini 应被忽略
  11. extra = tmp_path / 'x.ini'
  12. extra.write_text('', encoding='utf-8')
  13. result = expand_ini_inputs([str(extra)], [str(d)])
  14. names = [Path(p).name for p in result]
  15. assert names == ['x.ini', 'a.ini', 'b.ini'] # 先 ini 参数、再目录扫描、排序
  16. def test_expand_ini_inputs_dedup(tmp_path: Path):
  17. d = tmp_path / 'inis'
  18. d.mkdir()
  19. (d / 'a.ini').write_text('', encoding='utf-8')
  20. # 同一 ini 既通过 -ini 又通过 -inis 传入,只保留一份
  21. result = expand_ini_inputs([str(d / 'a.ini')], [str(d)])
  22. assert len(result) == 1
  23. def test_expand_ini_inputs_dir_not_exist_raises(tmp_path: Path):
  24. with pytest.raises(ValueError, match='ini 目录不存在'):
  25. expand_ini_inputs([], [str(tmp_path / 'nonexistent')])
  26. def test_run_batch_serial_success_and_fail_counts():
  27. calls = []
  28. def run_one(ini):
  29. calls.append(ini)
  30. return 0 if 'good' in ini else 1
  31. success, failed = run_batch(['good_1.ini', 'bad_1.ini', 'good_2.ini'], run_one, parallel=False)
  32. assert success == 2
  33. assert failed == 1
  34. assert calls == ['good_1.ini', 'bad_1.ini', 'good_2.ini'] # 串行顺序
  35. def test_run_batch_empty_inis():
  36. assert run_batch([], lambda p: 0) == (0, 0)
  37. def test_run_batch_parallel_counts():
  38. import threading
  39. lock = threading.Lock()
  40. seen = []
  41. def run_one(ini):
  42. with lock:
  43. seen.append(ini)
  44. return 0 if 'good' in ini else 1
  45. success, failed = run_batch(['good_1.ini', 'bad_1.ini', 'good_2.ini'],
  46. run_one, parallel=True, sleep_between=0)
  47. assert success == 2
  48. assert failed == 1
  49. assert set(seen) == {'good_1.ini', 'bad_1.ini', 'good_2.ini'} # 并行无顺序保证
  50. def test_run_batch_parallel_exception_counts_as_failure():
  51. def run_one(ini):
  52. raise RuntimeError('boom')
  53. success, failed = run_batch(['a.ini'], run_one, parallel=True, sleep_between=0)
  54. assert success == 0
  55. assert failed == 1