summaryrefslogtreecommitdiffstats
path: root/net/adblock-fast/tests/lib/mocklib/ubus.uc
blob: ee6d48788457f6e909151bc2e78271a57917ee57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// UBus mock for adblock-fast tests.
// Reused from mwan4's mock with no changes.

let mocklib = global.mocklib; // ucode-lsp disable

return {
	connect: function() {
		let self = this;

		return {
			call: (object, method, args) => {
				let signature = [ object + "~" + method ];

				if (type(args) == "object") {
					for (let i, k in sort(keys(args))) {
						switch (type(args[k])) {
						case "string":
						case "double":
						case "bool":
						case "int":
							push(signature, k + "-" + replace(args[k], /[^A-Za-z0-9_-]+/g, "_"));
							break;

						default:
							push(signature, type(args[k]));
						}
					}
				}

				let candidates = [];

				for (let i = length(signature); i > 0; i--) {
					let path = sprintf("ubus/%s.json", join("~", signature)),
					    mock = mocklib.read_json_file(path);

					if (mock != mock) {
						self._error = "Invalid argument";

						return null;
					}
					else if (mock) {
						mocklib.trace_call("ctx", "call", { object, method, args });

						return mock;
					}

					push(candidates, path);
					pop(signature);
				}

				// Return null silently for unmatched calls (non-critical in tests)
				self._error = "Method not found";

				return null;
			},

			disconnect: () => null,

			error: () => self.error()
		};
	},

	error: function() {
		let e = this._error;
		delete this._error;

		return e;
	}
};