spec/util_argparse_spec.lua
author Kim Alvefur <zash@zash.se>
Wed, 27 Mar 2024 19:33:11 +0100
changeset 13471 c2a476f4712a
parent 13164 4ee9a912ceea
permissions -rw-r--r--
util.startup: Fix exiting on pidfile trouble prosody.shutdown() relies on prosody.main_thread, which has not been set yet at this point. Doing a clean shutdown might actually be harmful in case it tears down things set up by the conflicting Prosody, such as the very pidfile we were looking at. Thanks again SigmaTel71 for noticing

describe("parse", function()
	local parse
	setup(function() parse = require"util.argparse".parse; end);

	it("works", function()
		-- basic smoke test
		local opts = parse({ "--help" });
		assert.same({ help = true }, opts);
	end);

	it("returns if no args", function() assert.same({}, parse({})); end);

	it("supports boolean flags", function()
		local opts, err = parse({ "--foo"; "--no-bar" });
		assert.falsy(err);
		assert.same({ foo = true; bar = false }, opts);
	end);

	it("consumes input until the first argument", function()
		local arg = { "--foo"; "bar"; "--baz" };
		local opts, err = parse(arg);
		assert.falsy(err);
		assert.same({ foo = true, "bar", "--baz" }, opts);
		assert.same({ "bar"; "--baz" }, arg);
	end);

	it("expands short options", function()
		local opts, err = parse({ "--foo"; "-b" }, { short_params = { b = "bar" } });
		assert.falsy(err);
		assert.same({ foo = true; bar = true }, opts);
	end);

	it("supports value arguments", function()
		local opts, err = parse({ "--foo"; "bar"; "--baz=moo" }, { value_params = { foo = true; bar = true } });
		assert.falsy(err);
		assert.same({ foo = "bar"; baz = "moo" }, opts);
	end);

	it("demands values for value params", function()
		local opts, err, where = parse({ "--foo" }, { value_params = { foo = true } });
		assert.falsy(opts);
		assert.equal("missing-value", err);
		assert.equal("--foo", where);
	end);

	it("reports where the problem is", function()
		local opts, err, where = parse({ "-h" });
		assert.falsy(opts);
		assert.equal("param-not-found", err);
		assert.equal("-h", where, "returned where");
	end);

	it("supports array arguments", function ()
		local opts, err = parse({ "--item"; "foo"; "--item"; "bar" }, { array_params = { item = true } });
		assert.falsy(err);
		assert.same({"foo","bar"}, opts.item);
	end)
end);