test_mask.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # -*- coding:utf-8 -*-
  2. import pytest
  3. from dw_base.datax.mask import build_query_sql, resolve_template
  4. def test_static_month_trunc():
  5. tpl = resolve_template('postgresql', 'month_trunc')
  6. assert tpl == "TO_CHAR({col}, 'YYYY-MM') AS {col}"
  7. def test_static_md5():
  8. tpl = resolve_template('postgresql', 'md5')
  9. assert tpl == 'MD5({col}::text) AS {col}'
  10. def test_dynamic_keep_last_4():
  11. tpl = resolve_template('postgresql', 'keep_last_4')
  12. assert tpl == "'****' || RIGHT({col}::text, 4) AS {col}"
  13. def test_dynamic_keep_last_10():
  14. tpl = resolve_template('postgresql', 'keep_last_10')
  15. assert 'RIGHT({col}::text, 10)' in tpl
  16. def test_dynamic_keep_first_3():
  17. tpl = resolve_template('postgresql', 'keep_first_3')
  18. assert tpl == "LEFT({col}::text, 3) || '****' AS {col}"
  19. def test_build_query_sql_mixed():
  20. sql = build_query_sql(
  21. db_type='postgresql',
  22. columns=['id', 'cert_birthday', 'phone'],
  23. mask_config={'cert_birthday': 'month_trunc', 'phone': 'keep_last_4'},
  24. table='public.t',
  25. where="create_time >= '${start_date}'",
  26. )
  27. assert 'SELECT id,' in sql
  28. assert "TO_CHAR(cert_birthday, 'YYYY-MM') AS cert_birthday" in sql
  29. assert "RIGHT(phone::text, 4)" in sql
  30. assert 'FROM public.t' in sql
  31. assert "WHERE create_time >= '${start_date}'" in sql
  32. def test_invalid_col_name_rejects_injection():
  33. with pytest.raises(ValueError, match='非法列名'):
  34. build_query_sql('postgresql', ['id; DROP TABLE x'], {}, 'public.t', '')
  35. def test_unknown_mask_type():
  36. with pytest.raises(ValueError, match='未知脱敏类型'):
  37. build_query_sql('postgresql', ['phone'], {'phone': 'bogus_mask'}, 'public.t', '')
  38. def test_mask_col_not_in_columns():
  39. with pytest.raises(ValueError, match='不在 reader.column 中'):
  40. build_query_sql('postgresql', ['id'], {'phone': 'md5'}, 'public.t', '')