Search is not available for this dataset
text stringlengths 75 104k |
|---|
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:
break
if trun["conf"]["VERBO... |
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 = script_run(tr... |
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:
dec... |
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'... |
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")
chunk_meta = cij.bin.Buffer(types=self.envs["CHUN... |
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"]
index = grp * num_pu * num_chk + pug * num_chk + chk
return chunk_meta[index] |
def is_bad_chunk(self, chunk_meta, grp, pug, chk):
"""Check the chunk is offline or not"""
meta = self.get_chunk_meta_item(chunk_meta, grp, pug, chk)
if meta.CS & 0x8 != 0:
return True
return False |
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:
raise RuntimeE... |
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:
raise RuntimeError("cij.liblight.gen_to_dev: cmd fail")
... |
def vblk_write(self, address, meta=False):
"""nvm_vblk write"""
cmd = list()
if meta:
cmd.append("NVM_CLI_META_MODE=1")
cmd += ["nvm_vblk write", self.envs["DEV_PATH"], "0x%x" % address]
status, _, _ = cij.ssh.command(cmd, shell=True)
return status |
def vector_read(self, address_list, file_name=None):
"""nvm_cmd read"""
address = ["0x{:x}".format(i) for i in address_list]
cmd = ["nvm_cmd read", self.envs["DEV_PATH"], " ".join(address)]
if file_name:
cmd += ["-o {}".format(file_name)]
status, _, _ = cij.ssh.comman... |
def scalar_write(self, address, block_count, data_file, meta_file):
"""nvme write"""
cmd = ["nvme", "write", self.envs["DEV_PATH"], "-s 0x{:x}".format(address),
"-c {}".format(block_count-1), "-d {}".format(data_file), "-M {}".format(meta_file),
"-z 0x{:x}".format(block_cou... |
def __run(self, shell=True, echo=True):
"""Run DMESG job"""
if env():
return 1
cij.emph("cij.dmesg.start: shell: %r, cmd: %r" % (shell, self.__prefix + self.__suffix))
return cij.ssh.command(self.__prefix, shell, echo, self.__suffix) |
def start(self):
"""Start DMESG job in thread"""
self.__thread = Thread(target=self.__run, args=(True, False))
self.__thread.setDaemon(True)
self.__thread.start() |
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 ... |
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... |
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:
s... |
def process_rt_data(source_data, is_bw=False):
""" process data"""
print("source_data length:", len(source_data))
filter_data = {}
for index in range(2):
filter_mask = source_data[:, 2] == index
if np.any(filter_mask):
filter_data[index] = sum_data(round_data(sourc... |
def sum_data(filter_data, is_bw):
""" caculate sum"""
for index in range(len(filter_data) - 1):
if filter_data[index][0] > filter_data[index + 1][0]:
max_index = index + 1
break
else:
max_index = len(filter_data)
print("max_index: ", max_index + 1)
nu... |
def round_data(filter_data):
""" round the data"""
for index, _ in enumerate(filter_data):
filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0
return filter_data |
def import_source(self, sheet, source, delimiter=","):
"""
Function:
Save original data into specific sheet, and try to translate data to float type
Input:
sheet: Must be a non exists sheet
source: File path of source
"""
# check input ... |
def generate_chart(self, properties):
"""
Function:
Generate and save chart to specific sheet.
Input:
sheet: If already exists, new chart will be added below.
Otherwise, it would create a new sheet;
x_axis: Specify x axis;
... |
def gen_config_sheet(self, sheetname, plist):
""" generate configuration"""
worksheet_cfg = self.workbook.add_worksheet(sheetname)
cell_format = self.workbook.add_format({'bold': False, 'font_name': u'等线'})
cell_format_title = self.workbook.add_format({'border': 0, 'align': 'center',... |
def gen_data_sheet(self, datafile, para_meter, scale=1.75, steady_time=300):
"""
datafile, sheetname, x_axis_name, y_axis_name, title,
Function:
Turn realtime bw data into picture, and save into specific sheet
Input:
sheetname: If already exists, new chart w... |
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)
pci["BUS_PATH"] = "/sys/bus/pci"
pci["DEV_PATH"] = os.sep.join([pci["BUS_PATH"], "devices", pci... |
def info(txt):
"""Print, emphasized 'neutral', the given 'txt' message"""
print("%s# %s%s%s" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))
sys.stdout.flush() |
def good(txt):
"""Print, emphasized 'good', the given 'txt' message"""
print("%s# %s%s%s" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))
sys.stdout.flush() |
def warn(txt):
"""Print, emphasized 'warning', the given 'txt' message"""
print("%s# %s%s%s" % (PR_WARN_CC, get_time_stamp(), txt, PR_NC))
sys.stdout.flush() |
def err(txt):
"""Print, emphasized 'error', the given 'txt' message"""
print("%s# %s%s%s" % (PR_ERR_CC, get_time_stamp(), txt, PR_NC))
sys.stdout.flush() |
def emph(txt, rval=None):
"""Print, emphasized based on rval"""
if rval is None: # rval is not specified, use 'neutral'
info(txt)
elif rval == 0: # rval is 0, by convention, this is 'good'
good(txt)
else: # any other value, considered 'bad'
err(txt) |
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:
... |
def env_to_dict(prefix, names):
"""
Construct dict from environment variables named: PREFIX_NAME
@returns dict of names
"""
env = {}
for name in names:
env[name] = ENV.get("_".join([prefix, name]))
if env[name] is None:
return None
return env |
def env_export(prefix, exported, env):
"""
Define the list of 'exported' variables with 'prefix' with values from 'env'
"""
for exp in exported:
ENV["_".join([prefix, exp])] = env[exp] |
def env():
"""Verify NVME variables and construct exported variables"""
if cij.ssh.env():
cij.err("cij.nvm.env: invalid SSH environment")
return 1
nvm = cij.env_to_dict(PREFIX, REQUIRED)
if "nvme" in nvm["DEV_NAME"]:
nvm["DEV_PATH"] = "/dev/%s" % nvm["DEV_NAME"]
else:
... |
def exists():
"""Verify that the ENV defined NVMe device exists"""
if env():
cij.err("cij.nvm.exists: Invalid NVMe ENV.")
return 1
nvm = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)
cmd = ['[[ -b "%s" ]]' % nvm["DEV_PATH"]]
rcode, _, _ = cij.ssh.command(cmd, shell=True, echo=False... |
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 ... |
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 that pugrp/punit
@returns the first chunk in the given state if one exists, None otherwise
"""
rprt = dev_get_rprt(dev... |
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:
status, _, _ = cij.ssh.command(["pkill -f fio"], shell=True)
if status:
return ... |
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")
if val is None:
args... |
def import_parms(self, args):
"""Import external dict to internal dict"""
for key, val in args.items():
self.set_parm(key, val) |
def get_parm(self, key):
"""Get parameter of FIO"""
if key in self.__parm.keys():
return self.__parm[key]
return None |
def start(self):
"""Run FIO job in thread"""
self.__thread = Threads(target=self.run, args=(True, True, False))
self.__thread.setDaemon(True)
self.__thread.start() |
def run(self, shell=True, cmdline=False, echo=True):
"""Run FIO job"""
if env():
return 1
cmd = ["fio"] + self.__parse_parms()
if cmdline:
cij.emph("cij.fio.run: shell: %r, cmd: %r" % (shell, cmd))
return cij.ssh.command(cmd, shell, echo) |
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("_ent... |
def tcase_comment(tcase):
"""
Extract testcase comment section / testcase description
@returns the testcase-comment from the tcase["fpath"] as a list of strings
"""
src = open(tcase["fpath"]).read()
if len(src) < 3:
cij.err("rprtr::tcase_comment: invalid src, tcase: %r" % tcase["name"]... |
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... |
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 = []
fo... |
def src_to_html(fpath):
"""
Returns content of the given 'fpath' with HTML annotations for syntax
highlighting
"""
if not os.path.exists(fpath):
return "COULD-NOT-FIND-TESTCASE-SRC-AT-FPATH:%r" % fpath
# NOTE: Do SYNTAX highlight?
return open(fpath, "r").read() |
def aux_listing(aux_root):
"""Listing"""
listing = []
for root, _, fnames in os.walk(aux_root):
count = len(aux_root.split(os.sep))
prefix = root.split(os.sep)[count:]
for fname in fnames:
listing.append(os.sep.join(prefix + [fname]))
return listing |
def process_tsuite(tsuite):
"""Goes through the tsuite and processes "*.log" """
# scoop of output from all run-logs
tsuite["log_content"] = runlogs_to_html(tsuite["res_root"])
tsuite["aux_list"] = aux_listing(tsuite["aux_root"])
tsuite["hnames"] = extract_hook_names(tsuite)
return True |
def process_tcase(tcase):
"""Goes through the trun and processes "run.log" """
tcase["src_content"] = src_to_html(tcase["fpath"])
tcase["log_content"] = runlogs_to_html(tcase["res_root"])
tcase["aux_list"] = aux_listing(tcase["aux_root"])
tcase["descr_short"], tcase["descr_long"] = tcase_parse_desc... |
def process_trun(trun):
"""Goes through the trun and processes "run.log" """
trun["log_content"] = runlogs_to_html(trun["res_root"])
trun["aux_list"] = aux_listing(trun["aux_root"])
trun["hnames"] = extract_hook_names(trun)
return True |
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)))
for tcase in tsuite["testcases"]:
plog.append(("tcase", process_t... |
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 i... |
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)
... |
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 s... |
def command(cmd, shell=True, echo=True, suffix=None):
"""SSH: Run the given command over SSH as defined in environment"""
if env():
cij.err("cij.ssh.command: Invalid SSH environment")
return 1
prefix = []
if cij.ENV.get("SSH_CMD_TIME") == "1":
prefix.append("/usr/bin/time")
... |
def pull(src, dst, folder=False):
"""SSH: pull data from remote linux"""
if env():
cij.err("cij.ssh.pull: Invalid SSH environment")
return 1
args = []
if cij.ENV.get("SSH_KEY"):
args.append("-i")
args.append(cij.ENV.get("SSH_KEY"))
if cij.ENV.get("SSH_PORT"):
... |
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:
... |
def reboot(timeout=300, extra=""):
"""Reboot target"""
if env():
cij.err("cij.ssh.reboot: Invalid SSH environment")
return 1
timeout_backup = cij.ENV.get("SSH_CMD_TIMEOUT")
try:
time_start = time.time()
status, last_uptime, _ = command(["/usr/bin/uptime -s"], shell=Tru... |
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:
return AssertionBuilder(val, description, 'soft')
return AssertionBuilder(val, description) |
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 ... |
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:
global _soft_err
_soft_err.append('Fail: %s!' % msg if msg else 'Fail!')
return
fail... |
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, ... |
def is_not_equal_to(self, other):
"""Asserts that val is not equal to other."""
if self.val == other:
self._err('Expected <%s> to be not equal to <%s>, but was.' % (self.val, other))
return self |
def is_same_as(self, other):
"""Asserts that the val is identical to other, via 'is' compare."""
if self.val is not other:
self._err('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other))
return self |
def is_not_same_as(self, other):
"""Asserts that the val is not identical to other, via 'is' compare."""
if self.val is other:
self._err('Expected <%s> to be not identical to <%s>, but was.' % (self.val, other))
return self |
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:
if hasattr(self.val, '_... |
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__'):
... |
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')
if len(self.val) != length:
self._err('... |
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... |
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 conta... |
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:
ext... |
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):
... |
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:
raise TypeError('val is not iterable')
self._err('Expected <%s> to contain du... |
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:
raise TypeError('val is not iterable')
self._err('Expecte... |
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)
else:
self._err('Expected <%s> to be empty, but was not.' % self.... |
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 not empty string, but was empty.')
else:
self._err('Expected not empty, but was empty.')
return self |
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 given')
else:
for i in items:
if self.val == i:
return self
self._err('Expected <... |
def is_nan(self):
"""Asserts that val is real number and NaN (not a number)."""
self._validate_number()
self._validate_real()
if not math.isnan(self.val):
self._err('Expected <%s> to be <NaN>, but was not.' % self.val)
return self |
def is_not_nan(self):
"""Asserts that val is real number and not NaN (not a number)."""
self._validate_number()
self._validate_real()
if math.isnan(self.val):
self._err('Expected not <NaN>, but was.')
return self |
def is_inf(self):
"""Asserts that val is real number and Inf (infinity)."""
self._validate_number()
self._validate_real()
if not math.isinf(self.val):
self._err('Expected <%s> to be <Inf>, but was not.' % self.val)
return self |
def is_not_inf(self):
"""Asserts that val is real number and not Inf (infinity)."""
self._validate_number()
self._validate_real()
if math.isinf(self.val):
self._err('Expected not <Inf>, but was.')
return self |
def is_less_than(self, other):
"""Asserts that val is numeric and is less than other."""
self._validate_compareable(other)
if self.val >= other:
if type(self.val) is datetime.datetime:
self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val.strftime('... |
def is_between(self, low, high):
"""Asserts that val is numeric and is between low and high."""
val_type = type(self.val)
self._validate_between_args(val_type, low, high)
if self.val < low or self.val > high:
if val_type is datetime.datetime:
self._err('Expec... |
def is_close_to(self, other, tolerance):
"""Asserts that val is numeric and is close to other within tolerance."""
self._validate_close_to_args(self.val, other, tolerance)
if self.val < (other-tolerance) or self.val > (other+tolerance):
if type(self.val) is datetime.datetime:
... |
def is_equal_to_ignoring_case(self, other):
"""Asserts that val is case-insensitive equal to other."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if not isinstance(other, str_types):
raise TypeError('given arg must be a string')
... |
def contains_ignoring_case(self, *items):
"""Asserts that val is string and contains the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
if isinstance(self.val, str_types):
if len(items) == 1:
if not isinstanc... |
def starts_with(self, prefix):
"""Asserts that val is string or iterable and starts with prefix."""
if prefix is None:
raise TypeError('given prefix arg must not be none')
if isinstance(self.val, str_types):
if not isinstance(prefix, str_types):
raise Type... |
def ends_with(self, suffix):
"""Asserts that val is string or iterable and ends with suffix."""
if suffix is None:
raise TypeError('given suffix arg must not be none')
if isinstance(self.val, str_types):
if not isinstance(suffix, str_types):
raise TypeErro... |
def matches(self, pattern):
"""Asserts that val is string and matches regex pattern."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if not isinstance(pattern, str_types):
raise TypeError('given pattern arg must be a string')
if l... |
def is_alpha(self):
"""Asserts that val is non-empty string and all characters are alphabetic."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if not self.val.isalpha():
... |
def is_digit(self):
"""Asserts that val is non-empty string and all characters are digits."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if not self.val.isdigit():
... |
def is_lower(self):
"""Asserts that val is non-empty string and all characters are lowercase."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if self.val != self.val.lower():... |
def is_upper(self):
"""Asserts that val is non-empty string and all characters are uppercase."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if self.val != self.val.upper():... |
def is_unicode(self):
"""Asserts that val is a unicode string."""
if type(self.val) is not unicode:
self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__))
return self |
def is_subset_of(self, *supersets):
"""Asserts that val is iterable and a subset of the given superset or flattened superset if multiple supersets are given."""
if not isinstance(self.val, Iterable):
raise TypeError('val is not iterable')
if len(supersets) == 0:
raise Val... |
def contains_key(self, *keys):
"""Asserts the val is a dict and contains the given key or keys. Alias for contains()."""
self._check_dict_like(self.val, check_values=False, check_getitem=False)
return self.contains(*keys) |
def does_not_contain_key(self, *keys):
"""Asserts the val is a dict and does not contain the given key or keys. Alias for does_not_contain()."""
self._check_dict_like(self.val, check_values=False, check_getitem=False)
return self.does_not_contain(*keys) |
def contains_value(self, *values):
"""Asserts that val is a dict and contains the given value or values."""
self._check_dict_like(self.val, check_getitem=False)
if len(values) == 0:
raise ValueError('one or more value args must be given')
missing = []
for v in values:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.