# frozen_string_literal: true require "active_support/core_ext/array/wrap" require "stringio" module DjiMqttConnect module Utils # Generates anonymised fixture data from MQTTX JSON Export Dumps class MqttxFixtureDataGenerator def self.from_file(file_path, **sanitizer_args) raw_data = File.read(file_path) new JSON.parse(raw_data), message_sanitizer: MessageSanitizer.new(**sanitizer_args) end def initialize(mqttx_data, message_sanitizer:) @mqttx_data = mqttx_data @message_sanitizer = message_sanitizer end # Generates fixture data using ALL found messages in the MQTTX export # # # Output is: # : # : def generate extracted_messages.each_with_object(StringIO.new) do |(topic, message), builder| builder.puts [topic, message.to_json].join(": ") end.string end # Generates fixture data using unique found messages in the MQTTX export # # A message is considered unique if the topic and schema does not match any other messages # # # Output is: # : def generate_unique(**schema_generator_args) message_schema_generator = MessageSchemaGenerator.new(**schema_generator_args) unique_messages = extracted_messages.each_with_object({}) do |(topic, message), found| message_schema = message_schema_generator.generate(message) found[[topic, message_schema]] ||= [topic, message] end.values unique_messages.each_with_object(StringIO.new) do |(topic, message), builder| builder.puts [topic, message.to_json].join(": ") end.string end private attr_reader :mqttx_data, :message_sanitizer def extracted_messages return enum_for(:extracted_messages) unless block_given? Array.wrap(mqttx_data).each do |client_output| client_messages = client_output["messages"] client_messages.each do |message| message_topic = message_sanitizer.sanitize_topic(message.fetch("topic")) message_payload = JSON.parse message.fetch("payload") yield(message_topic, message_sanitizer.sanitize_message(message_payload)) end end end end end end