How to use is_posix method in lisa

Best Python code snippet using lisa_python

utils.py

Source:utils.py Github

copy

Full Screen

1"""ZT platform and JSON/file handling utilities."""2import json3import os4import random5import string6import sys7from pathlib import Path8def platform_check():9 """10 Check to see if we think we are POSIX.11 :return valid_os: True if POSIX, else False12 """13 valid_os = []14 myname = sys.platform15 is_posix = os.name == 'posix'16 posix_list = [17 'linux',18 'darwin',19 'openbsd',20 'freebsd',21 ]22 valid_os = [x for x in posix_list if x in myname and is_posix]23 return valid_os24def pprint(obj):25 """26 Pretty printer for JSON.27 :param obj: JSON obj28 """29 print(json.dumps(obj, indent=2, separators=(',', ': ')))30def json_dump_file(endpoint, data, dirname=None, is_posix=platform_check()): # noqa31 """32 Dump JSON endpoint data to a named file and, optionally, to a target33 directory.34 :param endpoint: ZT endpoint name => filename35 :param data: endpoint data to dump36 :param dirname: target directory name37 :param is_posix: default is ``platform_check()``, force True/False38 if needed39 """40 if dirname and is_posix:41 def opener(dirname, flags):42 return os.open(dirname, flags, dir_fd=dir_fd)43 dir_fd = os.open(dirname, os.O_RDONLY)44 elif dirname and not is_posix:45 endpoint = os.path.join(dirname, endpoint)46 opener = None47 else:48 opener = None49 dump_json(endpoint, data, opener=opener)50def json_load_file(endpoint, dirname=None, is_posix=platform_check()): # noqa51 """52 Load JSON endpoint data from a named file and, optionally, a target53 directory.54 :param endpoint: ZT endpoint name => filename55 :param dirname: target directory name56 :param is_posix: default is ``platform_check()``, force True/False57 """58 if dirname and is_posix:59 def opener(dirname, flags):60 return os.open(dirname, flags, dir_fd=dir_fd)61 dir_fd = os.open(dirname, os.O_RDONLY)62 elif dirname and not is_posix:63 endpoint = os.path.join(dirname, endpoint)64 opener = None65 else:66 opener = None67 data = load_json(endpoint, opener=opener)68 return data69def dump_json(endpoint, data, opener=None):70 """Dump JSON endpoint data to a file using optional ``opener``."""71 with open(endpoint + '.json', 'w', encoding='utf-8', opener=opener) as f_ptr:72 json.dump(data, f_ptr)73 print(f'{endpoint} data saved to {endpoint}.json')74def load_json(endpoint, opener=None):75 """Load JSON endpoint data from a file using optional ``opener``."""76 with open(endpoint + '.json', 'r', encoding='utf-8', opener=opener) as f_ptr:77 data = json.load(f_ptr)78 print(f'{endpoint} data read from {endpoint}.json')79 return data80def get_token(zt_home=None):81 """82 Get ZeroTier authentication token (requires root or user acl).83 :param zt_home: non-std path to ZT home directory84 :return zt_auth: contents of ZT authtoken file or None85 """86 zt_auth = None87 if not zt_home:88 zt_home = get_platform_path()89 else:90 zt_home = Path(zt_home)91 if zt_home.exists():92 zt_auth = zt_home.joinpath('authtoken.secret').read_text(encoding='utf-8')93 return zt_auth94def get_platform_path():95 """96 Find platform path to ZT home directory (where the authtoken lives).97 :return: path to ZT home as Path obj98 """99 name = sys.platform100 platform_paths = {101 'win32': Path('C:\\ProgramData\\ZeroTier\\One'),102 'linux': Path('/var/lib/zerotier-one'),103 'darwin': Path('/Library/Application Support/ZeroTier/One'),104 'bsd': Path('/var/db/zerotier-one'),105 }106 plat_name = [x for x in platform_paths if x in name]107 return platform_paths[plat_name[0]]108def name_generator(109 size=10, chars=string.ascii_lowercase + string.digits, no_sep=False110):111 """112 Generate random ZeroTier network names or other ID strings. Default113 is 2 substrings of ``size`` with an underscore as separator, eg, if114 ``size`` is 10, the returned string is 21 characters.115 :param size: number of chars in each substring116 :param chars: character types used117 :param no_sep: if False, do not use separator, return ``size`` instead118 :return str:119 """120 str1 = ''.join(random.choice(chars) for _ in range(size))121 str2 = ''.join(random.choice(chars) for _ in range(size))122 if no_sep:123 return str1...

Full Screen

Full Screen

gen_cmake_test.py

Source:gen_cmake_test.py Github

copy

Full Screen

