How to use should_do_markup method in Pytest

Best Python code snippet using pytest

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_console.py

Source: test_console.py Github

copy
1"""Tests for rich module."""
2import io
3import sys
4
5import pytest
6from pytest_mock import MockFixture
7
8from enrich.console import Console, should_do_markup
9
10
11def test_rich_console_ex() -> None:
12    """Validate that ConsoleEx can capture output from print() calls."""
13    console = Console(record=True, redirect=True)
14    console.print("alpha")
15    print("beta")
16    sys.stdout.write("gamma\n")
17    sys.stderr.write("delta\n")
18    # While not supposed to happen we want to be sure that this will not raise
19    # an exception. Some libraries may still sometimes send bytes to the
20    # streams, notable example being click.
21    # sys.stdout.write(b"epsilon\n")  # type: ignore
22    text = console.export_text()
23    assert text == "alpha\nbeta\ngamma\ndelta\n"
24
25
26def test_rich_console_ex_ansi() -> None:
27    """Validate that ANSI sent to sys.stdout does not become garbage in record."""
28    print()
29    console = Console(force_terminal=True, record=True, redirect=True)
30    console.print("[green]this from Console.print()[/green]", style="red")
31
32    text = console.export_text(clear=False)
33    assert "this from Console" in text
34
35    html = console.export_html(clear=False)
36    assert "#008000" in html
37
38
39def test_console_soft_wrap() -> None:
40    """Assures long prints on console are not wrapped when requested."""
41    console = Console(
42        file=io.StringIO(), width=20, record=True, soft_wrap=True, redirect=False
43    )
44    text = 21 * "x"
45    console.print(text, end="")
46    assert console.file.getvalue() == text  # type: ignore
47    result = console.export_text()
48    assert text in result
49
50
51def test_console_print_ansi() -> None:
52    """Validates that Console.print() with ANSI does not make break them."""
53    console = Console(force_terminal=True, record=True, soft_wrap=True, redirect=True)
54    text = "\033[92mfuture is green!\033[0m"
55    console.print(text)
56    text_result = console.export_text(clear=False)
57    assert "future is green!" in text_result
58    html_result = console.export_html()
59    assert "#00ff00" in html_result
60
61
62def test_markup_detection_pycolors0() -> None:
63    """Assure PY_COLORS=0 disables markup."""
64    with pytest.MonkeyPatch.context() as monkeypatch:
65        monkeypatch.setenv("PY_COLORS", "0")
66        assert not should_do_markup()
67
68
69def test_markup_detection_pycolors1() -> None:
70    """Assure PY_COLORS=1 enables markup."""
71    with pytest.MonkeyPatch.context() as monkeypatch:
72        monkeypatch.setenv("PY_COLORS", "1")
73        assert should_do_markup()
74
75
76def test_markup_detection_tty_yes(mocker: MockFixture) -> None:
77    """Assures TERM=xterm enables markup."""
78    mocker.patch("sys.stdout.isatty", return_value=True)
79    mocker.patch("os.environ", {"TERM": "xterm"})
80    assert should_do_markup()
81    mocker.resetall()
82    mocker.stopall()
83
84
85def test_markup_detection_tty_no(mocker: MockFixture) -> None:
86    """Assures that if no tty is reported we disable markup."""
87    mocker.patch("os.environ", {})
88    mocker.patch("sys.stdout.isatty", return_value=False)
89    assert not should_do_markup()
90    mocker.resetall()
91    mocker.stopall()
92
93
94if __name__ == "__main__":
95    test_console_print_ansi()
96
Full Screen

test_terminalwriter.py

Source: test_terminalwriter.py Github

copy
1from collections import namedtuple
2
3import py
4import os, sys
5from py._io import terminalwriter
6import codecs
7import pytest
8
9def test_get_terminal_width():
10    x = py.io.get_terminal_width
11    assert x == terminalwriter.get_terminal_width
12
13def test_getdimensions(monkeypatch):
14    if sys.version_info >= (3, 3):
15        import shutil
16        Size = namedtuple('Size', 'lines columns')
17        monkeypatch.setattr(shutil, 'get_terminal_size', lambda: Size(60, 100))
18        assert terminalwriter._getdimensions() == (60, 100)
19    else:
20        fcntl = py.test.importorskip("fcntl")
21        import struct
22        l = []
23        monkeypatch.setattr(fcntl, 'ioctl', lambda *args: l.append(args))
24        try:
25            terminalwriter._getdimensions()
26        except (TypeError, struct.error):
27            pass
28        assert len(l) == 1
29        assert l[0][0] == 1
30
31def test_terminal_width_COLUMNS(monkeypatch):
32    """ Dummy test for get_terminal_width
33    """
34    fcntl = py.test.importorskip("fcntl")
35    monkeypatch.setattr(fcntl, 'ioctl', lambda *args: int('x'))
36    monkeypatch.setenv('COLUMNS', '42')
37    assert terminalwriter.get_terminal_width() == 42
38    monkeypatch.delenv('COLUMNS', raising=False)
39
40def test_terminalwriter_defaultwidth_80(monkeypatch):
41    monkeypatch.setattr(terminalwriter, '_getdimensions', lambda: 0/0)
42    monkeypatch.delenv('COLUMNS', raising=False)
43    tw = py.io.TerminalWriter()
44    assert tw.fullwidth == 80
45
46def test_terminalwriter_getdimensions_bogus(monkeypatch):
47    monkeypatch.setattr(terminalwriter, '_getdimensions', lambda: (10,10))
48    monkeypatch.delenv('COLUMNS', raising=False)
49    tw = py.io.TerminalWriter()
50    assert tw.fullwidth == 80
51
52def test_terminalwriter_getdimensions_emacs(monkeypatch):
53    # emacs terminal returns (0,0) but set COLUMNS properly
54    monkeypatch.setattr(terminalwriter, '_getdimensions', lambda: (0,0))
55    monkeypatch.setenv('COLUMNS', '42')
56    tw = py.io.TerminalWriter()
57    assert tw.fullwidth == 42
58
59def test_terminalwriter_computes_width(monkeypatch):
60    monkeypatch.setattr(terminalwriter, 'get_terminal_width', lambda: 42)
61    tw = py.io.TerminalWriter()
62    assert tw.fullwidth == 42
63
64def test_terminalwriter_default_instantiation():
65    tw = py.io.TerminalWriter(stringio=True)
66    assert hasattr(tw, 'stringio')
67
68def test_terminalwriter_dumb_term_no_markup(monkeypatch):
69    monkeypatch.setattr(os, 'environ', {'TERM': 'dumb', 'PATH': ''})
70    class MyFile:
71        closed = False
72        def isatty(self):
73            return True
74    monkeypatch.setattr(sys, 'stdout', MyFile())
75    try:
76        assert sys.stdout.isatty()
77        tw = py.io.TerminalWriter()
78        assert not tw.hasmarkup
79    finally:
80        monkeypatch.undo()
81
82def test_terminalwriter_file_unicode(tmpdir):
83    f = codecs.open(str(tmpdir.join("xyz")), "wb", "utf8")
84    tw = py.io.TerminalWriter(file=f)
85    assert tw.encoding == "utf8"
86
87def test_unicode_encoding():
88    msg = py.builtin._totext('b\u00f6y', 'utf8')
89    for encoding in 'utf8', 'latin1':
90        l = []
91        tw = py.io.TerminalWriter(l.append, encoding=encoding)
92        tw.line(msg)
93        assert l[0].strip() == msg.encode(encoding)
94
95@pytest.mark.parametrize("encoding", ["ascii"])
96def test_unicode_on_file_with_ascii_encoding(tmpdir, monkeypatch, encoding):
97    msg = py.builtin._totext('hell\xf6', "latin1")
98    #pytest.raises(UnicodeEncodeError, lambda: bytes(msg))
99    f = codecs.open(str(tmpdir.join("x")), "w", encoding)
100    tw = py.io.TerminalWriter(f)
101    tw.line(msg)
102    f.close()
103    s = tmpdir.join("x").open("rb").read().strip()
104    assert encoding == "ascii"
105    assert s == msg.encode("unicode-escape")
106
107
108win32 = int(sys.platform == "win32")
109class TestTerminalWriter:
110    def pytest_generate_tests(self, metafunc):
111        if "tw" in metafunc.funcargnames:
112            metafunc.addcall(id="path", param="path")
113            metafunc.addcall(id="stringio", param="stringio")
114            metafunc.addcall(id="callable", param="callable")
115    def pytest_funcarg__tw(self, request):
116        if request.param == "path":
117            tmpdir = request.getfuncargvalue("tmpdir")
118            p = tmpdir.join("tmpfile")
119            f = codecs.open(str(p), 'w+', encoding='utf8')
120            tw = py.io.TerminalWriter(f)
121            def getlines():
122                tw._file.flush()
123                return codecs.open(str(p), 'r',
124                    encoding='utf8').readlines()
125        elif request.param == "stringio":
126            tw = py.io.TerminalWriter(stringio=True)
127            def getlines():
128                tw.stringio.seek(0)
129                return tw.stringio.readlines()
130        elif request.param == "callable":
131            writes = []
132            tw = py.io.TerminalWriter(writes.append)
133            def getlines():
134                io = py.io.TextIO()
135                io.write("".join(writes))
136                io.seek(0)
137                return io.readlines()
138        tw.getlines = getlines
139        tw.getvalue = lambda: "".join(getlines())
140        return tw
141
142    def test_line(self, tw):
143        tw.line("hello")
144        l = tw.getlines()
145        assert len(l) == 1
146        assert l[0] == "hello\n"
147
148    def test_line_unicode(self, tw):
149        for encoding in 'utf8', 'latin1':
150            tw._encoding = encoding
151            msg = py.builtin._totext('b\u00f6y', 'utf8')
152            tw.line(msg)
153            l = tw.getlines()
154            assert l[0] == msg + "\n"
155
156    def test_sep_no_title(self, tw):
157        tw.sep("-", fullwidth=60)
158        l = tw.getlines()
159        assert len(l) == 1
160        assert l[0] == "-" * (60-win32) + "\n"
161
162    def test_sep_with_title(self, tw):
163        tw.sep("-", "hello", fullwidth=60)
164        l = tw.getlines()
165        assert len(l) == 1
166        assert l[0] == "-" * 26 + " hello " + "-" * (27-win32) + "\n"
167
168    def test_sep_longer_than_width(self, tw):
169        tw.sep('-', 'a' * 10, fullwidth=5)
170        line, = tw.getlines()
171        # even though the string is wider than the line, still have a separator
172        assert line == '- aaaaaaaaaa -\n'
173
174    @py.test.mark.skipif("sys.platform == 'win32'")
175    def test__escaped(self, tw):
176        text2 = tw._escaped("hello", (31))
177        assert text2.find("hello") != -1
178
179    @py.test.mark.skipif("sys.platform == 'win32'")
180    def test_markup(self, tw):
181        for bold in (True, False):
182            for color in ("red", "green"):
183                text2 = tw.markup("hello", **{color: True, 'bold': bold})
184                assert text2.find("hello") != -1
185        py.test.raises(ValueError, "tw.markup('x', wronkw=3)")
186        py.test.raises(ValueError, "tw.markup('x', wronkw=0)")
187
188    def test_line_write_markup(self, tw):
189        tw.hasmarkup = True
190        tw.line("x", bold=True)
191        tw.write("x\n", red=True)
192        l = tw.getlines()
193        if sys.platform != "win32":
194            assert len(l[0]) >= 2, l
195            assert len(l[1]) >= 2, l
196
197    def test_attr_fullwidth(self, tw):
198        tw.sep("-", "hello", fullwidth=70)
199        tw.fullwidth = 70
200        tw.sep("-", "hello")
201        l = tw.getlines()
202        assert len(l[0]) == len(l[1])
203
204    def test_reline(self, tw):
205        tw.line("hello")
206        tw.hasmarkup = False
207        pytest.raises(ValueError, lambda: tw.reline("x"))
208        tw.hasmarkup = True
209        tw.reline("0 1 2")
210        tw.getlines()
211        l = tw.getvalue().split("\n")
212        assert len(l) == 2
213        tw.reline("0 1 3")
214        l = tw.getvalue().split("\n")
215        assert len(l) == 2
216        assert l[1].endswith("0 1 3\r")
217        tw.line("so")
218        l = tw.getvalue().split("\n")
219        assert len(l) == 3
220        assert l[-1] == ""
221        assert l[1] == ("0 1 2\r0 1 3\rso   ")
222        assert l[0] == "hello"
223
224
225def test_terminal_with_callable_write_and_flush():
226    l = set()
227    class fil:
228        flush = lambda self: l.add("1")
229        write = lambda self, x: l.add("1")
230        __call__ = lambda self, x: l.add("2")
231
232    tw = py.io.TerminalWriter(fil())
233    tw.line("hello")
234    assert l == set(["1"])
235    del fil.flush
236    l.clear()
237    tw = py.io.TerminalWriter(fil())
238    tw.line("hello")
239    assert l == set(["2"])
240
241
242def test_chars_on_current_line():
243    tw = py.io.TerminalWriter(stringio=True)
244
245    written = []
246
247    def write_and_check(s, expected):
248        tw.write(s, bold=True)
249        written.append(s)
250        assert tw.chars_on_current_line == expected
251        assert tw.stringio.getvalue() == ''.join(written)
252
253    write_and_check('foo', 3)
254    write_and_check('bar', 6)
255    write_and_check('\n', 0)
256    write_and_check('\n', 0)
257    write_and_check('\n\n\n', 0)
258    write_and_check('\nfoo', 3)
259    write_and_check('\nfbar\nhello', 5)
260    write_and_check('10', 7)
261
262
263@pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
264def test_attr_hasmarkup():
265    tw = py.io.TerminalWriter(stringio=True)
266    assert not tw.hasmarkup
267    tw.hasmarkup = True
268    tw.line("hello", bold=True)
269    s = tw.stringio.getvalue()
270    assert len(s) > len("hello\n")
271    assert '\x1b[1m' in s
272    assert '\x1b[0m' in s
273
274@pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
275def test_ansi_print():
276    # we have no easy way to construct a file that
277    # represents a terminal
278    f = py.io.TextIO()
279    f.isatty = lambda: True
280    py.io.ansi_print("hello", 0x32, file=f)
281    text2 = f.getvalue()
282    assert text2.find("hello") != -1
283    assert len(text2) >= len("hello\n")
284    assert '\x1b[50m' in text2
285    assert '\x1b[0m' in text2
286
287def test_should_do_markup_PY_COLORS_eq_1(monkeypatch):
288    monkeypatch.setitem(os.environ, 'PY_COLORS', '1')
289    tw = py.io.TerminalWriter(stringio=True)
290    assert tw.hasmarkup
291    tw.line("hello", bold=True)
292    s = tw.stringio.getvalue()
293    assert len(s) > len("hello\n")
294    assert '\x1b[1m' in s
295    assert '\x1b[0m' in s
296
297def test_should_do_markup_PY_COLORS_eq_0(monkeypatch):
298    monkeypatch.setitem(os.environ, 'PY_COLORS', '0')
299    f = py.io.TextIO()
300    f.isatty = lambda: True
301    tw = py.io.TerminalWriter(file=f)
302    assert not tw.hasmarkup
303    tw.line("hello", bold=True)
304    s = f.getvalue()
305    assert s == "hello\n"
306
307def test_should_do_markup(monkeypatch):
308    monkeypatch.delenv("PY_COLORS", raising=False)
309    monkeypatch.delenv("NO_COLOR", raising=False)
310
311    should_do_markup = terminalwriter.should_do_markup
312
313    f = py.io.TextIO()
314    f.isatty = lambda: True
315
316    assert should_do_markup(f) is True
317
318    # NO_COLOR without PY_COLORS.
319    monkeypatch.setenv("NO_COLOR", "0")
320    assert should_do_markup(f) is False
321    monkeypatch.setenv("NO_COLOR", "1")
322    assert should_do_markup(f) is False
323    monkeypatch.setenv("NO_COLOR", "any")
324    assert should_do_markup(f) is False
325
326    # PY_COLORS overrides NO_COLOR ("0" and "1" only).
327    monkeypatch.setenv("PY_COLORS", "1")
328    assert should_do_markup(f) is True
329    monkeypatch.setenv("PY_COLORS", "0")
330    assert should_do_markup(f) is False
331    # Uses NO_COLOR.
332    monkeypatch.setenv("PY_COLORS", "any")
333    assert should_do_markup(f) is False
334    monkeypatch.delenv("NO_COLOR")
335    assert should_do_markup(f) is True
336
337    # Back to defaults.
338    monkeypatch.delenv("PY_COLORS")
339    assert should_do_markup(f) is True
340    f.isatty = lambda: False
341    assert should_do_markup(f) is False
342
Full Screen

