1#!/usr/bin/env python3 2# Copyright 2021 The ChromiumOS Authors 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6# We're testing protected methods, so allow protected access. 7# pylint: disable=protected-access 8 9"""Tests bug filing bits.""" 10 11import json 12import tempfile 13import unittest 14from unittest.mock import patch 15 16import bugs 17 18 19class Tests(unittest.TestCase): 20 """Tests for the bugs module.""" 21 22 def testWritingJSONFileSeemsToWork(self): 23 """Tests JSON file writing.""" 24 old_x20_path = bugs.X20_PATH 25 26 def restore_x20_path(): 27 bugs.X20_PATH = old_x20_path 28 29 self.addCleanup(restore_x20_path) 30 31 with tempfile.TemporaryDirectory() as tempdir: 32 bugs.X20_PATH = tempdir 33 file_path = bugs._WriteBugJSONFile( 34 "ObjectType", 35 { 36 "foo": "bar", 37 "baz": bugs.WellKnownComponents.CrOSToolchainPublic, 38 }, 39 ) 40 41 self.assertTrue( 42 file_path.startswith(tempdir), 43 f"Expected {file_path} to start with {tempdir}", 44 ) 45 46 with open(file_path) as f: 47 self.assertEqual( 48 json.load(f), 49 { 50 "type": "ObjectType", 51 "value": { 52 "foo": "bar", 53 "baz": int( 54 bugs.WellKnownComponents.CrOSToolchainPublic 55 ), 56 }, 57 }, 58 ) 59 60 @patch("bugs._WriteBugJSONFile") 61 def testAppendingToBugsSeemsToWork(self, mock_write_json_file): 62 """Tests AppendToExistingBug.""" 63 bugs.AppendToExistingBug(1234, "hello, world!") 64 mock_write_json_file.assert_called_once_with( 65 "AppendToExistingBugRequest", 66 { 67 "body": "hello, world!", 68 "bug_id": 1234, 69 }, 70 ) 71 72 @patch("bugs._WriteBugJSONFile") 73 def testBugCreationSeemsToWork(self, mock_write_json_file): 74 """Tests CreateNewBug.""" 75 test_case_additions = ( 76 {}, 77 { 78 "component_id": bugs.WellKnownComponents.CrOSToolchainPublic, 79 }, 80 { 81 "assignee": "foo@gbiv.com", 82 "cc": ["bar@baz.com"], 83 }, 84 ) 85 86 for additions in test_case_additions: 87 test_case = { 88 "component_id": 123, 89 "title": "foo", 90 "body": "bar", 91 **additions, 92 } 93 94 bugs.CreateNewBug(**test_case) 95 96 expected_output = { 97 "component_id": test_case["component_id"], 98 "subject": test_case["title"], 99 "body": test_case["body"], 100 } 101 102 assignee = test_case.get("assignee") 103 if assignee: 104 expected_output["assignee"] = assignee 105 106 cc = test_case.get("cc") 107 if cc: 108 expected_output["cc"] = cc 109 110 mock_write_json_file.assert_called_once_with( 111 "FileNewBugRequest", 112 expected_output, 113 ) 114 mock_write_json_file.reset_mock() 115 116 @patch("bugs._WriteBugJSONFile") 117 def testCronjobLogSendingSeemsToWork(self, mock_write_json_file): 118 """Tests SendCronjobLog.""" 119 bugs.SendCronjobLog("my_name", False, "hello, world!") 120 mock_write_json_file.assert_called_once_with( 121 "ChrotomationCronjobUpdate", 122 { 123 "name": "my_name", 124 "message": "hello, world!", 125 "failed": False, 126 }, 127 ) 128 129 130if __name__ == "__main__": 131 unittest.main() 132