Created
September 6, 2011 13:03
-
-
Save ah-itagile/1197478 to your computer and use it in GitHub Desktop.
Second try to solve the ccc-kata with ruby, this time with a tdd approach
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
require 'test/unit' | |
require 'socket' | |
class CCCResponder | |
def init_socket | |
@hostname = 'localhost' | |
@send_port = 9001 | |
@rec_port = 9000 | |
@rec_buffer = 1024 | |
@rec_socket = UDPSocket.new | |
@rec_socket.bind($hostname, @rec_port) | |
end | |
def operator(line) | |
line.split(':')[0] | |
end | |
def params(line) | |
line.split(':')[2..-1].map &:to_i | |
end | |
def uuid(line) | |
line.split(':')[1] | |
end | |
def calc_result(line) | |
ops = { | |
'ADD' => :+, | |
'SUBTRACT' => :-, | |
'MULTIPLY' => :* | |
} | |
op = ops[operator(line)] | |
params(line).reduce(op) | |
end | |
def generate_response(line) | |
uuid(line) + ':' + calc_result(line).to_s | |
end | |
def receive | |
@rec_socket.recvfrom(@rec_buffer)[0] | |
end | |
def respond_to line | |
response = generate_response(line) | |
UDPSocket.new.send(response, 0, @hostname, @send_port) | |
end | |
def response_loop | |
init_socket | |
line = receive() | |
while operator(line) != '__SHUTDOWN__' | |
respond_to line | |
line = receive() | |
end | |
@rec_socket.close | |
end | |
end | |
responder = CCCResponder.new | |
responder.response_loop | |
class TestCCCResponder < Test::Unit::TestCase | |
def setup | |
@responder = CCCResponder.new | |
end | |
def test_extract_operator | |
assert_equal( 'operator', @responder.operator('operator:uuid:param1:param2')) | |
end | |
def test_extract_uuid | |
assert_equal( 'uuid', @responder.uuid('operator:uuid:param1:param2')) | |
end | |
def test_extract_params_as_int_values | |
assert_equal( [ 1, 2], @responder.params('op:uuid:1:2')) | |
end | |
def test_calc_result_for_addition | |
assert_equal( 6, @responder.calc_result('ADD:uuid:1:2:3')) | |
end | |
def test_calc_result_for_subtraction | |
assert_equal( -4, @responder.calc_result('SUBTRACT:uuid:1:2:3')) | |
end | |
def test_calc_result_for_multiplication | |
assert_equal( 24, @responder.calc_result('MULTIPLY:uuid:1:2:3:4')) | |
end | |
def test_generate_response | |
assert_equal('uuidabc:6', @responder.generate_response('ADD:uuidabc:1:2:3')) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment