1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4# Copyright 2020 The ChromiumOS Authors 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 10 11import contextlib 12import io 13import json 14import unittest 15import unittest.mock as mock 16 17import cros_utils.email_sender as email_sender 18 19 20class Test(unittest.TestCase): 21 """Tests for email_sender.""" 22 23 @mock.patch("cros_utils.email_sender.AtomicallyWriteFile") 24 def test_x20_email_sending_rejects_invalid_inputs(self, write_file): 25 test_cases = [ 26 { 27 # no subject 28 "subject": "", 29 "identifier": "foo", 30 "direct_recipients": ["[email protected]"], 31 "text_body": "hi", 32 }, 33 { 34 "subject": "foo", 35 # no identifier 36 "identifier": "", 37 "direct_recipients": ["[email protected]"], 38 "text_body": "hi", 39 }, 40 { 41 "subject": "foo", 42 "identifier": "foo", 43 # no recipients 44 "direct_recipients": [], 45 "text_body": "hi", 46 }, 47 { 48 "subject": "foo", 49 "identifier": "foo", 50 "direct_recipients": ["[email protected]"], 51 # no body 52 }, 53 { 54 "subject": "foo", 55 "identifier": "foo", 56 # direct recipients lack @google. 57 "direct_recipients": ["gbiv"], 58 "text_body": "hi", 59 }, 60 { 61 "subject": "foo", 62 "identifier": "foo", 63 # non-list recipients 64 "direct_recipients": "[email protected]", 65 "text_body": "hi", 66 }, 67 { 68 "subject": "foo", 69 "identifier": "foo", 70 # non-list recipients 71 "well_known_recipients": "detective", 72 "text_body": "hi", 73 }, 74 ] 75 76 sender = email_sender.EmailSender() 77 for case in test_cases: 78 with self.assertRaises(ValueError): 79 sender.SendX20Email(**case) 80 81 write_file.assert_not_called() 82 83 @mock.patch("cros_utils.email_sender.AtomicallyWriteFile") 84 def test_x20_email_sending_translates_to_reasonable_json(self, write_file): 85 written_obj = None 86 87 @contextlib.contextmanager 88 def actual_write_file(file_path): 89 nonlocal written_obj 90 91 self.assertTrue( 92 file_path.startswith(email_sender.X20_PATH + "/"), file_path 93 ) 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=["detective"], 103 direct_recipients=["[email protected]"], 104 text_body="text", 105 html_body="html", 106 ) 107 108 self.assertEqual( 109 written_obj, 110 { 111 "subject": "hello", 112 "email_identifier": "world", 113 "well_known_recipients": ["detective"], 114 "direct_recipients": ["[email protected]"], 115 "body": "text", 116 "html_body": "html", 117 }, 118 ) 119 120 121if __name__ == "__main__": 122 unittest.main() 123