Best Python code snippet using avocado_python
test_diagnostics.py
Source:test_diagnostics.py  
1import unittest2from collections import OrderedDict3from unittest import mock4from LSP.plugin.core.diagnostics import (DiagnosticsStorage, DiagnosticsWalker, DiagnosticsCursor, CURSOR_FORWARD,5                                         CURSOR_BACKWARD)6from LSP.plugin.core.protocol import Diagnostic, Point, Range, DiagnosticSeverity7from test_protocol import LSP_MINIMAL_DIAGNOSTIC8import sublime9TYPE_CHECKING = False10if TYPE_CHECKING:11    from typing import List, Dict12    assert List and Dict13test_file_path = "test.py" if sublime.platform() == "windows" else "/test.py"14test_file_uri = "file:///test.py"15second_file_path = "/test2.py"16second_file_uri = "file:///test2.py"17test_server_name = "test_server"18minimal_diagnostic = Diagnostic.from_lsp(LSP_MINIMAL_DIAGNOSTIC)19def at_row(row: int) -> Diagnostic:20    return Diagnostic('message', Range(Point(row, 0), Point(row, 1)), DiagnosticSeverity.Error, None, dict(), [])21def diagnostics(test_file_diags: 'List[Diagnostic]',22                second_file_diags: 'List[Diagnostic]' = []) -> 'Dict[str, Dict[str, List[Diagnostic]]]':23    diags = OrderedDict()  # type: Dict[str, Dict[str, List[Diagnostic]]]24    if test_file_diags:25        source_diags = {}26        source_diags[test_server_name] = test_file_diags27        diags[test_file_path] = source_diags28    if second_file_diags:29        source_diags = {}30        source_diags[test_server_name] = second_file_diags31        diags[second_file_path] = source_diags32    return diags33def make_update(diagnostics: 'List[dict]') -> dict:34    return {'uri': 'file:///test.py', 'diagnostics': diagnostics}35class DiagnosticsStorageTest(unittest.TestCase):36    def test_empty_diagnostics(self):37        wd = DiagnosticsStorage(None)38        self.assertEqual(wd.get_by_file(__file__), {})39        self.assertEqual(wd.get(), {})40    def test_receive_diagnostics(self):41        ui = mock.Mock()42        wd = DiagnosticsStorage(ui)43        wd.receive("test_server", make_update([LSP_MINIMAL_DIAGNOSTIC]))44        view_diags = wd.get_by_file(test_file_path)45        self.assertEqual(len(view_diags["test_server"]), 1)46        self.assertEqual(view_diags["test_server"][0].message, LSP_MINIMAL_DIAGNOSTIC['message'])47        self.assertIn(test_file_path, wd.get())48        ui.update.assert_called_with(test_file_path, "test_server",49                                     {test_file_path: {50                                         'test_server': [minimal_diagnostic]51                                     }})52        wd.receive("test_server", make_update([]))53        view_diags = wd.get_by_file(test_file_path)54        self.assertEqual(len(view_diags), 0)55        self.assertEqual(wd.get(), {})56        ui.update.assert_called_with(test_file_path, "test_server", {})57    def test_remove_diagnostics(self):58        ui = mock.Mock()59        wd = DiagnosticsStorage(ui)60        wd.receive("test_server", make_update([LSP_MINIMAL_DIAGNOSTIC]))61        view_diags = wd.get_by_file(test_file_path)62        self.assertEqual(len(view_diags["test_server"]), 1)63        wd.remove(test_file_path, "test_server")64        view_diags = wd.get_by_file(test_file_path)65        self.assertEqual(len(view_diags), 0)66        self.assertEqual(wd.get(), {})67        ui.update.assert_called_with(test_file_path, "test_server", {})68    def test_clear_diagnostics(self):69        ui = mock.Mock()70        wd = DiagnosticsStorage(ui)71        wd.receive("test_server", make_update([LSP_MINIMAL_DIAGNOSTIC]))72        wd.clear()73        view_diags = wd.get_by_file(test_file_path)74        self.assertEqual(len(view_diags), 0)75        self.assertEqual(wd.get(), {})76        ui.update.assert_called_with(test_file_path, "test_server", {})77    def test_select(self):78        ui = mock.Mock()79        wd = DiagnosticsStorage(ui)80        wd.select_next()81        ui.select.assert_called_with(1)82        wd.select_previous()83        ui.select.assert_called_with(-1)84        wd.select_none()85        assert ui.deselect.call_count > 086class DiagnosticsWalkerTests(unittest.TestCase):87    def test_empty(self):88        walk = mock.Mock()89        walker = DiagnosticsWalker([walk])90        walker.walk({})91        assert walk.begin.call_count == 192        assert walk.begin_file.call_count == 093        assert walk.diagnostic.call_count == 094        assert walk.end.call_count == 195    def test_one_diagnosic(self):96        walk = mock.Mock()97        walker = DiagnosticsWalker([walk])98        diags = {}  # type: Dict[str, Dict[str, List[Diagnostic]]]99        diags[test_file_path] = {}100        diags[test_file_path]["test_server"] = [minimal_diagnostic]101        walker.walk(diags)102        assert walk.begin.call_count == 1103        walk.begin_file.assert_called_with(test_file_path)104        walk.diagnostic.assert_called_with(minimal_diagnostic)105        assert walk.end.call_count == 1106row1 = at_row(1)107row5 = at_row(5)108row3 = at_row(3)109info = at_row(4)110info.severity = DiagnosticSeverity.Information111test_diagnostics = diagnostics([row1, info, row5], [row3])112class DiagnosticsCursorTest(unittest.TestCase):113    def test_empty(self) -> None:114        cursor = DiagnosticsCursor()115        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD, test_file_path, Point(0, 0))])116        walker.walk({})117        self.assertIsNone(cursor.value)118    def test_from_no_position(self) -> None:119        cursor = DiagnosticsCursor()120        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD)])121        walker.walk(test_diagnostics)122        self.assertEqual((test_file_path, row1), cursor.value)123    def test_from_no_position_backwards(self) -> None:124        cursor = DiagnosticsCursor()125        walker = DiagnosticsWalker([cursor.from_position(CURSOR_BACKWARD)])126        walker.walk(test_diagnostics)127        self.assertEqual((second_file_path, row3), cursor.value)128    def test_from_file_position(self) -> None:129        cursor = DiagnosticsCursor()130        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD, test_file_path, Point(0, 0))])131        walker.walk(test_diagnostics)132        self.assertEqual((test_file_path, row1), cursor.value)133    def test_from_file_position_backward(self) -> None:134        cursor = DiagnosticsCursor()135        walker = DiagnosticsWalker([cursor.from_position(CURSOR_BACKWARD, test_file_path, Point(10, 0))])136        walker.walk(test_diagnostics)137        self.assertEqual((test_file_path, row5), cursor.value)138    def test_from_other_file_position_wrap(self) -> None:139        cursor = DiagnosticsCursor()140        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD, second_file_path, Point(5, 0))])141        walker.walk(test_diagnostics)142        self.assertEqual((test_file_path, row1), cursor.value)143    def test_from_file_position_backward_wrap(self) -> None:144        cursor = DiagnosticsCursor()145        walker = DiagnosticsWalker([cursor.from_position(CURSOR_BACKWARD, test_file_path, Point(0, 0))])146        walker.walk(test_diagnostics)147        self.assertEqual((second_file_path, row3), cursor.value)148    def test_from_other_file_position_backwards(self) -> None:149        cursor = DiagnosticsCursor()150        walker = DiagnosticsWalker([cursor.from_position(CURSOR_BACKWARD, second_file_path, Point(1, 0))])151        walker.walk(test_diagnostics)152        self.assertEqual((test_file_path, row5), cursor.value)153    def test_updated_diagnostic_remains(self) -> None:154        cursor = DiagnosticsCursor()155        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD)])156        walker.walk(test_diagnostics)157        self.assertEqual((test_file_path, row1), cursor.value)158        walker = DiagnosticsWalker([cursor.update()])159        walker.walk(test_diagnostics)160        self.assertEqual((test_file_path, row1), cursor.value)161    def test_updated_diagnostic_gone(self) -> None:162        cursor = DiagnosticsCursor()163        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD)])164        walker.walk(test_diagnostics)165        self.assertEqual((test_file_path, row1), cursor.value)166        walker = DiagnosticsWalker([cursor.update()])167        walker.walk({})168        self.assertEqual(None, cursor.value)169    def test_from_diagnostic_to_same(self) -> None:170        cursor = DiagnosticsCursor()171        diags = diagnostics([row1])172        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD)])173        walker.walk(diags)174        self.assertEqual((test_file_path, row1), cursor.value)175        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_FORWARD)])176        walker.walk(diags)177        self.assertEqual((test_file_path, row1), cursor.value)178        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_BACKWARD)])179        walker.walk(diags)180        self.assertEqual((test_file_path, row1), cursor.value)181    def test_from_diagnostic_forward(self) -> None:182        cursor = DiagnosticsCursor()183        walker = DiagnosticsWalker([cursor.from_position(CURSOR_FORWARD)])184        walker.walk(test_diagnostics)185        self.assertEqual((test_file_path, row1), cursor.value)186        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_FORWARD)])187        walker.walk(test_diagnostics)188        self.assertEqual((test_file_path, row5), cursor.value)189        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_FORWARD)])190        walker.walk(test_diagnostics)191        self.assertEqual((second_file_path, row3), cursor.value)192        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_FORWARD)])193        walker.walk(test_diagnostics)194        self.assertEqual((test_file_path, row1), cursor.value)195    def test_from_diagnostic_backward(self) -> None:196        cursor = DiagnosticsCursor()197        walker = DiagnosticsWalker([cursor.from_position(CURSOR_BACKWARD)])198        walker.walk(test_diagnostics)199        self.assertEqual((second_file_path, row3), cursor.value)200        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_BACKWARD)])201        walker.walk(test_diagnostics)202        self.assertEqual((test_file_path, row5), cursor.value)203        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_BACKWARD)])204        walker.walk(test_diagnostics)205        self.assertEqual((test_file_path, row1), cursor.value)206        walker = DiagnosticsWalker([cursor.from_diagnostic(CURSOR_BACKWARD)])207        walker.walk(test_diagnostics)...test_main.py
Source:test_main.py  
1import builtins2import io3import json4import os5import subprocess6import sys7import zipfile8from pathlib import Path9from typing import Any, List10from . import main11from .diagnostics import InvalidLiteralInclude, InvalidURL, UnknownSubstitution12from .n import FileId13from .parser import Project14def test_backend() -> None:15    messages: List[str] = []16    def test_print(*values: Any, **kwargs: Any) -> None:17        messages.extend(str(val) for val in values)18    backend = main.Backend()19    orig_print = builtins.print20    builtins.print = test_print21    test_diagnostics = [22        InvalidLiteralInclude("invalid literal include error", 10, 12),23        InvalidURL((10, 0), (12, 30)),24        UnknownSubstitution("unknown substitution warning", 10),25    ]26    try:27        backend.on_diagnostics(FileId("foo/bar.rst"), test_diagnostics[0:2])28        backend.on_diagnostics(FileId("foo/foo.rst"), test_diagnostics[2:])29        assert backend.total_errors == 230    finally:31        builtins.print = orig_print32    assert messages == [33        f"ERROR(foo/bar.rst:10ish): {test_diagnostics[0].message}",34        f"ERROR(foo/bar.rst:10ish): {test_diagnostics[1].message}",35        f"WARNING(foo/foo.rst:10ish): {test_diagnostics[2].message}",36    ]37    # test returning diagnostic messages as JSON38    backend = main.Backend()39    messages.clear()40    builtins.print = test_print41    os.environ["DIAGNOSTICS_FORMAT"] = "JSON"42    try:43        backend.on_diagnostics(FileId("foo/bar.rst"), test_diagnostics[0:2])44        backend.on_diagnostics(FileId("foo/foo.rst"), test_diagnostics[2:])45        assert backend.total_errors == 246    finally:47        builtins.print = orig_print48    assert [json.loads(message) for message in messages] == [49        {50            "diagnostic": {51                "severity": "ERROR",52                "start": 10,53                "message": test_diagnostics[0].message,54                "path": "foo/bar.rst",55            }56        },57        {58            "diagnostic": {59                "severity": "ERROR",60                "start": 10,61                "message": test_diagnostics[1].message,62                "path": "foo/bar.rst",63            }64        },65        {66            "diagnostic": {67                "severity": "WARNING",68                "start": 10,69                "message": test_diagnostics[2].message,70                "path": "foo/foo.rst",71            }72        },73    ]74def test_parser_failure() -> None:75    return_code = subprocess.call(76        [sys.executable, "-m", "snooty", "build", "test_data/test_parser_failure"]77    )78    assert return_code == 179def test_manifest() -> None:80    f = io.BytesIO()81    zf = zipfile.ZipFile(f, mode="w")82    backend = main.ZipBackend(zf)83    with Project(Path("test_data/test_project/"), backend, {}) as project:84        project.build()85        backend.flush()86        backend.close()87        with zipfile.ZipFile(f, mode="r") as zf:88            zf.testzip()89            assert set(zf.namelist()) == set(90                [91                    "documents/index.bson",92                    "site.bson",93                    "assets/10e351828f156afcafc7744c30d7b2564c6efba1ca7c55cac59560c67581f947",94                ]...diagnostics.py
Source:diagnostics.py  
...42		self.elapsed_time = (self.finish_time - self.start_time).seconds43		logger.info(f'{self.message}: {self.elapsed_time} secs')44# temp test harness ...45# test code46def test_diagnostics():47	# test code timer48	logger.info(f'This message from: {current_function_name()}')49	logger.info(f'Called by: {caller_function_name()}')50	with CodeTimer():51		time.sleep(3)52# main53def main():54	test_diagnostics()55# test code56if __name__ == '__main__':57	log_setup()58	log_session_info()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
