_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q256500
Wallet.getAccountsFromPublicKey
validation
def getAccountsFromPublicKey(self, pub): """ Obtain all accounts associated with a public key """
python
{ "resource": "" }
q256501
Wallet.getAccountFromPublicKey
validation
def getAccountFromPublicKey(self, pub): """ Obtain the first account name from public key """ # FIXME, this only returns the first associated key.
python
{ "resource": "" }
q256502
Wallet.getKeyType
validation
def getKeyType(self, account, pub): """ Get key type """ for authority in ["owner", "active"]: for key in account[authority]["key_auths"]: if str(pub) == key[0]:
python
{ "resource": "" }
q256503
Wallet.getAccounts
validation
def getAccounts(self): """ Return all accounts installed in the wallet database """ pubkeys = self.getPublicKeys() accounts = [] for pubkey in pubkeys: # Filter those keys not for our network
python
{ "resource": "" }
q256504
Wallet.getPublicKeys
validation
def getPublicKeys(self, current=False): """ Return all installed public keys :param bool current: If true, returns only keys for currently connected blockchain """
python
{ "resource": "" }
q256505
Memo.unlock_wallet
validation
def unlock_wallet(self, *args, **kwargs): """ Unlock the library internal wallet """
python
{ "resource": "" }
q256506
Memo.encrypt
validation
def encrypt(self, message): """ Encrypt a memo :param str message: clear text memo message :returns: encrypted message :rtype: str """ if not message: return None nonce = str(random.getrandbits(64)) try: memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey( self.from_account["options"]["memo_key"] ) except KeyNotFound: # if all fails, raise exception raise MissingKeyError( "Memo private key {} for {} could not be found".format( self.from_account["options"]["memo_key"], self.from_account["name"] ) ) if not memo_wif: raise MissingKeyError( "Memo key for %s missing!" % self.from_account["name"] ) if not hasattr(self, "chain_prefix"): self.chain_prefix
python
{ "resource": "" }
q256507
Memo.decrypt
validation
def decrypt(self, message): """ Decrypt a message :param dict message: encrypted memo message :returns: decrypted message :rtype: str """ if not message: return None # We first try to decode assuming we received the memo try: memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(message["to"]) pubkey = message["from"] except KeyNotFound: try: # if that failed, we assume that we have sent the memo memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey( message["from"] ) pubkey = message["to"] except KeyNotFound: # if all fails, raise exception raise MissingKeyError(
python
{ "resource": "" }
q256508
get_shared_secret
validation
def get_shared_secret(priv, pub): """ Derive the share secret between ``priv`` and ``pub`` :param `Base58` priv: Private Key :param `Base58` pub: Public Key :return: Shared secret :rtype: hex The shared secret is generated such that:: Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)
python
{ "resource": "" }
q256509
init_aes
validation
def init_aes(shared_secret, nonce): """ Initialize AES instance :param hex shared_secret: Shared Secret to use as encryption key :param int nonce: Random nonce :return: AES instance :rtype: AES """ " Shared Secret " ss = hashlib.sha512(unhexlify(shared_secret)).digest() " Seed " seed = bytes(str(nonce), "ascii") + hexlify(ss)
python
{ "resource": "" }
q256510
encode_memo
validation
def encode_memo(priv, pub, nonce, message): """ Encode a message with a shared secret between Alice and Bob :param PrivateKey priv: Private Key (of Alice) :param PublicKey pub: Public Key (of Bob) :param int nonce: Random nonce :param str message: Memo message :return: Encrypted message :rtype: hex """ shared_secret =
python
{ "resource": "" }
q256511
decode_memo
validation
def decode_memo(priv, pub, nonce, message): """ Decode a message with a shared secret between Alice and Bob :param PrivateKey priv: Private Key (of Bob) :param PublicKey pub: Public Key (of Alice) :param int nonce: Nonce used for Encryption :param bytes message: Encrypted Memo message :return: Decrypted message :rtype: str :raise ValueError: if message cannot be decoded as valid UTF-8 string """ shared_secret = get_shared_secret(priv, pub) aes = init_aes(shared_secret, nonce) " Encryption " raw = bytes(message, "ascii") cleartext = aes.decrypt(unhexlify(raw)) "
python
{ "resource": "" }
q256512
env
validation
def env(): """Verify IPMI environment""" ipmi = cij.env_to_dict(PREFIX, REQUIRED) if ipmi is None: ipmi["USER"] = "admin" ipmi["PASS"] = "admin" ipmi["HOST"] = "localhost" ipmi["PORT"] = "623" cij.info("ipmi.env: USER: %s, PASS: %s, HOST: %s, PORT: %s" %
python
{ "resource": "" }
q256513
cmd
validation
def cmd(command): """Send IPMI 'command' via ipmitool""" env() ipmi = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED) command = "ipmitool -U %s -P %s -H %s -p %s %s" % (
python
{ "resource": "" }
q256514
regex_find
validation
def regex_find(pattern, content): """Find the given 'pattern' in 'content'""" find = re.findall(pattern, content) if not find: cij.err("pattern <%r> is invalid, no matches!" % pattern) cij.err("content: %r" % content) return '' if len(find) >= 2:
python
{ "resource": "" }
q256515
execute
validation
def execute(cmd=None, shell=True, echo=True): """ Execute the given 'cmd' @returns (rcode, stdout, stderr) """ if echo: cij.emph("cij.util.execute: shell: %r, cmd: %r" % (shell, cmd)) rcode = 1 stdout, stderr = ("", "") if cmd: if shell: cmd = " ".join(cmd) proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=shell, close_fds=True)
python
{ "resource": "" }
q256516
env
validation
def env(): """Verify BOARD variables and construct exported variables""" if cij.ssh.env(): cij.err("board.env: invalid SSH environment") return 1 board = cij.env_to_dict(PREFIX, REQUIRED) # Verify REQUIRED variables if board is None: cij.err("board.env: invalid BOARD environment") return 1
python
{ "resource": "" }
q256517
cat_file
validation
def cat_file(path): """Cat file and return content""" cmd = ["cat", path] status, stdout, _ = cij.ssh.command(cmd, shell=True, echo=True) if status:
python
{ "resource": "" }
q256518
fmt
validation
def fmt(lbaf=3): """Do format for NVMe device""" if env(): cij.err("cij.nvme.exists: Invalid NVMe ENV.") return 1 nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED) cmd
python
{ "resource": "" }
q256519
get_meta
validation
def get_meta(offset, length, output): """Get chunk meta of NVMe device""" if env(): cij.err("cij.nvme.meta: Invalid NVMe ENV.") return 1 nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED) max_size = 0x40000 with open(output, "wb") as fout: for off in range(offset, length, max_size):
python
{ "resource": "" }
q256520
get_sizeof_descriptor_table
validation
def get_sizeof_descriptor_table(version="Denali"): """ Get sizeof DescriptorTable """ if version == "Denali": return sizeof(DescriptorTableDenali) elif version == "Spec20": return
python
{ "resource": "" }
q256521
env
validation
def env(): """Verify LNVM variables and construct exported variables""" if cij.ssh.env(): cij.err("cij.lnvm.env: invalid SSH environment") return 1 lnvm = cij.env_to_dict(PREFIX, REQUIRED) nvme = cij.env_to_dict("NVME", ["DEV_NAME"]) if "BGN" not in lnvm.keys(): cij.err("cij.lnvm.env: invalid LNVM_BGN") return 1 if "END" not in lnvm.keys(): cij.err("cij.lnvm.env: invalid LNVM_END")
python
{ "resource": "" }
q256522
create
validation
def create(): """Create LNVM device""" if env(): cij.err("cij.lnvm.create: Invalid LNVM ENV") return 1 nvme = cij.env_to_dict("NVME", ["DEV_NAME"]) lnvm = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED) cij.emph("lnvm.create: LNVM_DEV_NAME: %s" % lnvm["DEV_NAME"]) cmd = ["nvme lnvm create -d %s -n %s -t %s -b %s -e %s -f" % ( nvme["DEV_NAME"],
python
{ "resource": "" }
q256523
compare
validation
def compare(buf_a, buf_b, ignore): """Compare of two Buffer item""" for field in getattr(buf_a, '_fields_'): name, types = field[0], field[1] if name in ignore: continue val_a = getattr(buf_a, name) val_b = getattr(buf_b, name) if isinstance(types, (type(Union), type(Structure))): if compare(val_a, val_b, ignore): return 1 elif isinstance(types, type(Array)): for i, _ in enumerate(val_a):
python
{ "resource": "" }
q256524
Buffer.memcopy
validation
def memcopy(self, stream, offset=0, length=float("inf")): """Copy stream to buffer""" data = [ord(i) for i in list(stream)] size = min(length, len(data), self.m_size)
python
{ "resource": "" }
q256525
Buffer.write
validation
def write(self, path): """Write buffer to file"""
python
{ "resource": "" }
q256526
Buffer.read
validation
def read(self, path): """Read file to buffer""" with open(path,
python
{ "resource": "" }
q256527
Relay.power_on
validation
def power_on(self, interval=200): """230v power on""" if self.__power_on_port is None: cij.err("cij.usb.relay: Invalid USB_RELAY_POWER_ON")
python
{ "resource": "" }
q256528
Relay.power_off
validation
def power_off(self, interval=200): """230v power off""" if self.__power_off_port is None: cij.err("cij.usb.relay: Invalid USB_RELAY_POWER_OFF")
python
{ "resource": "" }
q256529
Relay.power_btn
validation
def power_btn(self, interval=200): """TARGET power button""" if self.__power_btn_port is None: cij.err("cij.usb.relay: Invalid USB_RELAY_POWER_BTN")
python
{ "resource": "" }
q256530
Spdk.get_chunk_information
validation
def get_chunk_information(self, chk, lun, chunk_name): """Get chunk information""" cmd = ["nvm_cmd rprt_lun", self.envs, "%d
python
{ "resource": "" }
q256531
env
validation
def env(): """Verify BLOCK variables and construct exported variables""" if cij.ssh.env(): cij.err("cij.block.env: invalid SSH environment") return 1 block
python
{ "resource": "" }
q256532
script_run
validation
def script_run(trun, script): """Execute a script or testcase""" if trun["conf"]["VERBOSE"]: cij.emph("rnr:script:run { script: %s }" % script) cij.emph("rnr:script:run:evars: %s" % script["evars"]) launchers = { ".py": "python", ".sh": "source" } ext = os.path.splitext(script["fpath"])[-1] if not ext in launchers.keys(): cij.err("rnr:script:run { invalid script[\"fpath\"]: %r }" % script["fpath"]) return 1 launch = launchers[ext] with open(script["log_fpath"], "a") as log_fd: log_fd.write("# script_fpath: %r\n" % script["fpath"]) log_fd.flush() bgn = time.time() cmd = [ 'bash', '-c', 'CIJ_ROOT=$(cij_root) && ' 'source $CIJ_ROOT/modules/cijoe.sh && ' 'source %s && ' 'CIJ_TEST_RES_ROOT="%s" %s %s ' % ( trun["conf"]["ENV_FPATH"], script["res_root"], launch, script["fpath"] )
python
{ "resource": "" }
q256533
hooks_setup
validation
def hooks_setup(trun, parent, hnames=None): """ Setup test-hooks @returns dict of hook filepaths {"enter": [], "exit": []} """ hooks = { "enter": [], "exit": [] } if hnames is None: # Nothing to do, just return the struct return hooks for hname in hnames: # Fill out paths for med in HOOK_PATTERNS: for ptn in HOOK_PATTERNS[med]: fpath = os.sep.join([trun["conf"]["HOOKS"], ptn % hname]) if not os.path.exists(fpath):
python
{ "resource": "" }
q256534
trun_to_file
validation
def trun_to_file(trun, fpath=None): """Dump the given trun to file""" if fpath is None: fpath = yml_fpath(trun["conf"]["OUTPUT"]) with open(fpath, 'w') as yml_file:
python
{ "resource": "" }
q256535
trun_emph
validation
def trun_emph(trun): """Print essential info on""" if trun["conf"]["VERBOSE"] > 1: # Print environment variables cij.emph("rnr:CONF {") for cvar in sorted(trun["conf"].keys()): cij.emph(" % 16s: %r" % (cvar, trun["conf"][cvar])) cij.emph("}") if trun["conf"]["VERBOSE"]:
python
{ "resource": "" }
q256536
tcase_setup
validation
def tcase_setup(trun, parent, tcase_fname): """ Create and initialize a testcase """ #pylint: disable=locally-disabled, unused-argument case = copy.deepcopy(TESTCASE) case["fname"] = tcase_fname case["fpath_orig"] = os.sep.join([trun["conf"]["TESTCASES"], case["fname"]]) if not os.path.exists(case["fpath_orig"]): cij.err('rnr:tcase_setup: !case["fpath_orig"]: %r' % case["fpath_orig"]) return None case["name"] = os.path.splitext(case["fname"])[0] case["ident"] = "/".join([parent["ident"], case["fname"]]) case["res_root"] = os.sep.join([parent["res_root"], case["fname"]]) case["aux_root"] = os.sep.join([case["res_root"], "_aux"]) case["log_fpath"] = os.sep.join([case["res_root"], "run.log"])
python
{ "resource": "" }
q256537
tsuite_exit
validation
def tsuite_exit(trun, tsuite): """Triggers when exiting the given testsuite""" if trun["conf"]["VERBOSE"]: cij.emph("rnr:tsuite:exit") rcode = 0 for hook in reversed(tsuite["hooks"]["exit"]): # EXIT-hooks rcode = script_run(trun, hook) if rcode:
python
{ "resource": "" }
q256538
tsuite_enter
validation
def tsuite_enter(trun, tsuite): """Triggers when entering the given testsuite""" if trun["conf"]["VERBOSE"]: cij.emph("rnr:tsuite:enter { name: %r }" % tsuite["name"]) rcode = 0 for hook in tsuite["hooks"]["enter"]: # ENTER-hooks rcode = script_run(trun, hook)
python
{ "resource": "" }
q256539
tsuite_setup
validation
def tsuite_setup(trun, declr, enum): """ Creates and initialized a TESTSUITE struct and site-effects such as creating output directories and forwarding initialization of testcases """ suite = copy.deepcopy(TESTSUITE) # Setup the test-suite suite["name"] = declr.get("name") if suite["name"] is None: cij.err("rnr:tsuite_setup: no testsuite is given") return None suite["alias"] = declr.get("alias") suite["ident"] = "%s_%d" % (suite["name"], enum) suite["res_root"] = os.sep.join([trun["conf"]["OUTPUT"], suite["ident"]]) suite["aux_root"] = os.sep.join([suite["res_root"], "_aux"]) suite["evars"].update(copy.deepcopy(trun["evars"])) suite["evars"].update(copy.deepcopy(declr.get("evars", {}))) # Initialize os.makedirs(suite["res_root"]) os.makedirs(suite["aux_root"]) # Setup testsuite-hooks suite["hooks"] = hooks_setup(trun, suite, declr.get("hooks")) # Forward from declaration suite["hooks_pr_tcase"] = declr.get("hooks_pr_tcase", []) suite["fname"] = "%s.suite" % suite["name"] suite["fpath"] = os.sep.join([trun["conf"]["TESTSUITES"], suite["fname"]]) # # Load testcases from .suite file OR from declaration # tcase_fpaths = [] # Load testcase fpaths if os.path.exists(suite["fpath"]): # From suite-file suite_lines = (
python
{ "resource": "" }
q256540
tcase_enter
validation
def tcase_enter(trun, tsuite, tcase): """ setup res_root and aux_root, log info and run tcase-enter-hooks @returns 0 when all hooks succeed, some value othervise """ #pylint: disable=locally-disabled, unused-argument if trun["conf"]["VERBOSE"]: cij.emph("rnr:tcase:enter") cij.emph("rnr:tcase:enter { fname: %r }" % tcase["fname"]) cij.emph("rnr:tcase:enter { log_fpath: %r }" % tcase["log_fpath"]) rcode
python
{ "resource": "" }
q256541
trun_exit
validation
def trun_exit(trun): """Triggers when exiting the given testrun""" if trun["conf"]["VERBOSE"]: cij.emph("rnr:trun:exit") rcode = 0 for hook in reversed(trun["hooks"]["exit"]): # EXIT-hooks rcode = script_run(trun, hook) if rcode:
python
{ "resource": "" }
q256542
trun_enter
validation
def trun_enter(trun): """Triggers when entering the given testrun""" if trun["conf"]["VERBOSE"]: cij.emph("rnr:trun::enter") trun["stamp"]["begin"] = int(time.time()) # Record start timestamp rcode = 0 for hook in trun["hooks"]["enter"]: # ENTER-hooks rcode =
python
{ "resource": "" }
q256543
trun_setup
validation
def trun_setup(conf): """ Setup the testrunner data-structure, embedding the parsed environment variables and command-line arguments and continues with setup for testplans, testsuites, and testcases """ declr = None try: with open(conf["TESTPLAN_FPATH"]) as declr_fd: declr = yaml.safe_load(declr_fd) except AttributeError as exc: cij.err("rnr: %r" % exc) if not declr: return None trun = copy.deepcopy(TRUN) trun["ver"] = cij.VERSION trun["conf"] = copy.deepcopy(conf) trun["res_root"] = conf["OUTPUT"] trun["aux_root"] = os.sep.join([trun["res_root"], "_aux"]) trun["evars"].update(copy.deepcopy(declr.get("evars", {}))) os.makedirs(trun["aux_root"]) hook_names = declr.get("hooks", []) if "lock" not in hook_names: hook_names = ["lock"] + hook_names if hook_names[0] != "lock":
python
{ "resource": "" }
q256544
main
validation
def main(conf): """CIJ Test Runner main entry point""" fpath = yml_fpath(conf["OUTPUT"]) if os.path.exists(fpath): # YAML exists, we exit, it might be RUNNING! cij.err("main:FAILED { fpath: %r }, exists" % fpath) return 1 trun = trun_setup(conf) # Construct 'trun' from 'conf' if not trun: return 1 trun_to_file(trun) # Persist trun trun_emph(trun) # Print trun before run tr_err = 0 tr_ent_err = trun_enter(trun) for tsuite in (ts for ts in trun["testsuites"] if not tr_ent_err): ts_err = 0 ts_ent_err = tsuite_enter(trun, tsuite) for tcase in (tc for tc in tsuite["testcases"] if not ts_ent_err): tc_err = tcase_enter(trun, tsuite, tcase) if not tc_err: tc_err += script_run(trun, tcase) tc_err += tcase_exit(trun, tsuite, tcase) tcase["status"] = "FAIL" if tc_err else "PASS" trun["progress"][tcase["status"]] += 1 # Update progress trun["progress"]["UNKN"] -= 1 ts_err += tc_err # Accumulate errors
python
{ "resource": "" }
q256545
Nvm.get_chunk_meta
validation
def get_chunk_meta(self, meta_file): """Get chunk meta table""" chunks = self.envs["CHUNKS"] if cij.nvme.get_meta(0, chunks * self.envs["CHUNK_META_SIZEOF"], meta_file): raise RuntimeError("cij.liblight.get_chunk_meta: fail")
python
{ "resource": "" }
q256546
Nvm.get_chunk_meta_item
validation
def get_chunk_meta_item(self, chunk_meta, grp, pug, chk): """Get item of chunk meta table""" num_chk = self.envs["NUM_CHK"] num_pu = self.envs["NUM_PU"]
python
{ "resource": "" }
q256547
Nvm.s20_to_gen
validation
def s20_to_gen(self, pugrp, punit, chunk, sectr): """S20 unit to generic address""" cmd = ["nvm_addr s20_to_gen", self.envs["DEV_PATH"], "%d %d %d %d" % (pugrp, punit, chunk, sectr)] status, stdout, _ = cij.ssh.command(cmd, shell=True) if status:
python
{ "resource": "" }
q256548
Nvm.gen_to_dev
validation
def gen_to_dev(self, address): """Generic address to device address""" cmd = ["nvm_addr gen2dev", self.envs["DEV_PATH"], "0x{:x}".format(address)] status, stdout, _ = cij.ssh.command(cmd, shell=True) if status:
python
{ "resource": "" }
q256549
Job.__run
validation
def __run(self, shell=True, echo=True): """Run DMESG job""" if env(): return 1 cij.emph("cij.dmesg.start: shell: %r, cmd: %r"
python
{ "resource": "" }
q256550
Job.start
validation
def start(self): """Start DMESG job in thread""" self.__thread = Thread(target=self.__run, args=(True, False))
python
{ "resource": "" }
q256551
Job.terminate
validation
def terminate(self): """Terminate DMESG job""" if self.__thread: cmd = ["who am i"] status, output, _ = cij.util.execute(cmd, shell=True, echo=True) if status: cij.warn("cij.dmesg.terminate: who am i failed") return 1 tty = output.split()[1] cmd = ["pkill -f '{}' -t '{}'".format(" ".join(self.__prefix), tty)] status, _, _ = cij.util.execute(cmd,
python
{ "resource": "" }
q256552
generate_rt_pic
validation
def generate_rt_pic(process_data, para_meter, scale): """ generate rater pic""" pic_path = para_meter['filename'] + '.png' plt.figure(figsize=(5.6 * scale, 3.2 * scale)) for key in process_data.keys(): plt.plot(process_data[key][:, 0], process_data[key][:, 1], label=str(key)) plt.title(para_meter['title'])
python
{ "resource": "" }
q256553
generate_steady_rt_pic
validation
def generate_steady_rt_pic(process_data, para_meter, scale, steady_time): """ generate rate steady""" pic_path_steady = para_meter['filename'] + '_steady.png' plt.figure(figsize=(4 * scale, 2.5 * scale)) for key in process_data.keys(): if len(process_data[key]) < steady_time: steady_time = len(process_data[key]) plt.scatter(process_data[key][-1 * steady_time:, 0], process_data[key][-1 * steady_time:, 1], label=str(key), s=10) steady_value = np.mean(process_data[key][-1 * steady_time:, 1]) steady_value_5 = steady_value * (1 + 0.05) steady_value_10 = steady_value * (1 + 0.1) steady_value_ng_5 = steady_value * (1 - 0.05) steady_value_ng_10 = steady_value * (1 - 0.1) plt.plot(process_data[key][-1 * steady_time:, 0], [steady_value] * steady_time, 'b') plt.plot(process_data[key][-1 * steady_time:, 0],
python
{ "resource": "" }
q256554
round_data
validation
def round_data(filter_data): """ round the data""" for index, _ in enumerate(filter_data): filter_data[index][0]
python
{ "resource": "" }
q256555
env
validation
def env(): """Verify PCI variables and construct exported variables""" if cij.ssh.env(): cij.err("cij.pci.env: invalid SSH environment") return 1 pci = cij.env_to_dict(PREFIX, REQUIRED)
python
{ "resource": "" }
q256556
info
validation
def info(txt): """Print, emphasized 'neutral', the given 'txt' message""" print("%s# %s%s%s" % (PR_EMPH_CC,
python
{ "resource": "" }
q256557
good
validation
def good(txt): """Print, emphasized 'good', the given 'txt' message""" print("%s# %s%s%s" % (PR_GOOD_CC,
python
{ "resource": "" }
q256558
warn
validation
def warn(txt): """Print, emphasized 'warning', the given 'txt' message""" print("%s# %s%s%s" % (PR_WARN_CC,
python
{ "resource": "" }
q256559
err
validation
def err(txt): """Print, emphasized 'error', the given 'txt' message""" print("%s# %s%s%s" % (PR_ERR_CC,
python
{ "resource": "" }
q256560
emph
validation
def emph(txt, rval=None): """Print, emphasized based on rval""" if rval is None: # rval is not specified, use 'neutral'
python
{ "resource": "" }
q256561
paths_from_env
validation
def paths_from_env(prefix=None, names=None): """Construct dict of paths from environment variables'""" def expand_path(path): """Expands variables in 'path' and turns it into absolute path""" return os.path.abspath(os.path.expanduser(os.path.expandvars(path))) if prefix is None: prefix = "CIJ" if names is None: names = [ "ROOT", "ENVS", "TESTPLANS", "TESTCASES", "TESTSUITES", "MODULES", "HOOKS", "TEMPLATES" ] conf = {v: os.environ.get("_".join([prefix, v])) for v
python
{ "resource": "" }
q256562
env_export
validation
def env_export(prefix, exported, env): """ Define the list of 'exported' variables with
python
{ "resource": "" }
q256563
exists
validation
def exists(): """Verify that the ENV defined NVMe device exists""" if env(): cij.err("cij.nvm.exists: Invalid NVMe ENV.")
python
{ "resource": "" }
q256564
dev_get_rprt
validation
def dev_get_rprt(dev_name, pugrp=None, punit=None): """ Get-log-page chunk information If the pugrp and punit is set, then provide report only for that pugrp/punit @returns the first chunk in the given state if one exists, None otherwise """ cmd = ["nvm_cmd", "rprt_all", dev_name] if not (pugrp is None and punit is None):
python
{ "resource": "" }
q256565
dev_get_chunk
validation
def dev_get_chunk(dev_name, state, pugrp=None, punit=None): """ Get a chunk-descriptor for the first chunk in the given state. If the pugrp and punit is set, then search only
python
{ "resource": "" }
q256566
pkill
validation
def pkill(): """Kill all of FIO processes""" if env(): return 1 cmd = ["ps -aux | grep fio | grep -v grep"] status, _, _ = cij.ssh.command(cmd, shell=True, echo=False) if not status:
python
{ "resource": "" }
q256567
Job.__parse_parms
validation
def __parse_parms(self): """Translate dict parameters to string""" args = list() for key, val in self.__parm.items(): key = key.replace("FIO_", "").lower() if key == "runtime": args.append("--time_based")
python
{ "resource": "" }
q256568
Job.import_parms
validation
def import_parms(self, args): """Import external dict to internal
python
{ "resource": "" }
q256569
Job.get_parm
validation
def get_parm(self, key): """Get parameter of FIO""" if key in self.__parm.keys():
python
{ "resource": "" }
q256570
Job.start
validation
def start(self): """Run FIO job in thread""" self.__thread = Threads(target=self.run, args=(True, True, False))
python
{ "resource": "" }
q256571
Job.run
validation
def run(self, shell=True, cmdline=False, echo=True): """Run FIO job""" if env(): return 1
python
{ "resource": "" }
q256572
extract_hook_names
validation
def extract_hook_names(ent): """Extract hook names from the given entity""" hnames = [] for hook in ent["hooks"]["enter"] + ent["hooks"]["exit"]: hname = os.path.basename(hook["fpath_orig"]) hname = os.path.splitext(hname)[0] hname = hname.strip() hname = hname.replace("_enter", "")
python
{ "resource": "" }
q256573
tcase_parse_descr
validation
def tcase_parse_descr(tcase): """Parse descriptions from the the given tcase""" descr_short = "SHORT" descr_long = "LONG" try: comment = tcase_comment(tcase) except (IOError, OSError, ValueError) as exc: comment = [] cij.err("tcase_parse_descr: failed: %r, tcase: %r" % (exc, tcase)) comment = [l for l in comment if l.strip()] # Remove empty lines for line_number,
python
{ "resource": "" }
q256574
runlogs_to_html
validation
def runlogs_to_html(run_root): """ Returns content of the given 'fpath' with HTML annotations, currently simply a conversion of ANSI color codes to HTML elements """ if not os.path.isdir(run_root): return "CANNOT_LOCATE_LOGFILES" hook_enter = [] hook_exit = [] tcase = [] for fpath in glob.glob(os.sep.join([run_root, "*.log"])): if "exit" in fpath: hook_exit.append(fpath) continue if "hook" in fpath: hook_enter.append(fpath)
python
{ "resource": "" }
q256575
src_to_html
validation
def src_to_html(fpath): """ Returns content of the given 'fpath' with HTML annotations for syntax highlighting """ if not os.path.exists(fpath):
python
{ "resource": "" }
q256576
postprocess
validation
def postprocess(trun): """Perform postprocessing of the given test run""" plog = [] plog.append(("trun", process_trun(trun))) for tsuite in trun["testsuites"]: plog.append(("tsuite", process_tsuite(tsuite)))
python
{ "resource": "" }
q256577
rehome
validation
def rehome(old, new, struct): """ Replace all absolute paths to "re-home" it """ if old == new: return if isinstance(struct, list): for item in struct: rehome(old, new, item) elif isinstance(struct, dict): for key, val in struct.iteritems(): if isinstance(val, (dict, list)): rehome(old, new, val) elif "conf" in key:
python
{ "resource": "" }
q256578
main
validation
def main(args): """Main entry point""" trun = cij.runner.trun_from_file(args.trun_fpath) rehome(trun["conf"]["OUTPUT"], args.output, trun) postprocess(trun) cij.emph("main: reports are uses tmpl_fpath: %r" % args.tmpl_fpath) cij.emph("main: reports are here args.output: %r" % args.output) html_fpath = os.sep.join([args.output, "%s.html" % args.tmpl_name]) cij.emph("html_fpath: %r" % html_fpath) try: # Create and store HTML report with open(html_fpath, 'w') as
python
{ "resource": "" }
q256579
env
validation
def env(): """Verify SSH variables and construct exported variables""" ssh = cij.env_to_dict(PREFIX, REQUIRED) if "KEY" in ssh: ssh["KEY"] = cij.util.expand_path(ssh["KEY"]) if cij.ENV.get("SSH_PORT") is None: cij.ENV["SSH_PORT"] = "22" cij.warn("cij.ssh.env: SSH_PORT was not set, assigned: %r" % ( cij.ENV.get("SSH_PORT")
python
{ "resource": "" }
q256580
wait
validation
def wait(timeout=300): """Wait util target connected""" if env(): cij.err("cij.ssh.wait: Invalid SSH environment") return 1 timeout_backup = cij.ENV.get("SSH_CMD_TIMEOUT") try: time_start = time.time() cij.ENV["SSH_CMD_TIMEOUT"] = "3" while True: time_current = time.time() if (time_current - time_start) > timeout: cij.err("cij.ssh.wait: Timeout") return 1 status, _, _ = command(["exit"], shell=True,
python
{ "resource": "" }
q256581
assert_that
validation
def assert_that(val, description=''): """Factory method for the assertion builder with value to be tested and optional description.""" global _soft_ctx if _soft_ctx:
python
{ "resource": "" }
q256582
contents_of
validation
def contents_of(f, encoding='utf-8'): """Helper to read the contents of the given file or path into a string with the given encoding. Encoding defaults to 'utf-8', other useful encodings are 'ascii' and 'latin-1'.""" try: contents = f.read() except AttributeError: try: with open(f, 'r') as fp: contents = fp.read() except TypeError: raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__) except OSError: if not isinstance(f, str_types): raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__) raise if sys.version_info[0] == 3 and type(contents) is bytes:
python
{ "resource": "" }
q256583
soft_fail
validation
def soft_fail(msg=''): """Adds error message to soft errors list if within soft assertions context. Either just force test failure with the given message.""" global _soft_ctx if _soft_ctx:
python
{ "resource": "" }
q256584
AssertionBuilder.is_equal_to
validation
def is_equal_to(self, other, **kwargs): """Asserts that val is equal to other.""" if self._check_dict_like(self.val, check_values=False, return_as_bool=True) and \ self._check_dict_like(other, check_values=False, return_as_bool=True): if self._dict_not_equal(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include')): self._dict_err(self.val, other, ignore=kwargs.get('ignore'),
python
{ "resource": "" }
q256585
AssertionBuilder.is_not_equal_to
validation
def is_not_equal_to(self, other): """Asserts that val is not equal to other.""" if self.val == other:
python
{ "resource": "" }
q256586
AssertionBuilder.is_same_as
validation
def is_same_as(self, other): """Asserts that the val is identical to other, via 'is' compare.""" if self.val is not other:
python
{ "resource": "" }
q256587
AssertionBuilder.is_not_same_as
validation
def is_not_same_as(self, other): """Asserts that the val is not identical to other, via 'is' compare.""" if self.val is other:
python
{ "resource": "" }
q256588
AssertionBuilder.is_type_of
validation
def is_type_of(self, some_type): """Asserts that val is of the given type.""" if type(some_type) is not type and\ not issubclass(type(some_type), type): raise TypeError('given arg must be a type') if type(self.val) is not some_type:
python
{ "resource": "" }
q256589
AssertionBuilder.is_instance_of
validation
def is_instance_of(self, some_class): """Asserts that val is an instance of the given class.""" try: if not isinstance(self.val, some_class): if hasattr(self.val, '__name__'): t = self.val.__name__ elif hasattr(self.val, '__class__'): t = self.val.__class__.__name__ else:
python
{ "resource": "" }
q256590
AssertionBuilder.is_length
validation
def is_length(self, length): """Asserts that val is the given length.""" if type(length) is not int: raise TypeError('given arg must be an int') if length < 0: raise ValueError('given arg must be a positive int')
python
{ "resource": "" }
q256591
AssertionBuilder.contains
validation
def contains(self, *items): """Asserts that val contains the given item or items.""" if len(items) == 0: raise ValueError('one or more args must be given') elif len(items) == 1: if items[0] not in self.val: if self._check_dict_like(self.val, return_as_bool=True): self._err('Expected <%s> to contain key <%s>, but did not.' % (self.val, items[0])) else: self._err('Expected <%s> to contain item <%s>, but did not.' % (self.val, items[0])) else: missing = [] for i in items: if i not in self.val: missing.append(i) if missing: if self._check_dict_like(self.val, return_as_bool=True):
python
{ "resource": "" }
q256592
AssertionBuilder.does_not_contain
validation
def does_not_contain(self, *items): """Asserts that val does not contain the given item or items.""" if len(items) == 0: raise ValueError('one or more args must be given') elif len(items) == 1: if items[0] in self.val: self._err('Expected <%s> to not contain item <%s>, but did.' % (self.val, items[0])) else: found = [] for i in items:
python
{ "resource": "" }
q256593
AssertionBuilder.contains_only
validation
def contains_only(self, *items): """Asserts that val contains only the given item or items.""" if len(items) == 0: raise ValueError('one or more args must be given') else: extra = [] for i in self.val: if i not in items: extra.append(i) if extra: self._err('Expected <%s> to contain only %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(extra))) missing = [] for
python
{ "resource": "" }
q256594
AssertionBuilder.contains_sequence
validation
def contains_sequence(self, *items): """Asserts that val contains the given sequence of items in order.""" if len(items) == 0: raise ValueError('one or more args must be given') else: try: for i in xrange(len(self.val) - len(items) + 1):
python
{ "resource": "" }
q256595
AssertionBuilder.contains_duplicates
validation
def contains_duplicates(self): """Asserts that val is iterable and contains duplicate items.""" try: if len(self.val) != len(set(self.val)): return self except TypeError:
python
{ "resource": "" }
q256596
AssertionBuilder.does_not_contain_duplicates
validation
def does_not_contain_duplicates(self): """Asserts that val is iterable and does not contain any duplicate items.""" try: if len(self.val) == len(set(self.val)): return self except TypeError:
python
{ "resource": "" }
q256597
AssertionBuilder.is_empty
validation
def is_empty(self): """Asserts that val is empty.""" if len(self.val) != 0: if isinstance(self.val, str_types): self._err('Expected <%s> to be empty string, but was not.' % self.val)
python
{ "resource": "" }
q256598
AssertionBuilder.is_not_empty
validation
def is_not_empty(self): """Asserts that val is not empty.""" if len(self.val) == 0: if isinstance(self.val, str_types): self._err('Expected
python
{ "resource": "" }
q256599
AssertionBuilder.is_in
validation
def is_in(self, *items): """Asserts that val is equal to one of the given items.""" if len(items) == 0: raise ValueError('one or more args must be
python
{ "resource": "" }