test_logger.py

Source: test_logger.py Github

copy
1#  Copyright (c) 2015-2018 Cisco Systems, Inc.
2#
3#  Permission is hereby granted, free of charge, to any person obtaining a copy
4#  of this software and associated documentation files (the "Software"), to
5#  deal in the Software without restriction, including without limitation the
6#  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7#  sell copies of the Software, and to permit persons to whom the Software is
8#  furnished to do so, subject to the following conditions:
9#
10#  The above copyright notice and this permission notice shall be included in
11#  all copies or substantial portions of the Software.
12#
13#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19#  DEALINGS IN THE SOFTWARE.
20
21from __future__ import print_function
22
23import sys
24
25import colorama
26
27from molecule import logger
28
29
30def test_info(capsys):
31    log = logger.get_logger(__name__)
32    log.info('foo')
33    stdout, _ = capsys.readouterr()
34
35    print('--> {}{}{}'.format(colorama.Fore.CYAN, 'foo'.rstrip(),
36                              colorama.Style.RESET_ALL))
37    x, _ = capsys.readouterr()
38
39    assert x == stdout
40
41
42def test_out(capsys):
43    log = logger.get_logger(__name__)
44    log.out('foo')
45
46    stdout, _ = capsys.readouterr()
47
48    assert '    foo\n' == stdout
49
50
51def test_warn(capsys):
52    log = logger.get_logger(__name__)
53    log.warn('foo')
54
55    stdout, _ = capsys.readouterr()
56
57    print('{}{}{}'.format(colorama.Fore.YELLOW, 'foo'.rstrip(),
58                          colorama.Style.RESET_ALL))
59    x, _ = capsys.readouterr()
60
61    assert x == stdout
62
63
64def test_error(capsys):
65    log = logger.get_logger(__name__)
66    log.error('foo')
67
68    _, stderr = capsys.readouterr()
69
70    print(
71        '{}{}{}'.format(colorama.Fore.RED, 'foo'.rstrip(),
72                        colorama.Style.RESET_ALL),
73        file=sys.stderr)
74    _, x = capsys.readouterr()
75
76    assert x in stderr
77
78
79def test_critical(capsys):
80    log = logger.get_logger(__name__)
81    log.critical('foo')
82
83    _, stderr = capsys.readouterr()
84
85    print(
86        '{}ERROR: {}{}'.format(colorama.Fore.RED, 'foo'.rstrip(),
87                               colorama.Style.RESET_ALL),
88        file=sys.stderr)
89    _, x = capsys.readouterr()
90
91    assert x in stderr
92
93
94def test_success(capsys):
95    log = logger.get_logger(__name__)
96    log.success('foo')
97
98    stdout, _ = capsys.readouterr()
99
100    print('{}{}{}'.format(colorama.Fore.GREEN, 'foo'.rstrip(),
101                          colorama.Style.RESET_ALL))
102    x, _ = capsys.readouterr()
103
104    assert x == stdout
105
106
107def test_red_text():
108    x = '{}{}{}'.format(colorama.Fore.RED, 'foo', colorama.Style.RESET_ALL)
109
110    assert x == logger.red_text('foo')
111
112
113def test_yellow_text():
114    x = '{}{}{}'.format(colorama.Fore.YELLOW, 'foo', colorama.Style.RESET_ALL)
115
116    assert x == logger.yellow_text('foo')
117
118
119def test_green_text():
120    x = '{}{}{}'.format(colorama.Fore.GREEN, 'foo', colorama.Style.RESET_ALL)
121
122    assert x == logger.green_text('foo')
123
124
125def test_cyan_text():
126    x = '{}{}{}'.format(colorama.Fore.CYAN, 'foo', colorama.Style.RESET_ALL)
127
128    assert x == logger.cyan_text('foo')
129
130
131def test_markup_detection_pycolors0(monkeypatch):
132    monkeypatch.setenv('PY_COLORS', '0')
133    assert not logger.should_do_markup()
134
135
136def test_markup_detection_pycolors1(monkeypatch):
137    monkeypatch.setenv('PY_COLORS', '1')
138    assert logger.should_do_markup()
139
140
141def test_markup_detection_tty_yes(mocker):
142    mocker.patch('sys.stdout.isatty', return_value=True)
143    mocker.patch('os.environ', {'TERM': 'xterm'})
144    assert logger.should_do_markup()
145    mocker.resetall()
146    mocker.stopall()
147
148
149def test_markup_detection_tty_no(mocker):
150    mocker.patch('os.environ', {})
151    mocker.patch('sys.stdout.isatty', return_value=False)
152    assert not logger.should_do_markup()
153    mocker.resetall()
154    mocker.stopall()
155
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Pytest on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)