1#!/usr/bin/env python32#3# Copyright 2020 the V8 project authors. All rights reserved.4# Use of this source code is governed by a BSD-style license that can be5# found in the LICENSE file.6from gen_cmake import CMakeBuilder, V8GNTransformer, ParseGN, V8_TARGET_TYPES7import unittest8class CMakeMockBuilder(CMakeBuilder):9 """10 Similar to CMakeBuilder but doesn't produce prologues/epilogues.11 """12 def BuildPrologue(self):13 pass14 def BuildEpilogue(self):15 pass16class CMakeGenerationTest(unittest.TestCase):17 TARGET = 'cppgc_base'18 CMAKE_TARGET_SOURCES = TARGET.upper() + '_SOURCES'19 def test_source_assignment(self):20 self._CompileAndCheck(21 f'set({self.CMAKE_TARGET_SOURCES} "source1.h" "source1.cc")',22 'sources = [ "source1.h", "source1.cc", ]')23 def test_source_append(self):24 self._CompileAndCheck(25 f'list(APPEND {self.CMAKE_TARGET_SOURCES} "source1.h" "source1.cc")',26 'sources += [ "source1.h", "source1.cc", ]')27 def test_source_remove(self):28 self._CompileAndCheck(29 f'list(REMOVE_ITEM {self.CMAKE_TARGET_SOURCES} "source1.h" "source1.cc")',30 'sources -= [ "source1.h", "source1.cc", ]')31 def test_equal(self):32 self._CompileExpressionAndCheck('"${CURRENT_CPU}" STREQUAL "x64"',33 'current_cpu == "x64"')34 def test_not_equal(self):35 self._CompileExpressionAndCheck('NOT "${CURRENT_CPU}" STREQUAL "x86"',36 'current_cpu != "x86"')37 def test_comparison_ops(self):38 OPS = {39 '<': 'LESS',40 '<=': 'LESS_EQUAL',41 '>': 'GREATER',42 '>=': 'GREATER_EQUAL',43 }44 for gn_op, cmake_op in OPS.items():45 self._CompileExpressionAndCheck(46 f'"${{GCC_VERSION}}" {cmake_op} 40802',47 f'gcc_version {gn_op} 40802')48 def test_parenthesized_expressions(self):49 self._CompileExpressionAndCheck(50 '(("${IS_POSIX}" AND NOT "${IS_ANDROID}") OR "${IS_FUCHSIA}") AND NOT "${USING_SANITIZER}"',51 '((is_posix && !is_android) || is_fuchsia) && !using_sanitizer')52 def test_conditional_statements(self):53 self._CompileAndCheck(54 f"""55if("${{IS_POSIX}}")56 list(APPEND {self.CMAKE_TARGET_SOURCES} "unistd.h")57else()58 list(REMOVE_ITEM {self.CMAKE_TARGET_SOURCES} "unistd.h")59endif()60 """, """61if (is_posix) {62 sources += ["unistd.h"]63} else {64 sources -= ["unistd.h"]65}66 """)67 def test_conditional_statements_elseif(self):68 self._CompileAndCheck(69 f"""70if("${{IS_POSIX}}")71 list(APPEND {self.CMAKE_TARGET_SOURCES} "unistd.h")72elseif("${{IS_WIN}}")73 list(REMOVE_ITEM {self.CMAKE_TARGET_SOURCES} "unistd.h")74endif()75 """, """76if (is_posix) {77 sources += ["unistd.h"]78} else if (is_win) {79 sources -= ["unistd.h"]80}81 """)82 def _Compile(self, gn_string):83 gn_code = f'v8_component({self.TARGET}) {{ {gn_string} }}'84 tree = ParseGN(gn_code)85 builder = CMakeMockBuilder()86 V8GNTransformer(builder, [self.TARGET]).Traverse(tree)87 return builder.GetResult()88 def _CompileAndCheck(self, expected_cmake, gn_string):89 actual_cmake = self._Compile(gn_string)90 self.assertIn(self._Canonicalize(expected_cmake),91 self._Canonicalize(actual_cmake))92 pass93 def _CompileExpressionAndCheck(self, expected_cmake, gn_string):94 gn_string = f'if ({gn_string}) {{ sources = [ "source.cc" ] }}'95 expected_cmake = f'if({expected_cmake})'96 actual_cmake = self._Compile(gn_string)97 self.assertIn(self._Canonicalize(expected_cmake),98 self._Canonicalize(actual_cmake))99 pass100 @staticmethod101 def _Canonicalize(str):102 return ' '.join(str.split()).strip()103if __name__ == '__main__':...

Full Screen

Full Screen

client.py

Source:client.py Github

copy

Full Screen

2from secretwallet.constants import parameters, is_posix3from secretwallet.utils.logging import get_logger4logger = get_logger(__name__)5def get_session_password():6 if not is_posix():7 raise NotImplementedError("Client/Server daemons not supported on this system")8 logger.info("Retrieving session password")9 conn = Client(parameters.get_session_address(), authkey=parameters.get_session_connection_password()) 10 conn.send({'action':'get','password':None})11 r = conn.recv()12 conn.close()13 return r['status'],r['password']14def set_session_password(pwd):15 if not is_posix():16 return 17 logger.info("Setting session password")18 conn = Client(parameters.get_session_address(), authkey=parameters.get_session_connection_password()) 19 conn.send({'action':'set','password':pwd})20 r = conn.recv()21 conn.close()22 logger.debug(r['status'])23def stop_service():24 if not is_posix():25 return26 logger.info("Stopping the service")27 conn = Client(parameters.get_session_address(), authkey=parameters.get_session_connection_password()) 28 conn.send({'action':'stop','password':None})29 r = conn.recv()30 conn.close()31 logger.debug(r['status'])32 33def is_connected():34 if parameters.is_in_shell():35 return False #the secret_wallet shell has a different way to keep the password36 if not is_posix():37 return False #only posix systems support daemons in the way required38 try:39 get_session_password()40 return True41 except ConnectionRefusedError:42 return False...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run lisa automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful