require_relative "test_helper" require "socket" require_relative "../lib/maptool/mqtt_client" class MqttClientTest < Minitest::Test # A one-connection fake broker: checks CONNECT/SUBSCRIBE, then sends a QoS 0 # and a QoS 1 PUBLISH and records what the client sends back. def test_connects_subscribes_and_yields_messages server = TCPServer.new("127.0.0.1", 0) port = server.addr[1] seen = {} broker = Thread.new do conn = server.accept type, body = read_packet(conn) seen[:connect] = [type, body] conn.write("\x20\x02\x00\x00".b) # CONNACK, accepted type, body = read_packet(conn) seen[:subscribe] = [type, body] conn.write("\x90\x04\x00\x01\x00\x00".b) # SUBACK conn.write(publish("mcu-tracker/location", '{"latitude":48.1}', qos: 0)) conn.write(publish("mcu-its-g5/decoded", '{"id":"a"}', qos: 1, packet_id: 7)) seen[:puback] = read_packet(conn) sleep 0.2 conn.close end client = Maptool::MqttClient.new(url: "mqtt://127.0.0.1:#{port}", username: "maptool", password: "secret", topics: ["mcu-tracker/location", "mcu-its-g5/decoded"], client_id: "test") messages = [] worker = Thread.new { client.each_message { |topic, payload| messages << [topic, payload] } } broker.join(5) sleep 0.1 worker.kill assert_equal [["mcu-tracker/location", '{"latitude":48.1}'], ["mcu-its-g5/decoded", '{"id":"a"}']], messages type, body = seen[:connect] assert_equal 1, type assert_includes body, "MQTT".b assert_equal 0xC2, body.getbyte(7) # clean session + username + password assert_includes body, "maptool".b assert_includes body, "secret".b type, body = seen[:subscribe] assert_equal 8, type assert_includes body, "mcu-its-g5/decoded".b assert_equal [4, "\x00\x07".b], seen[:puback] # PUBACK for packet 7 ensure server&.close end def test_rejects_other_url_schemes assert_raises(ArgumentError) { Maptool::MqttClient.new(url: "http://broker:1883", topics: []) } end private def read_packet(conn) header = conn.read(1).ord length = conn.read(1).ord # tests stay under 128 bytes [header >> 4, conn.read(length)] end def publish(topic, payload, qos:, packet_id: nil) body = [topic.bytesize].pack("n") + topic.b + (qos.positive? ? [packet_id].pack("n") : "".b) + payload.b [0x30 | (qos << 1), body.bytesize].pack("CC") + body end end