File: test_testr.py

package info (click to toggle)
rally 5.0.0-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,368 kB
  • sloc: python: 42,541; javascript: 487; sh: 198; makefile: 192; xml: 43
file content (421 lines) | stat: -rw-r--r-- 17,452 bytes parent folder | download | duplicates (2)
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import os
import subprocess
from unittest import mock

from rally import exceptions
from rally.plugins.verification import testr
from tests.unit import test


PATH = "rally.plugins.verification.testr"


class TestrContextTestCase(test.TestCase):

    def setUp(self):
        super(TestrContextTestCase, self).setUp()
        self.verifier = mock.Mock()
        self.prepare_run_args = self.verifier.manager.prepare_run_args
        self.prepare_run_args.side_effect = lambda x: x

    def assertEqualCmd(self, expected, actual, msg="", stestr=False):
        cmd = ["stestr" if stestr else "testr", "run", "--subunit"]
        cmd.extend(expected)
        self.assertEqual(cmd, actual, msg=msg)

    def test_setup_with_concurrency(self):
        # default behaviour
        cfg = {"verifier": self.verifier}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--parallel"], cfg["testr_cmd"])
        cfg = {"verifier": self.verifier, "run_args": {"concurrency": 0}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--parallel"], cfg["testr_cmd"])

        # serial mode
        cfg = {"verifier": self.verifier,
               "run_args": {"concurrency": 1}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--concurrency", "1"], cfg["testr_cmd"])

        # parallel mode
        cfg = {"verifier": self.verifier,
               "run_args": {"concurrency": 2}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--parallel", "--concurrency", "2"],
                            cfg["testr_cmd"])

    def test_setup_with_concurrency_stestr(self):
        self.verifier.manager._use_testr = False
        # default behaviour
        cfg = {"verifier": self.verifier}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd([], cfg["testr_cmd"], stestr=True)
        cfg = {"verifier": self.verifier, "run_args": {"concurrency": 0}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd([], cfg["testr_cmd"], stestr=True)

        # serial mode
        cfg = {"verifier": self.verifier,
               "run_args": {"concurrency": 1}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--serial"], cfg["testr_cmd"], stestr=True)

        # parallel mode
        cfg = {"verifier": self.verifier,
               "run_args": {"concurrency": 2}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--concurrency", "2"], cfg["testr_cmd"],
                            stestr=True)

    @mock.patch("%s.common_utils.generate_random_path" % PATH)
    def test_setup_with_skip_and_load_lists(self, mock_generate_random_path):
        # with load_list, but without skip_list
        load_list = ["tests.foo", "tests.bar"]
        cfg = {"verifier": self.verifier,
               "run_args": {"load_list": load_list}}
        ctx = testr.TestrContext(cfg)
        mock_open = mock.mock_open()
        with mock.patch("%s.open" % PATH, mock_open):
            ctx.setup()
        mock_open.assert_called_once_with(
            mock_generate_random_path.return_value, "w")
        handle = mock_open.return_value
        handle.write.assert_called_once_with("\n".join(load_list))
        self.assertEqualCmd(["--parallel", "--load-list",
                             mock_generate_random_path.return_value],
                            cfg["testr_cmd"])
        self.assertFalse(self.verifier.manager.list_tests.called)

        # with load_list and skip_list
        load_list = ["tests.foo", "tests.bar"]
        skip_list = {"tests.foo": "skip reason"}
        cfg = {"verifier": self.verifier,
               "run_args": {"load_list": load_list,
                            "skip_list": skip_list}}
        ctx = testr.TestrContext(cfg)
        mock_open = mock.mock_open()
        with mock.patch("%s.open" % PATH, mock_open):
            ctx.setup()
        mock_open.assert_called_once_with(
            mock_generate_random_path.return_value, "w")
        handle = mock_open.return_value
        handle.write.assert_called_once_with(load_list[1])
        self.assertEqualCmd(["--parallel", "--load-list",
                             mock_generate_random_path.return_value],
                            cfg["testr_cmd"])
        self.assertFalse(self.verifier.manager.list_tests.called)

        # with skip_list, but without load_list
        load_list = ["tests.foo", "tests.bar"]
        self.verifier.manager.list_tests.return_value = load_list
        skip_list = {"tests.foo": "skip reason"}
        cfg = {"verifier": self.verifier,
               "run_args": {"skip_list": skip_list}}
        ctx = testr.TestrContext(cfg)
        mock_open = mock.mock_open()
        with mock.patch("%s.open" % PATH, mock_open):
            ctx.setup()
        mock_open.assert_called_once_with(
            mock_generate_random_path.return_value, "w")
        handle = mock_open.return_value
        handle.write.assert_called_once_with(load_list[1])
        self.assertEqualCmd(["--parallel", "--load-list",
                             mock_generate_random_path.return_value],
                            cfg["testr_cmd"])
        self.verifier.manager.list_tests.assert_called_once_with()

    @mock.patch("%s.common_utils.generate_random_path" % PATH)
    def test_skip_list_with_regex_positive_match(self,
                                                 mock_generate_random_path):
        # using a regex in skip_list
        load_list = ["tests.foo.bar", "tests.bar"]
        self.verifier.manager.list_tests.return_value = load_list
        skip_list = {"^tests.foo": "skip reason"}
        cfg = {"verifier": self.verifier,
               "run_args": {"skip_list": skip_list}}
        ctx = testr.TestrContext(cfg)
        mock_open = mock.mock_open()
        with mock.patch("%s.open" % PATH, mock_open):
            ctx.setup()
        mock_open.assert_called_once_with(
            mock_generate_random_path.return_value, "w")
        handle = mock_open.return_value
        handle.write.assert_called_once_with(load_list[1])
        self.assertEqualCmd(["--parallel", "--load-list",
                             mock_generate_random_path.return_value],
                            cfg["testr_cmd"])
        self.verifier.manager.list_tests.assert_called_once_with()

    @mock.patch("%s.common_utils.generate_random_path" % PATH)
    def test_skip_list_with_invalid_regex(self,
                                          mock_generate_random_path):
        load_list = [
            "tests.foo[e3976dea-bed9-4b14-abaf-59372de9303]",
            "tests.bar"
        ]
        self.verifier.manager.list_tests.return_value = load_list
        skip_list = {
            "tests.foo[e3976dea-bed9-4b14-abaf-59372de9303]": "skip reason"
        }
        cfg = {"verifier": self.verifier,
               "run_args": {"skip_list": skip_list}}
        ctx = testr.TestrContext(cfg)
        mock_open = mock.mock_open()
        with mock.patch("%s.open" % PATH, mock_open):
            ctx.setup()
        mock_open.assert_called_once_with(
            mock_generate_random_path.return_value, "w")
        handle = mock_open.return_value
        handle.write.assert_called_once_with(load_list[1])
        self.assertEqualCmd(["--parallel", "--load-list",
                             mock_generate_random_path.return_value],
                            cfg["testr_cmd"])
        self.verifier.manager.list_tests.assert_called_once_with()

    def test_setup_with_failing(self):
        cfg = {"verifier": self.verifier, "run_args": {"failed": True}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--parallel", "--failing"], cfg["testr_cmd"])

    def test_setup_with_pattern(self):
        cfg = {"verifier": self.verifier, "run_args": {"pattern": "foo"}}
        ctx = testr.TestrContext(cfg)
        ctx.setup()
        self.assertEqualCmd(["--parallel", "foo"], cfg["testr_cmd"])

    @mock.patch("%s.os.remove" % PATH)
    @mock.patch("%s.os.path.exists" % PATH)
    def test_cleanup(self, mock_exists, mock_remove):
        files = {"/path/foo_1": True,
                 "/path/bar_1": False,
                 "/path/foo_2": False,
                 "/path/bar_2": True}

        def fake_exists(path):
            return files.get(path, False)

        mock_exists.side_effect = fake_exists

        ctx = testr.TestrContext({"verifier": self.verifier})
        ctx._tmp_files = files.keys()

        ctx.cleanup()

        self.assertEqual([mock.call(f) for f in files.keys()],
                         mock_exists.call_args_list)
        self.assertEqual([mock.call(f) for f in files.keys() if files[f]],
                         mock_remove.call_args_list)


class TestrLauncherTestCase(test.TestCase):
    def test_run_environ_property(self):
        env = mock.Mock()

        class FakeLauncher(testr.TestrLauncher):
            @property
            def environ(self):
                return env

        self.assertEqual(env, FakeLauncher(mock.Mock()).run_environ)

    @mock.patch("%s.utils.check_output" % PATH)
    def test_list_tests_via_stestr(self, mock_check_output):
        mock_check_output.return_value = (
            "logging message\n"  # should be ignored
            "one more useless data\n"  # should be ignored
            "tests.FooTestCase.test_something\n"  # valid
            "tests.FooTestCase.test_another[\n"  # invalid
            "tests.BarTestCase.test_another[id=123]\n"  # valid
            "tests.FooTestCase.test_another[id=a2-213,smoke]\n"  # valid
        )
        verifier = mock.Mock()

        launcher = testr.TestrLauncher(verifier)
        launcher._use_testr = False

        self.assertEqual(["tests.FooTestCase.test_something",
                          "tests.BarTestCase.test_another[id=123]",
                          "tests.FooTestCase.test_another[id=a2-213,smoke]"],
                         launcher.list_tests())

        mock_check_output.assert_called_once_with(
            ["stestr", "list", ""],
            cwd=launcher.repo_dir, env=launcher.environ, debug_output=False)

    @mock.patch("%s.utils.check_output" % PATH)
    def test_list_tests_via_testr(self, mock_check_output):
        mock_check_output.return_value = (
            "logging message\n"  # should be ignored
            "one more useless data\n"  # should be ignored
            "tests.FooTestCase.test_something\n"  # valid
            "tests.FooTestCase.test_another[\n"  # invalid
            "tests.BarTestCase.test_another[id=123]\n"  # valid
            "tests.FooTestCase.test_another[id=a2-213,smoke]\n"  # valid
        )
        verifier = mock.Mock()

        launcher = testr.TestrLauncher(verifier)
        launcher._use_testr = True

        self.assertEqual(["tests.FooTestCase.test_something",
                          "tests.BarTestCase.test_another[id=123]",
                          "tests.FooTestCase.test_another[id=a2-213,smoke]"],
                         launcher.list_tests())

        mock_check_output.assert_called_once_with(
            ["testr", "list-tests", ""],
            cwd=launcher.repo_dir, env=launcher.environ, debug_output=False)

    @mock.patch("%s.shutil.rmtree" % PATH)
    @mock.patch("%s.utils.check_output" % PATH)
    @mock.patch("%s.os.path.exists" % PATH)
    @mock.patch("%s.os.path.isdir" % PATH)
    def test__init_testr(self, mock_isdir, mock_exists, mock_check_output,
                         mock_rmtree):
        launcher = testr.TestrLauncher(mock.Mock())
        mock_exists.assert_called_once_with(
            os.path.join(launcher.repo_dir, ".testr.conf"))
        mock_exists.reset_mock()

        # case #1: testr already initialized
        mock_isdir.return_value = True

        launcher._init_testr()

        self.assertFalse(mock_check_output.called)
        self.assertFalse(mock_exists.called)
        self.assertFalse(mock_rmtree.called)

        # case #2: initializing testr without errors
        mock_isdir.return_value = False

        launcher._init_testr()

        mock_check_output.assert_called_once_with(
            ["testr", "init"], cwd=launcher.repo_dir, env=launcher.environ)
        self.assertFalse(mock_exists.called)
        self.assertFalse(mock_rmtree.called)
        mock_check_output.reset_mock()

        # case #3: initializing stestr without errors
        launcher._use_testr = False

        launcher._init_testr()

        mock_check_output.assert_called_once_with(
            ["stestr", "init"], cwd=launcher.repo_dir, env=launcher.environ)
        self.assertFalse(mock_exists.called)
        self.assertFalse(mock_rmtree.called)
        mock_check_output.reset_mock()

        # case #4: initializing testr with error
        mock_check_output.side_effect = OSError
        test_repository_dir = os.path.join(launcher.base_dir,
                                           ".testrepository")

        self.assertRaises(exceptions.RallyException, launcher._init_testr)

        mock_check_output.assert_called_once_with(
            ["stestr", "init"], cwd=launcher.repo_dir, env=launcher.environ)
        mock_exists.assert_called_once_with(test_repository_dir)
        mock_rmtree.assert_called_once_with(test_repository_dir)

    @mock.patch("%s.subunit_v2.parse" % PATH)
    @mock.patch("%s.subprocess.Popen" % PATH)
    def test_run(self, mock_popen, mock_parse):
        launcher = testr.TestrLauncher(mock.Mock())
        ctx = {"testr_cmd": ["ls", "-la"],
               "xfail_list": None, "skip_list": None}

        self.assertEqual(mock_parse.return_value, launcher.run(ctx))

        mock_popen.assert_called_once_with(ctx["testr_cmd"],
                                           env=launcher.run_environ,
                                           cwd=launcher.repo_dir,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.STDOUT)
        mock_popen.return_value.wait.assert_called_once_with()
        mock_parse.assert_called_once_with(
            mock_popen.return_value.stdout, live=True,
            expected_failures=None,
            skipped_tests=None,
            logger_name=launcher.verifier.name)

    @mock.patch("%s.subunit_v2.parse" % PATH)
    @mock.patch("%s.subprocess.Popen" % PATH)
    def test_run_skip(self, mock_popen, mock_parse):
        launcher = testr.TestrLauncher(mock.Mock())
        skip_list = {"test1": "reason1"}
        ctx = {"testr_cmd": ["ls", "-la"],
               "xfail_list": None, "skip_list": skip_list}

        self.assertEqual(mock_parse.return_value, launcher.run(ctx))

        mock_popen.assert_called_once_with(ctx["testr_cmd"],
                                           env=launcher.run_environ,
                                           cwd=launcher.repo_dir,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.STDOUT)
        mock_popen.return_value.wait.assert_called_once_with()
        mock_parse.assert_called_once_with(
            mock_popen.return_value.stdout, live=True,
            expected_failures=None,
            skipped_tests=ctx["skip_list"],
            logger_name=launcher.verifier.name)

    @mock.patch("%s.subunit_v2.parse" % PATH)
    @mock.patch("%s.subprocess.Popen" % PATH)
    def test_run_exclude(self, mock_popen, mock_parse):
        launcher = testr.TestrLauncher(mock.Mock())
        xfail_list = {"test1": "reason1"}
        ctx = {"testr_cmd": ["ls", "-la"],
               "xfail_list": xfail_list, "skip_list": None}
        launcher = testr.TestrLauncher(mock.Mock())

        result = launcher.run(ctx)
        self.assertEqual(mock_parse.return_value, result)

        mock_popen.assert_called_once_with(ctx["testr_cmd"],
                                           env=launcher.run_environ,
                                           cwd=launcher.repo_dir,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.STDOUT)
        mock_popen.return_value.wait.assert_called_once_with()
        mock_parse.assert_called_once_with(
            mock_popen.return_value.stdout, live=True,
            expected_failures=xfail_list,
            skipped_tests=None,
            logger_name=launcher.verifier.name)

    @mock.patch("%s.manager.VerifierManager.install" % PATH)
    def test_install(self, mock_verifier_manager_install):
        launcher = testr.TestrLauncher(mock.Mock())
        launcher._init_testr = mock.Mock()

        launcher.install()

        mock_verifier_manager_install.assert_called_once_with()
        launcher._init_testr.assert_called_once_with()