email_parser_test.rb 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # rubocop:disable all
  2. require 'test_helper'
  3. class EmailParserTest < ActiveSupport::TestCase
  4. =begin
  5. to write new .yml files for emails you can use the following code:
  6. File.write('test/data/mail/mailXXX.yml', Channel::EmailParser.new.parse(File.read('test/data/mail/mailXXX.box')).slice(:from, :from_email, :from_display_name, :to, :cc, :subject, :body, :content_type, :'reply-to', :attachments).to_yaml)
  7. =end
  8. test 'parse' do
  9. msg_files = Dir.glob(Rails.root.join('test', 'data', 'mail', 'mail*.box')).sort
  10. messages = []
  11. msg_files.each do |f|
  12. next if !File.exists?(f.ext('yml'))
  13. item = {
  14. source: File.basename(f),
  15. content: YAML.load(File.read(f.ext('yml'))),
  16. parsed: Channel::EmailParser.new.parse(File.read(f)),
  17. }
  18. messages.push item
  19. end
  20. messages.each do |m|
  21. # assert: raw content hash is a subset of parsed message hash
  22. expected_msg = m[:content].except(:attachments)
  23. parsed_msg = m[:parsed].slice(*expected_msg.keys)
  24. expected_msg.each do |key, value|
  25. if value.nil?
  26. assert_nil(parsed_msg[key], "parsed message data does not match test/data/mail/#{m[:source]}: #{key}")
  27. else
  28. assert_equal(value, parsed_msg[key], "parsed message data does not match test/data/mail/#{m[:source]}: #{key}")
  29. end
  30. end
  31. # assert: attachments in parsed message hash match metadata in raw hash
  32. next if m[:content][:attachments].blank?
  33. attachments_found = []
  34. m[:content][:attachments].each do |expected_attachment|
  35. expected_attachment_md5 = Digest::MD5.hexdigest(expected_attachment[:data])
  36. m[:parsed][:attachments].each do |parsed_attachment|
  37. parsed_attachment_md5 = Digest::MD5.hexdigest(parsed_attachment[:data])
  38. next if attachments_found.include?(parsed_attachment_md5)
  39. next if expected_attachment_md5 != parsed_attachment_md5
  40. attachments_found.push parsed_attachment_md5
  41. expected_attachment.each do |key, value|
  42. assert_equal(value, parsed_attachment[key], "#{key} is different in test/data/mail/#{m[:source]}")
  43. end
  44. next
  45. end
  46. end
  47. next if attachments_found.count == m[:content][:attachments].count
  48. m[:content][:attachments].each do |expected_attachment|
  49. next if attachments_found.include?(Digest::MD5.hexdigest(expected_attachment[:data]))
  50. assert(false, "Attachment not found test/data/mail/#{m[:source]}: #{expected_attachment.inspect}")
  51. end
  52. end
  53. end
  54. end