Best Python code snippet using tox_python
vscode-ext.py
Source:vscode-ext.py
1#!/usr/bin/env python32# Download the last Visual Studio Code extension compatible with a given version3import argparse4import json5import requests6from pathlib import Path7import os8from dateutil.parser import parse as parsedate9import re10import zipfile11import subprocess12# constants from vscode extension API13# https://github.com/microsoft/vscode/blob/main/src/vs/platform/extensionManagement/common/extensionGalleryService.ts14FilterType_Tag = 115FilterType_ExtensionId = 416FilterType_Category = 517FilterType_ExtensionName = 718FilterType_Target = 819FilterType_Featured = 920FilterType_SearchText = 1021FilterType_ExcludeWithFlags = 1222Flags_None = 0x023Flags_IncludeVersions = 0x124Flags_IncludeFiles = 0x225Flags_IncludeCategoryAndTags = 0x426Flags_IncludeSharedAccounts = 0x827Flags_IncludeVersionProperties = 0x1028Flags_ExcludeNonValidated = 0x2029Flags_IncludeInstallationTargets = 0x4030Flags_IncludeAssetUri = 0x8031Flags_IncludeStatistics = 0x10032Flags_IncludeLatestVersionOnly = 0x20033Flags_Unpublished = 0x100034Flags_IncludeNameConflictInfo = 0x800035def get_property(version, name):36 if "properties" not in version:37 # print(version)38 return39 for property in version["properties"]:40 if property["key"] == name:41 return property["value"]42 return43def version_serial(version):44 v = version.split(".", maxsplit=2)45 if "-" in v[2]:46 r = v[2].split("-", maxsplit=1)47 t = (int(v[0]), int(v[1]), int(r[0]), r[1])48 return t49 else:50 return tuple(map(int, v))51def engine_match(pattern, engine):52 if pattern == "*":53 return True54 if pattern[0] != "^":55 if pattern == "0.10.x" or pattern.endswith("-insider"):56 return False57 # print("missing caret:", pattern)58 return False59 assert pattern[0] == "^"60 def rr():61 p = version_serial(pattern[1:])62 v = version_serial(engine)63 if len(p) == 4 and p[3] == "insiders":64 return False65 if p[0] != v[0]: # major must be the same66 return False67 if p[1] > v[1]: # minor must be greater or equal68 return False69 if p[1] == v[1] and p[2] != 0 and p[2] > v[2]:70 return False71 return True72 r = rr()73 # print(pattern, engine, r)74 return r75class Extension:76 def __init__(self, engine, verbose=False):77 self.engine = engine78 self.verbose = verbose79 def run(self, dest_dir, slugs):80 """Download all extensions and packs."""81 self.all_extensions = set()82 self._get_downloads(slugs)83 self._download_files(dest_dir)84 while self.packs:85 new_extensions = set()86 for vsix in self.downloads:87 if vsix in self.packs:88 zip = zipfile.ZipFile(dest_dir / vsix)89 m = json.loads(zip.open("extension/package.json").read())90 new_extensions.update(m["extensionPack"])91 zip.close()92 new_extensions.difference_update(self.all_extensions)93 self._get_downloads(new_extensions)94 self._download_files(dest_dir)95 def _download_files(self, dest_dir):96 """Download extesions archive (VSIX)."""97 for k, v in self.downloads.items():98 vsix = dest_dir / k99 if not vsix.exists():100 vsix.parent.mkdir(parents=True, exist_ok=True)101 print("downloading", vsix)102 r = requests.get(v[2])103 vsix.write_bytes(r.content)104 url_date = parsedate(v[3])105 mtime = round(url_date.timestamp() * 1_000_000_000)106 os.utime(vsix, ns=(mtime, mtime))107 else:108 print(f"already downloaded: {vsix.name}")109 def _get_downloads(self, slugs):110 """Build the extension list to download."""111 self.downloads = {}112 self.packs = set()113 if not slugs:114 return115 r = self._query(slugs)116 for result in r["results"]:117 for extension in result["extensions"]:118 vsix = self._get_download(extension)119 if vsix:120 if "Extension Packs" in extension["categories"]:121 self.packs.update(vsix)122 self.all_extensions.update(vsix)123 def _query(self, slugs):124 """125 Prepare the request tp the extension server, with::126 - assets uri (Flags.IncludeAssetUri)127 - details (Flags.IncludeVersionProperties)128 - categories (Flags.IncludeCategoryAndTags)129 """130 data = {131 "filters": [132 {133 "criteria": [134 {135 "filterType": FilterType_Target,136 "value": "Microsoft.VisualStudio.Code",137 },138 {139 "filterType": FilterType_ExcludeWithFlags,140 "value": str(Flags_Unpublished),141 },142 # {143 # "filterType": FilterType_ExtensionName,144 # "value": args.slug,145 # },146 ]147 }148 ],149 "flags": Flags_IncludeAssetUri + Flags_IncludeVersionProperties + Flags_IncludeCategoryAndTags,150 }151 for slug in slugs:152 data["filters"][0]["criteria"].append({"filterType": FilterType_ExtensionName, "value": slug})153 data = json.dumps(data)154 r = requests.post(155 "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery",156 data=data,157 headers={158 "Content-Type": "application/json",159 "Accept": "application/json;api-version=3.0-preview.1",160 },161 )162 if self.verbose:163 Path("query.json").write_text(data)164 Path("response.json").write_bytes(r.content)165 r = r.json()166 # r = json.load(open("response.json"))167 return r168 def _get_download(self, extension):169 name = extension["publisher"]["publisherName"] + "." + extension["extensionName"]170 def filter_version(extension, platform):171 has_target_platform = set()172 for version in extension["versions"]:173 # sanity check174 if version["flags"] != "validated" and version["flags"] != "none":175 print("flags should be 'validated' or 'none'")176 print(json.dumps(version, indent=2))177 exit()178 # do not use pre-release version179 v = get_property(version, "Microsoft.VisualStudio.Code.PreRelease")180 if v == "true":181 continue182 # we have to match the engine version183 v = get_property(version, "Microsoft.VisualStudio.Code.Engine")184 if not (v and engine_match(v, self.engine)):185 continue186 if version.get("targetPlatform") != None:187 has_target_platform.add(version["version"])188 # we have to match the platform if asked and specified for the version189 if version["version"] in has_target_platform and platform and version.get("targetPlatform") != platform:190 continue191 yield version192 def find_latest_version(extension, platform):193 versions = filter_version(extension, platform)194 versions = sorted(versions, key=lambda v: version_serial(v["version"]))195 if versions:196 return versions[-1]197 def find_version_vsix(extension, platform):198 version = find_latest_version(extension, platform)199 if name == "vadimcn.vscode-lldb":200 if "alpine" in platform:201 return202 os, arch = platform.split("-")203 # cf. extension/package.json of the generic extension204 arch = {"x64": "x86_64", "arm64": "aarch64"}.get(arch)205 asset_uri = f"https://github.com/vadimcn/vscode-lldb/releases/download/v{version['version']}/codelldb-{arch}-{os}.vsix"206 target_platform = platform207 else:208 if not version:209 print(f"missing {platform} for {name}")210 return211 asset_uri = version["assetUri"] + "/Microsoft.VisualStudio.Services.VSIXPackage"212 target_platform = version.get("targetPlatform")213 if target_platform:214 vsix = name + "-" + target_platform + "-" + version["version"] + ".vsix"215 else:216 vsix = name + "-" + version["version"] + ".vsix"217 download = (218 version["version"],219 get_property(version, "Microsoft.VisualStudio.Code.Engine"),220 asset_uri,221 version["lastUpdated"],222 )223 if vsix in self.downloads:224 assert self.downloads[vsix] == download225 self.downloads[vsix] = download226 return vsix227 vsix = set()228 vsix.add(find_version_vsix(extension, "linux-x64"))229 vsix.add(find_version_vsix(extension, "linux-arm64"))230 vsix.add(find_version_vsix(extension, "alpine-x64"))231 vsix.add(find_version_vsix(extension, "alpine-arm64"))232 return vsix233def vscode_latest_version(channel="stable"):234 """Retrieve current VSCode version from Windows download link."""235 url = f"https://code.visualstudio.com/sha/download?build={channel}&os=win32-x64-archive"236 r = requests.get(url, allow_redirects=False)237 if r is None or r.status_code != 302:238 print(f"request error {r}")239 exit(2)240 url = r.headers["Location"]241 m = re.search(r"/(\w+)/([a-f0-9]{40})/VSCode-win32-x64-([\d.]+).zip", url)242 if not m or m[1] != channel:243 print(f"cannot extract vscode version from url {url}")244 exit(2)245 _, commit_id, version = m.groups()246 print(f"Using VSCode {version} {commit_id} {channel}")247 return version, commit_id248def check_local(slugs):249 """250 Compare the list of desired extensions with the list of locally installed extensions.251 """252 set_installed = set(subprocess.check_output(["code", "--list-extensions"]).decode().split())253 set_wanted = set(slugs)254 # check the case255 set_installed_lowercase = set(map(str.lower, set_installed))256 for i in set_wanted:257 if i in set_installed:258 continue259 if i.lower() in set_installed_lowercase:260 for j in set_installed:261 if j.lower() == i.lower():262 print(f"Upper/lower case problem with {i}, should be {j}")263 return 2264 set3 = set_wanted.union(set_installed)265 color_wanted = "95"266 color_installed = "93"267 extension, color, a, b = "extension", "37", "wanted", "installed"268 print(f"\033[1;3;{color}m{extension:<55}\033[{color_wanted}m{a:^9}\033[{color_installed}m{b:^9}\033[0m")269 for extension in sorted(set3):270 a = extension in set_wanted271 b = extension in set_installed272 color = "37"273 if not a and b:274 color = color_installed275 if a and not b:276 color = color_wanted277 a = "ââ
"[a]278 b = "ââ
"[b]279 # see explaination here:280 # https://wezfurlong.org/wezterm/hyperlinks.html#explicit-hyperlinks281 link = f"\033]8;;https://marketplace.visualstudio.com/items?itemName={extension}\033\\{extension}\033]8;;\033\\"282 link += " " * (55 - len(extension))283 print(f"\033[{color}m{link}\033[0m{a:^9}{b:^9}")284 return 0285def main():286 parser = argparse.ArgumentParser()287 parser.add_argument("-v", "--verbose", help="verbose and debug info", action="store_true")288 parser.add_argument("-d", "--dest-dir", help="output dir", type=Path, default=".")289 parser.add_argument("-e", "--engine", help="engine version", default="current")290 parser.add_argument("-c", "--config", help="conf file", type=Path)291 parser.add_argument("--check-local", help=argparse.SUPPRESS, action="store_true")292 parser.add_argument("slugs", help="extension identifier", nargs="*")293 args = parser.parse_args()294 if args.config:295 in_section = False296 for i in args.config.read_text().splitlines():297 i = i.strip()298 if not i or i.startswith("#"):299 continue300 if i.startswith("["):301 in_section = i.startswith("[vscode")302 else:303 if in_section:304 args.slugs.append(i)305 if args.check_local:306 exit(check_local(args.slugs))307 if args.engine == "latest":308 args.engine, _ = vscode_latest_version()309 elif args.engine == "current":310 args.engine = (args.dest_dir / "vscode-version").read_text().strip()311 print(f"Using vscode {args.engine}")312 dest_dir = args.dest_dir / f"vscode-extensions-{args.engine}"313 dest_dir.mkdir(exist_ok=True, parents=True)314 e = Extension(args.engine, args.verbose)315 e.run(dest_dir, args.slugs)316if __name__ == "__main__":...
root.py
Source:root.py
1# R overlay -- root interface2# -*- coding: utf-8 -*-3# Copyright (C) 2013 André Erdmann <dywi@mailerd.de>4# Distributed under the terms of the GNU General Public License;5# either version 2 of the License, or (at your option) any later version.6import logging7import roverlay.core8import roverlay.errorqueue9import roverlay.hook10import roverlay.config.tree11import roverlay.interface.generic12# does nothing if already initialized13roverlay.core.setup_initial_logger()14def get_dummy_config():15 return roverlay.config.tree.ConfigTree()16# --- end of get_dummy_config (...) ---17class RootInterface ( roverlay.interface.generic.RoverlayInterface ):18 """Root interfaces for accessing roverlay interfaces.19 See MainInterface for a root interface with delayed initialization.20 """21 # class-wide map ( <interface name> => <interface class> )22 # for creating/"spawning" subinterfaces23 #24 SPAWN_MAP = dict()25 @classmethod26 def register_interface ( my_cls, name, cls, force=False ):27 """Registers a subinterface with the root interface.28 arguments:29 * name -- name of the interface, e.g. "depres"30 * cls -- interface class31 * force -- if True: overwrite existing entries for name32 Defaults to False.33 """34 if name and ( force or name not in my_cls.SPAWN_MAP ):35 my_cls.SPAWN_MAP [name] = cls36 return True37 else:38 return False39 # --- end of register_interface (...) ---40 @classmethod41 def new_unconfigured ( cls, **kwargs ):42 """Creates a new root interface with a dummy config tree.43 arguments:44 * **kwargs -- passed to __init__()45 """46 kwargs ['config'] = False47 return cls ( **kwargs )48 # --- end of new_unconfigured (...) ---49 def __init__ ( self,50 config_file=None, config=None, additional_config=None, is_installed=None51 ):52 """Initializes the root interface:53 * loads the config54 * creates shared objects like logger and error queue55 * calls roverlay.hook.setup()56 arguments:57 * config_file -- path to the config file58 * config -- config tree or None59 takes precedence over config_file60 A dummy config tree will be created if this61 arg is False.62 * additional_config -- when loading the config file: extra config dict63 * is_installed -- whether roverlay has been installed or not64 Defaults to None.65 """66 super ( RootInterface, self ).__init__()67 self.parent = None68 self.err_queue = roverlay.errorqueue.ErrorQueue()69 self.config_file = config_file70 if getattr ( self, 'config', None ):71 pass72 elif config is False:73 self.config = get_dummy_config()74 elif config is not None:75 self.config = config76 elif config_file is not None:77 if additional_config is None:78 self.config = roverlay.core.load_config_file (79 config_file, extraconf={ 'installed': False, }80 )81 else:82 # modifies additional_config83 additional_config.update ( { 'installed': False, } )84 self.config = roverlay.core.load_config_file (85 config_file, extraconf=additional_config86 )87 else:88 raise Exception ( "config, config_file?" )89 if is_installed is not None:90 self.set_installed ( is_installed )91 elif self.config.get ( "installed", None ) is None:92 self.set_installed ( False )93 self.logger = logging.getLogger ( self.__class__.__name__ )94 roverlay.hook.setup()95 # --- end of __init__ (...) ---96 def set_installed ( self, status=True ):97 """Marks roverlay as installed/not installed.98 arguments:99 * status -- installation status bool (defaults to True)100 Returns: None (implicit)101 """102 self.config.merge_with ( { 'installed': bool ( status ), } )103 # --- end of set_installed (...) ---104 def spawn_interface ( self, name ):105 """Spawns an registered subinterface.106 (Creates it if necessary, else uses the existing one.)107 arguments:108 * name -- name of the interface, e.g. "depres"109 Returns: subinterface110 """111 if self.has_interface ( name ):112 return self.get_interface ( name )113 else:114 iface_cls = self.SPAWN_MAP.get ( name, None )115 if iface_cls is None:116 raise Exception (117 "unknown interface identifier {!r}".format ( name )118 )119 else:120 return self.attach_interface (121 name, iface_cls ( parent_interface=self )122 )123 # --- end of spawn_interface (...) ---124 def run_hook ( self, phase ):125 """Triggers a hook event.126 arguments:127 * phase -- event, e.g. "overlay_success" or "user"128 Returns: success (True/False)129 """130 return roverlay.hook.run ( phase, catch_failure=False )...
test_package.py
Source:test_package.py
...6import unittest7from tomlparser.package import Package8class TestPackage(unittest.TestCase):9 p = Package("TestPackage")10 p.set_installed()11 p2 = Package("TestPackage2")12 p2.set_installed()13 p3 = Package("A_TestPackage")14 def test_Package_setters_and_getters(self):15 self.assertEqual(self.p.get_name(), "TestPackage")16 desc = "this is a test package"17 self.p.set_desc(desc)18 self.assertEqual(self.p.get_desc(), desc)19 self.assertTrue(self.p.get_installed())20 self.p.add_depency(self.p2)21 self.p.add_depency(self.p3)22 self.assertEqual(self.p.get_depencies(), [self.p3, self.p2])23 self.p.add_reverse_depency(self.p2)24 self.p.add_reverse_depency(self.p3)25 self.assertEqual(self.p.get_reverse_depencies(), [self.p3, self.p2])26if __name__ == "__main__":...
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!!