Created
December 10, 2014 13:48
-
-
Save c-spencer/ba0b56ced05193974908 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var functions = { | |
add: function (args) { | |
return args.reduce(function (a, b) { return a + b }); | |
}, | |
twoarg: function (a, b) { | |
return a * b; | |
}, | |
async: function (a, cb) { | |
var state = this.state; | |
setTimeout(function () { | |
cb(a + state.val); | |
}, 100); | |
}, | |
add_state: function (x) { | |
this.state.val += x; | |
}, | |
timeout: function (x) { | |
setTimeout(function () { | |
cb(x); | |
}, x); | |
}, | |
call: function (a, b, cb) { | |
this.call('multiply', [a, b], function (c) { | |
cb(c); | |
}); | |
} | |
}; | |
function Server(state) { | |
this.state = state; | |
}; | |
// Convert ["fn", 4, 5] to functions.fn.apply(state, [4, 5, cb]) | |
Server.prototype.handle_call = function (args, cb) { | |
return functions[args[0]].apply(this, args.slice(1).concat([cb])); | |
}; | |
Server.prototype.handle_cast = function (args) { | |
var cb = function () {}; | |
return functions[args[0]].apply(this, args.slice(1).concat([cb])); | |
}; | |
module.exports = Server; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule JSGenServerTest.TestServer do | |
use JSGenServer, path: "/fixtures/adder.js" | |
def multiply(a, b) do | |
a * b | |
end | |
end | |
defmodule JSGenServerTest do | |
use ExUnit.Case | |
setup do | |
{:ok, pid} = JSGenServerTest.TestServer.start_link(%{val: 10}, name: Adder) | |
{:ok, [pid: pid]} | |
end | |
test "basic functionality", %{pid: pid} do | |
assert GenServer.call(pid, {:add, Enum.to_list(1..4)}) == 10 | |
assert GenServer.call(pid, {:twoarg, 6, 7}) == 42 | |
assert GenServer.call(pid, {:async, 5}) == 15 | |
end | |
test "named servers" do | |
assert GenServer.call(Adder, {:add, Enum.to_list(1..4)}) == 10 | |
end | |
test "external calls" do | |
assert GenServer.call(Adder, {:call, 6, 9}) == 54 | |
assert GenServer.call(Adder, {:call, 7, 9}) == 63 | |
assert GenServer.call(Adder, {:call, 8, 9}) == 72 | |
end | |
test "casts", %{pid: pid} do | |
assert GenServer.call(pid, {:async, 5}) == 15 | |
assert GenServer.cast(pid, {:add_state, 5}) | |
assert GenServer.call(pid, {:async, 5}) == 20 | |
end | |
test "timeouts", %{pid: pid} do | |
assert {:timeout, {GenServer, :call, [^pid, {:timeout, 500}, 100]}} | |
= catch_exit(GenServer.call(pid, {:timeout, 500}, 100)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment