test_bindings.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import pytest
  2. from cq2_sdk.lua_bridge.runtime import LuaRuntime
  3. from cq2_sdk.lua_bridge.loader import LuaLoader
  4. from cq2_sdk.lua_bridge.bindings import Cq2Lua
  5. @pytest.fixture
  6. def cq2lua_with_fakes(tmp_path):
  7. """Set up fake Lua modules and return a Cq2Lua pointing at them."""
  8. (tmp_path / "encode_util.lua").write_text(
  9. """
  10. local M = {}
  11. -- Note: avoid string.gsub (returns tuple of (result, count)).
  12. -- Use explicit loop so the function returns a single string.
  13. M.Encode6BitBuf = function(s)
  14. local r = ""
  15. for i = 1, #s do
  16. r = r .. string.format("%02x", s:byte(i))
  17. end
  18. return r
  19. end
  20. M.Decode6BitBuf = function(s) return s end
  21. _G.encode_util = M
  22. return M
  23. """
  24. )
  25. (tmp_path / "crypto_util.lua").write_text(
  26. """
  27. local M = {}
  28. M.md5 = function(s) return s .. "_md5" end
  29. M.sha1 = function(s) return s .. "_sha1" end
  30. M.aes_encrypt = function(p, k) return p .. "_aes(" .. k .. ")" end
  31. M.aes_decrypt = function(c, k) return c end
  32. _G.crypto_util = M
  33. return M
  34. """
  35. )
  36. rt = LuaRuntime(lua_path=str(tmp_path))
  37. loader = LuaLoader(rt, str(tmp_path))
  38. return Cq2Lua(rt, loader)
  39. def test_encode6bit(cq2lua_with_fakes):
  40. assert cq2lua_with_fakes.encode6bit("abc") == "616263"
  41. def test_md5(cq2lua_with_fakes):
  42. assert cq2lua_with_fakes.md5("hello") == "hello_md5"
  43. def test_sha1(cq2lua_with_fakes):
  44. assert cq2lua_with_fakes.sha1("x") == "x_sha1"
  45. def test_aes_encrypt(cq2lua_with_fakes):
  46. assert cq2lua_with_fakes.aes_encrypt("p", "k") == "p_aes(k)"
  47. def test_lazy_load(cq2lua_with_fakes):
  48. # Should work even without pre-loading
  49. assert cq2lua_with_fakes.sha1("y") == "y_sha1"
  50. def test_missing_binding_raises_attributeerror(cq2lua_with_fakes):
  51. with pytest.raises(AttributeError):
  52. cq2lua_with_fakes.nonexistent_method()