Best Python code snippet using localstack_python
LanguageServer.py
Source:LanguageServer.py
1from os import environ2from sys import executable, platform3from io import BytesIO4from json import load as json_load, loads as json_loads, dumps as json_dumps5from pathlib import Path6from urllib.parse import quote7from subprocess import run as subprocess_run, PIPE8from typing import Optional9from unittest import TestCase10from pytest import mark11from pyGHDL.lsp.lsp import LanguageProtocolServer, LSPConn12class StrConn:13 __res: str14 def __init__(self):15 self.__res = ""16 def write(self, s):17 self.__res += s18 @property19 def res(self):20 return self.__res21def show_diffs(name, ref, res):22 if isinstance(ref, dict) and isinstance(res, dict):23 for k in ref:24 if k not in res:25 print("{}.{} not in the result".format(name, k))26 else:27 show_diffs("{}.{}".format(name, k), ref[k], res[k])28 for k in res:29 if k not in ref:30 print("{}.{} unexpected in the result".format(name, k))31 elif isinstance(ref, str) and isinstance(res, str):32 if res != ref:33 print("{}: mismatch (ref: {}, result: {})".format(name, ref, res))34 elif isinstance(ref, int) and isinstance(res, int):35 if res != ref:36 print("{}: mismatch (ref: {}, result: {})".format(name, ref, res))37 elif isinstance(ref, list) and isinstance(res, list):38 for i in range(max(len(ref), len(res))):39 if i >= len(res):40 print("{}[{}]: missing element:".format(name, i))41 print(" {}".format(res[i]))42 elif i >= len(ref):43 print("{}[{}]: extra elements".format(name, i))44 else:45 show_diffs("{}[{}]".format(name, i), ref[i], res[i])46 else:47 print("unhandle type {} in {}".format(type(ref), name))48def root_subst(obj, path, uri):49 """Substitute in all strings of :param obj: @ROOT@ with :param root:50 URI in LSP are supposed to contain an absolute path. But putting an51 hard absolute path would make the test suite not portable. So we use52 the metaname @ROOT@ which should be replaced by the root path of the53 test suite. Also we need to deal with the windows particularity54 about URI."""55 if isinstance(obj, dict):56 for k, v in obj.items():57 if isinstance(v, str):58 if k in ("rootUri", "uri"):59 assert v.startswith("file://@ROOT@/")60 obj[k] = "file://" + uri + v[13:]61 elif k in ("rootPath", "message"):62 obj[k] = v.replace("@ROOT@", path)63 else:64 obj[k] = root_subst(v, path, uri)65 return obj66 elif obj is None or isinstance(obj, (str, int)):67 return obj68 elif isinstance(obj, list):69 res = []70 for v in obj:71 res.append(root_subst(v, path, uri))72 return res73 else:74 raise AssertionError("root_subst: unhandled type {}".format(type(obj)))75class JSONTest(TestCase):76 _LSPTestDirectory = Path(__file__).parent.resolve()77 subdir = None78 def _RequestResponse(self, requestName: str, responseName: Optional[str] = None):79 root = str(self._LSPTestDirectory)80 root_uri = self._LSPTestDirectory.as_uri()81 assert root_uri.startswith("file://")82 root_uri = root_uri[7:]83 requestFile = self._LSPTestDirectory / self.subdir / requestName84 # Convert the JSON input file to an LSP string.85 with requestFile.open("r") as file:86 res = json_load(file)87 res = root_subst(res, root, root_uri)88 conn = StrConn()89 ls = LanguageProtocolServer(None, conn)90 for req in res:91 ls.write_output(req)92 # Run93 p = subprocess_run(94 [executable, "-m", "pyGHDL.cli.lsp"],95 input=conn.res.encode("utf-8"),96 stdout=PIPE,97 )98 self.assertEqual(99 p.returncode,100 0,101 "Language server executable exit with a non-zero return code.",102 )103 if responseName is None:104 return105 responseFile = self._LSPTestDirectory / self.subdir / responseName106 # Check output107 in_io = BytesIO(p.stdout)108 conn = LSPConn(in_io, None)109 ls = LanguageProtocolServer(None, conn)110 with responseFile.open("r") as file:111 ref = json_load(file)112 ref = root_subst(ref, root, root_uri)113 errs = 0114 json_res = []115 for i, r in enumerate(ref):116 rep = ls.read_request()117 if rep is None:118 print("FAIL: number of reply does not match")119 errs += 1120 break121 rep = json_loads(rep)122 json_res.append(rep)123 # self.assertEqual(rep, r, "reply does not match for {!s}".format(requestFile))124 if rep != r:125 print(self.__class__.__name__)126 show_diffs("[{}]".format(i), r, rep)127 errs += 1128 rep = ls.read_request()129 self.assertIsNone(rep, "Too many replies.")130 if errs != 0:131 print(132 "FAILURE between output and {!s} (for {!s})".format(133 responseFile, requestFile134 )135 )136 print("Writing result output to result.json")137 with open("result.json", "w") as f:138 f.write(json_dumps(json_res, indent=2))139 f.write("\n")140 with open("request.json", "w") as f:141 f.write(json_dumps(res, indent=2))142 f.write("\n")143 self.fail()144class Test001_Simple(JSONTest):145 subdir = Path("001simple")146 def test_Request_Response(self):147 self._RequestResponse("cmds.json", "replies.json")148class Test002_Coverage(JSONTest):149 subdir = Path("002coverage")150 def test_Request_Response(self):151 self._RequestResponse("cmds.json", "replies.json")152class Test003_Errors(JSONTest):153 subdir = Path("003errors")154 def test_Crash1(self):155 self._RequestResponse("crash1.json")156 def test_Crash2(self):157 self._RequestResponse("crash2.json")158 def test_Request_Response(self):159 self._RequestResponse("cmds.json", "replies.json")160@mark.xfail(161 platform == 'win32' and ('MINGW_PREFIX' not in environ),162 reason="needs OpenSSL",163)164class Test004_Error_Project(JSONTest):165 subdir = Path("004errprj")166 def test_Request_Response(self):167 self._RequestResponse("cmds.json", "replies.json")168class Test005_Create(JSONTest):169 subdir = Path("005create")170 def test_Request_Response(self):171 self._RequestResponse("cmds.json", "replies.json")172class Test006_Option_Error(JSONTest):173 subdir = Path("006opterr")174 def test_Request_Response(self):175 self._RequestResponse("cmds.json", "replies.json")176class Test007_Error_Project(JSONTest):177 subdir = Path("007errprj")178 def test_Request_Response(self):179 self._RequestResponse("cmds.json", "replies.json")180class Test008_Error_NoFile(JSONTest):181 subdir = Path("008errnofile")182 def test_Request_Response(self):...
nose_test.py
Source:nose_test.py
1#%%2import requests3from nose.tools import assert_true4#%%5# def test_request_response():6# response = requests.get('http://jsonplaceholder.typicode.com/todos')7# assert_true(response.ok)8# test_request_response()9# nosetests --verbosity=2 nose_test.py10#%%11BASE_URL = 'http://jsonplaceholder.typicode.com/todos'12def parser():13 response = requests.get(BASE_URL)14 resp = response.json15 return resp16from nose.tools import assert_is_not_none17def test_request_response():18 response = parser()19 ...
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!!