inventory.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. local item_with_meta = ItemStack({name = "air", meta = {test = "abc"}})
  2. local test_list = {
  3. ItemStack("air"),
  4. ItemStack(""),
  5. ItemStack(item_with_meta),
  6. }
  7. local function compare_lists(a, b)
  8. if not a or not b or #a ~= #b then
  9. return false
  10. end
  11. for i=1, #a do
  12. if not ItemStack(a[i]):equals(ItemStack(b[i])) then
  13. return false
  14. end
  15. end
  16. return true
  17. end
  18. local function test_inventory()
  19. local inv = core.create_detached_inventory("test")
  20. inv:set_lists({test = {""}})
  21. assert(inv:get_list("test"))
  22. assert(inv:get_size("test") == 1)
  23. assert(inv:set_size("test", 3))
  24. assert(not inv:set_size("test", -1))
  25. assert(inv:get_width("test") == 0)
  26. assert(inv:set_width("test", 3))
  27. assert(not inv:set_width("test", -1))
  28. inv:set_stack("test", 1, "air")
  29. inv:set_stack("test", 3, item_with_meta)
  30. assert(not inv:is_empty("test"))
  31. assert(compare_lists(inv:get_list("test"), test_list))
  32. assert(inv:add_item("test", "air") == ItemStack())
  33. assert(inv:add_item("test", item_with_meta) == ItemStack())
  34. assert(inv:get_stack("test", 1) == ItemStack("air 2"))
  35. assert(inv:room_for_item("test", "air 99"))
  36. inv:set_stack("test", 2, "air 99")
  37. assert(not inv:room_for_item("test", "air 99"))
  38. inv:set_stack("test", 2, "")
  39. assert(inv:contains_item("test", "air"))
  40. assert(not inv:contains_item("test", "air 99"))
  41. assert(inv:contains_item("test", item_with_meta, true))
  42. -- Items should be removed in reverse and combine with first stack removed
  43. assert(inv:remove_item("test", "air") == item_with_meta)
  44. item_with_meta:set_count(2)
  45. assert(inv:remove_item("test", "air 2") == item_with_meta)
  46. assert(inv:remove_item("test", "air") == ItemStack("air"))
  47. assert(inv:is_empty("test"))
  48. -- Failure of set_list(s) should not change inventory
  49. local before = inv:get_list("test")
  50. pcall(inv.set_lists, inv, {test = true})
  51. pcall(inv.set_list, inv, "test", true)
  52. local after = inv:get_list("test")
  53. assert(compare_lists(before, after))
  54. local location = inv:get_location()
  55. assert(core.remove_detached_inventory("test"))
  56. assert(not core.get_inventory(location))
  57. end
  58. unittests.register("test_inventory", test_inventory)