summaryrefslogtreecommitdiff
path: root/testrepository/tests/ui/test_cli.py
blob: 7b7b24579ca3252b09a60dfef96065f8a20b7a96 (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
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
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2009, 2010 Testrepository Contributors
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two licences.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.

"""Tests for UI support logic and the UI contract."""

import doctest
from cStringIO import StringIO
import sys

from testtools import TestCase
from testtools.matchers import DocTestMatches

from testrepository import arguments
from testrepository import commands
from testrepository.ui import cli
from testrepository.tests import ResourcedTestCase


def get_test_ui_and_cmd():
    stdout = StringIO()
    stdin = StringIO()
    stderr = StringIO()
    ui = cli.UI([], stdin, stdout, stderr)
    cmd = commands.Command(ui)
    ui.set_command(cmd)
    return ui, cmd


class TestCLIUI(ResourcedTestCase):

    def test_construct(self):
        stdout = StringIO()
        stdin = StringIO()
        stderr = StringIO()
        cli.UI([], stdin, stdout, stderr)

    def test_stream_comes_from_stdin(self):
        stdout = StringIO()
        stdin = StringIO('foo\n')
        stderr = StringIO()
        ui = cli.UI([], stdin, stdout, stderr)
        cmd = commands.Command(ui)
        cmd.input_streams = ['subunit']
        ui.set_command(cmd)
        results = []
        for stream in ui.iter_streams('subunit'):
            results.append(stream.read())
        self.assertEqual(['foo\n'], results)

    def test_dash_d_sets_here_option(self):
        stdout = StringIO()
        stdin = StringIO('foo\n')
        stderr = StringIO()
        ui = cli.UI(['-d', '/nowhere/'], stdin, stdout, stderr)
        cmd = commands.Command(ui)
        ui.set_command(cmd)
        self.assertEqual('/nowhere/', ui.here)

    def test_outputs_error_string(self):
        try:
            raise Exception('fooo')
        except Exception:
            err_tuple = sys.exc_info()
        expected = str(err_tuple[1]) + '\n'
        stdout = StringIO()
        stdin = StringIO()
        stderr = StringIO()
        ui = cli.UI([], stdin, stdout, stderr)
        ui.output_error(err_tuple)
        self.assertThat(stderr.getvalue(), DocTestMatches(expected))

    def test_outputs_rest_to_stdout(self):
        ui, cmd = get_test_ui_and_cmd()
        ui.output_rest('topic\n=====\n')
        self.assertEqual('topic\n=====\n', ui._stdout.getvalue())

    def test_outputs_results_to_stdout(self):
        ui, cmd = get_test_ui_and_cmd()
        class Case(ResourcedTestCase):
            def method(self):
                self.fail('quux')
        result = ui.make_result(lambda: None)
        Case('method').run(result)
        self.assertThat(ui._stdout.getvalue(),DocTestMatches(
            """======================================================================
FAIL: testrepository.tests.ui.test_cli.Case.method
----------------------------------------------------------------------
...Traceback (most recent call last):...
  File "...test_cli.py", line ..., in method
    self.fail(\'quux\')
AssertionError: quux...
""", doctest.ELLIPSIS))

    def test_outputs_stream_to_stdout(self):
        ui, cmd = get_test_ui_and_cmd()
        stream = StringIO("Foo \n bar")
        ui.output_stream(stream)
        self.assertEqual("Foo \n bar", ui._stdout.getvalue())

    def test_outputs_tables_to_stdout(self):
        ui, cmd = get_test_ui_and_cmd()
        ui.output_table([('foo', 1), ('b', 'quux')])
        self.assertEqual('foo  1\n---  ----\nb    quux\n',
            ui._stdout.getvalue())

    def test_outputs_tests_to_stdout(self):
        ui, cmd = get_test_ui_and_cmd()
        ui.output_tests([self, self.__class__('test_construct')])
        self.assertThat(
            ui._stdout.getvalue(),
            DocTestMatches(
                '...TestCLIUI.test_outputs_tests_to_stdout\n'
                '...TestCLIUI.test_construct\n', doctest.ELLIPSIS))

    def test_outputs_values_to_stdout(self):
        ui, cmd = get_test_ui_and_cmd()
        ui.output_values([('foo', 1), ('bar', 'quux')])
        self.assertEqual('foo=1, bar=quux\n', ui._stdout.getvalue())

    def test_outputs_summary_to_stdout(self):
        ui, cmd = get_test_ui_and_cmd()
        success, values = True, [('time', 1, None), ('tests', 2, None)]
        expected_summary = ui._format_summary(success, values)
        ui.output_summary(success, values)
        self.assertEqual(expected_summary, ui._stdout.getvalue())

    def test_parse_error_goes_to_stderr(self):
        stdout = StringIO()
        stdin = StringIO()
        stderr = StringIO()
        ui = cli.UI(['one'], stdin, stdout, stderr)
        cmd = commands.Command(ui)
        cmd.args = [arguments.command.CommandArgument('foo')]
        ui.set_command(cmd)
        self.assertEqual("Could not find command 'one'.\n", stderr.getvalue())

    def test_parse_excess_goes_to_stderr(self):
        stdout = StringIO()
        stdin = StringIO()
        stderr = StringIO()
        ui = cli.UI(['one'], stdin, stdout, stderr)
        cmd = commands.Command(ui)
        ui.set_command(cmd)
        self.assertEqual("Unexpected arguments: ['one']\n", stderr.getvalue())

    def test_parse_after_double_dash_are_arguments(self):
        stdout = StringIO()
        stdin = StringIO()
        stderr = StringIO()
        ui = cli.UI(['one', '--', '--two', 'three'], stdin, stdout, stderr)
        cmd = commands.Command(ui)
        cmd.args = [arguments.string.StringArgument('args', max=None)]
        ui.set_command(cmd)
        self.assertEqual({'args':['one', '--two', 'three']}, ui.arguments)


class TestCLISummary(TestCase):

    def get_summary(self, successful, values):
        """Get the summary that would be output for successful & values."""
        ui, cmd = get_test_ui_and_cmd()
        return ui._format_summary(successful, values)

    def test_success_only(self):
        x = self.get_summary(True, [])
        self.assertEqual(x, 'PASSED')

    def test_failure_only(self):
        x = self.get_summary(False, [])
        self.assertEqual(x, 'FAILED')

    def test_time(self):
        x = self.get_summary(True, [('time', 3.4, None)])
        self.assertEqual(x, 'Ran tests in 3.400s\nPASSED')

    def test_time_with_delta(self):
        x = self.get_summary(True, [('time', 3.4, 0.1)])
        self.assertEqual(x, 'Ran tests in 3.400s (+0.100s)\nPASSED')

    def test_tests_run(self):
        x = self.get_summary(True, [('tests', 34, None)])
        self.assertEqual(x, 'Ran 34 tests\nPASSED')

    def test_tests_run_with_delta(self):
        x = self.get_summary(True, [('tests', 34, -5)])
        self.assertEqual(x, 'Ran 34 (-5) tests\nPASSED')

    def test_tests_and_time(self):
        x = self.get_summary(True, [('tests', 34, -5), ('time', 3.4, 0.1)])
        self.assertEqual(x, 'Ran 34 (-5) tests in 3.400s (+0.100s)\nPASSED')


class TestCLITestResult(TestCase):

    def make_exc_info(self):
        # Make an exc_info tuple for use in testing.
        try:
            1/0
        except ZeroDivisionError:
            return sys.exc_info()

    def make_result(self, stream=None):
        if stream is None:
            stream = StringIO()
        ui = cli.UI([], None, stream, None)
        return ui.make_result(lambda: None)

    def test_initial_stream(self):
        # CLITestResult.__init__ does not do anything to the stream it is
        # given.
        stream = StringIO()
        cli.CLITestResult(cli.UI(None, None, None, None), stream, lambda: None)
        self.assertEqual('', stream.getvalue())

    def test_format_error(self):
        # CLITestResult formats errors by giving them a big fat line, a title
        # made up of their 'label' and the name of the test, another different
        # big fat line, and then the actual error itself.
        result = self.make_result()
        error = result._format_error('label', self, 'error text')
        expected = '%s%s: %s\n%s%s' % (
            result.sep1, 'label', self.id(), result.sep2, 'error text')
        self.assertThat(error, DocTestMatches(expected))

    def test_addError_outputs_error(self):
        # CLITestResult.addError outputs the given error immediately to the
        # stream.
        stream = StringIO()
        result = self.make_result(stream)
        error = self.make_exc_info()
        error_text = result._err_details_to_string(self, error)
        result.addError(self, error)
        self.assertThat(
            stream.getvalue(),
            DocTestMatches(result._format_error('ERROR', self, error_text)))

    def test_addFailure_outputs_failure(self):
        # CLITestResult.addError outputs the given error immediately to the
        # stream.
        stream = StringIO()
        result = self.make_result(stream)
        error = self.make_exc_info()
        error_text = result._err_details_to_string(self, error)
        result.addFailure(self, error)
        self.assertThat(
            stream.getvalue(),
            DocTestMatches(result._format_error('FAIL', self, error_text)))