aboutsummaryrefslogtreecommitdiff
path: root/cros_utils/bugs_test.py
blob: 1ee6bfe4b7ec418cc1b21f5911c28c49048aa012 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python3
# Copyright 2021 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# We're testing protected methods, so allow protected access.
# pylint: disable=protected-access

"""Tests bug filing bits."""

import datetime
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest import mock
from unittest.mock import patch

from cros_utils import bugs


_ARBITRARY_DATETIME = datetime.datetime(2020, 1, 1, 23, 0, 0, 0)


class Tests(unittest.TestCase):
    """Tests for the bugs module."""

    def testWritingJSONFileSeemsToWork(self):
        """Tests JSON file writing."""
        old_x20_path = bugs.X20_PATH

        def restore_x20_path():
            bugs.X20_PATH = old_x20_path

        self.addCleanup(restore_x20_path)

        with tempfile.TemporaryDirectory() as tempdir:
            bugs.X20_PATH = tempdir
            file_path = bugs._WriteBugJSONFile(
                "ObjectType",
                {
                    "foo": "bar",
                    "baz": bugs.WellKnownComponents.CrOSToolchainPublic,
                },
                None,
            )

            self.assertTrue(
                file_path.startswith(tempdir),
                f"Expected {file_path} to start with {tempdir}",
            )

            with open(file_path, encoding="utf-8") as f:
                self.assertEqual(
                    json.load(f),
                    {
                        "type": "ObjectType",
                        "value": {
                            "foo": "bar",
                            "baz": int(
                                bugs.WellKnownComponents.CrOSToolchainPublic
                            ),
                        },
                    },
                )

    @patch.object(bugs, "_WriteBugJSONFile")
    def testAppendingToBugsSeemsToWork(self, mock_write_json_file):
        """Tests AppendToExistingBug."""
        bugs.AppendToExistingBug(1234, "hello, world!")
        mock_write_json_file.assert_called_once_with(
            "AppendToExistingBugRequest",
            {
                "body": "hello, world!",
                "bug_id": 1234,
            },
            None,
        )

    @patch.object(bugs, "_WriteBugJSONFile")
    def testBugCreationSeemsToWork(self, mock_write_json_file):
        """Tests CreateNewBug."""
        test_case_additions = (
            {},
            {
                "component_id": bugs.WellKnownComponents.CrOSToolchainPublic,
            },
            {
                "assignee": "foo@gbiv.com",
                "cc": ["bar@baz.com"],
            },
        )

        for additions in test_case_additions:
            test_case = {
                "component_id": 123,
                "title": "foo",
                "body": "bar",
                **additions,
            }

            bugs.CreateNewBug(**test_case)

            expected_output = {
                "component_id": test_case["component_id"],
                "subject": test_case["title"],
                "body": test_case["body"],
            }

            assignee = test_case.get("assignee")
            if assignee:
                expected_output["assignee"] = assignee

            cc = test_case.get("cc")
            if cc:
                expected_output["cc"] = cc

            mock_write_json_file.assert_called_once_with(
                "FileNewBugRequest",
                expected_output,
                None,
            )
            mock_write_json_file.reset_mock()

    @patch.object(bugs, "_WriteBugJSONFile")
    def testCronjobLogSendingSeemsToWork(self, mock_write_json_file):
        """Tests SendCronjobLog."""
        bugs.SendCronjobLog("my_name", False, "hello, world!")
        mock_write_json_file.assert_called_once_with(
            "CronjobUpdate",
            {
                "name": "my_name",
                "message": "hello, world!",
                "failed": False,
            },
            None,
        )

    @patch.object(bugs, "_WriteBugJSONFile")
    def testCronjobLogSendingSeemsToWorkWithTurndown(
        self, mock_write_json_file
    ):
        """Tests SendCronjobLog."""
        bugs.SendCronjobLog(
            "my_name", False, "hello, world!", turndown_time_hours=42
        )
        mock_write_json_file.assert_called_once_with(
            "CronjobUpdate",
            {
                "name": "my_name",
                "message": "hello, world!",
                "failed": False,
                "cronjob_turndown_time_hours": 42,
            },
            None,
        )

    def testFileNameGenerationProducesFileNamesInSortedOrder(self):
        """Tests that _FileNameGenerator gives us sorted file names."""
        gen = bugs._FileNameGenerator()
        first = gen.generate_json_file_name(_ARBITRARY_DATETIME)
        second = gen.generate_json_file_name(_ARBITRARY_DATETIME)
        self.assertLess(first, second)

    def testFileNameGenerationProtectsAgainstRipplingAdds(self):
        """Tests that _FileNameGenerator gives us sorted file names."""
        gen = bugs._FileNameGenerator()
        gen._entropy = 9
        first = gen.generate_json_file_name(_ARBITRARY_DATETIME)
        second = gen.generate_json_file_name(_ARBITRARY_DATETIME)
        self.assertLess(first, second)

        gen = bugs._FileNameGenerator()
        all_9s = "9" * (gen._ENTROPY_STR_SIZE - 1)
        gen._entropy = int(all_9s)
        third = gen.generate_json_file_name(_ARBITRARY_DATETIME)
        self.assertLess(second, third)

        fourth = gen.generate_json_file_name(_ARBITRARY_DATETIME)
        self.assertLess(third, fourth)

    @patch.object(os, "getpid")
    def testForkingProducesADifferentReport(self, mock_getpid):
        """Tests that _FileNameGenerator gives us sorted file names."""
        gen = bugs._FileNameGenerator()

        mock_getpid.return_value = 1
        gen._entropy = 0
        parent_file = gen.generate_json_file_name(_ARBITRARY_DATETIME)

        mock_getpid.return_value = 2
        gen._entropy = 0
        child_file = gen.generate_json_file_name(_ARBITRARY_DATETIME)
        self.assertNotEqual(parent_file, child_file)

    @patch.object(bugs, "_WriteBugJSONFile")
    def testCustomDirectoriesArePassedThrough(self, mock_write_json_file):
        directory = "/path/to/somewhere/interesting"
        bugs.AppendToExistingBug(1, "foo", directory=directory)
        mock_write_json_file.assert_called_once_with(
            mock.ANY, mock.ANY, directory
        )
        mock_write_json_file.reset_mock()

        bugs.CreateNewBug(1, "title", "body", directory=directory)
        mock_write_json_file.assert_called_once_with(
            mock.ANY, mock.ANY, directory
        )
        mock_write_json_file.reset_mock()

        bugs.SendCronjobLog("cronjob", False, "message", directory=directory)
        mock_write_json_file.assert_called_once_with(
            mock.ANY, mock.ANY, directory
        )

    def testWriteBugJSONFileWritesToGivenDirectory(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            bugs.AppendToExistingBug(1, "body", directory=tmpdir)
            json_files = list(Path(tmpdir).glob("*.json"))
            self.assertEqual(len(json_files), 1, json_files)


if __name__ == "__main__":
    unittest.main()