1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4# Copyright 2020 The Chromium OS Authors. All rights reserved. 5# Use of this source code is governed by a BSD-style license that can be 6# found in the LICENSE file. 7 8"""Tests for email_sender.""" 9 10from __future__ import print_function 11 12import contextlib 13import io 14import json 15import unittest 16import unittest.mock as mock 17 18import cros_utils.email_sender as email_sender 19 20 21class Test(unittest.TestCase): 22 """Tests for email_sender.""" 23 24 @mock.patch('cros_utils.email_sender.AtomicallyWriteFile') 25 def test_x20_email_sending_rejects_invalid_inputs(self, write_file): 26 test_cases = [ 27 { 28 # no subject 29 'subject': '', 30 'identifier': 'foo', 31 'direct_recipients': ['gbiv@google.com'], 32 'text_body': 'hi', 33 }, 34 { 35 'subject': 'foo', 36 # no identifier 37 'identifier': '', 38 'direct_recipients': ['gbiv@google.com'], 39 'text_body': 'hi', 40 }, 41 { 42 'subject': 'foo', 43 'identifier': 'foo', 44 # no recipients 45 'direct_recipients': [], 46 'text_body': 'hi', 47 }, 48 { 49 'subject': 'foo', 50 'identifier': 'foo', 51 'direct_recipients': ['gbiv@google.com'], 52 # no body 53 }, 54 { 55 'subject': 'foo', 56 'identifier': 'foo', 57 # direct recipients lack @google. 58 'direct_recipients': ['gbiv'], 59 'text_body': 'hi', 60 }, 61 { 62 'subject': 'foo', 63 'identifier': 'foo', 64 # non-list recipients 65 'direct_recipients': 'gbiv@google.com', 66 'text_body': 'hi', 67 }, 68 { 69 'subject': 'foo', 70 'identifier': 'foo', 71 # non-list recipients 72 'well_known_recipients': 'sheriff', 73 'text_body': 'hi', 74 }, 75 ] 76 77 sender = email_sender.EmailSender() 78 for case in test_cases: 79 with self.assertRaises(ValueError): 80 sender.SendX20Email(**case) 81 82 write_file.assert_not_called() 83 84 @mock.patch('cros_utils.email_sender.AtomicallyWriteFile') 85 def test_x20_email_sending_translates_to_reasonable_json(self, write_file): 86 written_obj = None 87 88 @contextlib.contextmanager 89 def actual_write_file(file_path): 90 nonlocal written_obj 91 92 self.assertTrue( 93 file_path.startswith(email_sender.X20_PATH + '/'), file_path) 94 f = io.StringIO() 95 yield f 96 written_obj = json.loads(f.getvalue()) 97 98 write_file.side_effect = actual_write_file 99 email_sender.EmailSender().SendX20Email( 100 subject='hello', 101 identifier='world', 102 well_known_recipients=['sheriff'], 103 direct_recipients=['gbiv@google.com'], 104 text_body='text', 105 html_body='html', 106 ) 107 108 self.assertEqual( 109 written_obj, { 110 'subject': 'hello', 111 'email_identifier': 'world', 112 'well_known_recipients': ['sheriff'], 113 'direct_recipients': ['gbiv@google.com'], 114 'body': 'text', 115 'html_body': 'html', 116 }) 117 118 119if __name__ == '__main__': 120 unittest.main() 121