email_parser_test.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. assert_equal(value, parsed_msg[key], "parsed message data does not match test/data/mail/#{m[:source]}: #{key}")
  26. end
  27. # assert: attachments in parsed message hash match metadata in raw hash
  28. next if m[:content][:attachments].blank?
  29. attachments_found = []
  30. m[:content][:attachments].each do |expected_attachment|
  31. expected_attachment_md5 = Digest::MD5.hexdigest(expected_attachment[:data])
  32. m[:parsed][:attachments].each do |parsed_attachment|
  33. parsed_attachment_md5 = Digest::MD5.hexdigest(parsed_attachment[:data])
  34. next if attachments_found.include?(parsed_attachment_md5)
  35. next if expected_attachment_md5 != parsed_attachment_md5
  36. attachments_found.push parsed_attachment_md5
  37. expected_attachment.each do |key, value|
  38. assert_equal(value, parsed_attachment[key], "#{key} is different")
  39. end
  40. next
  41. end
  42. end
  43. next if attachments_found.count == m[:content][:attachments].count
  44. m[:content][:attachments].each do |expected_attachment|
  45. next if attachments_found.include?(Digest::MD5.hexdigest(expected_attachment[:data]))
  46. assert(false, "Attachment not found test/data/mail/#{m[:source]}: #{expected_attachment.inspect}")
  47. end
  48. end
  49. end
  50. end