util.stanza: Validate input to clone() (with brief tests) 0.11
authorKim Alvefur <zash@zash.se>
Sat, 17 Nov 2018 15:26:11 +0100
branch0.11
changeset 9634 bff66c3faceb
parent 9632 2fcf517b811e
child 9635 d6104aaf94bc
util.stanza: Validate input to clone() (with brief tests)
spec/util_stanza_spec.lua
util/stanza.lua
--- a/spec/util_stanza_spec.lua	Thu Nov 15 21:55:16 2018 +0000
+++ b/spec/util_stanza_spec.lua	Sat Nov 17 15:26:11 2018 +0100
@@ -346,4 +346,18 @@
 			end, "Invalid stanza");
 		end);
 	end);
+
+	describe("#clone", function ()
+		it("works", function ()
+			local s = st.message({type="chat"}, "Hello"):reset();
+			local c = st.clone(s);
+			assert.same(s, c);
+		end);
+
+		it("works", function ()
+			assert.has_error(function ()
+				st.clone("this is not a stanza");
+			end);
+		end);
+	end);
 end);
--- a/util/stanza.lua	Thu Nov 15 21:55:16 2018 +0000
+++ b/util/stanza.lua	Sat Nov 17 15:26:11 2018 +0100
@@ -398,7 +398,7 @@
 	return stanza;
 end
 
-local function clone(stanza)
+local function _clone(stanza)
 	local attr, tags = {}, {};
 	for k,v in pairs(stanza.attr) do attr[k] = v; end
 	local old_namespaces, namespaces = stanza.namespaces;
@@ -410,7 +410,7 @@
 	for i=1,#stanza do
 		local child = stanza[i];
 		if child.name then
-			child = clone(child);
+			child = _clone(child);
 			t_insert(tags, child);
 		end
 		t_insert(new, child);
@@ -418,6 +418,13 @@
 	return setmetatable(new, stanza_mt);
 end
 
+local function clone(stanza)
+	if not is_stanza(stanza) then
+		error("bad argument to clone: expected stanza, got "..type(stanza));
+	end
+	return _clone(stanza);
+end
+
 local function message(attr, body)
 	if not body then
 		return new_stanza("message", attr);