def validate_modules(self):
# Match def p_funcname(
fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
for module in self.modules:
try:
lines, linen = inspect.getsourcelines(module)
except IOError:
continue
counthash = {}
for linen, line in enumerate(lines):
linen += 1
m = fre.match(line)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d',
filename, linen, name, prev)
# Get the start symbol
python类getsourcelines()的实例源码
def validate_modules(self):
# Match def p_funcname(
fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
for module in self.modules:
try:
lines, linen = inspect.getsourcelines(module)
except IOError:
continue
counthash = {}
for linen, line in enumerate(lines):
linen += 1
m = fre.match(line)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d',
filename, linen, name, prev)
# Get the start symbol
def validate_modules(self):
# Match def p_funcname(
fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
for module in self.modules:
try:
lines, linen = inspect.getsourcelines(module)
except IOError:
continue
counthash = {}
for linen, line in enumerate(lines):
linen += 1
m = fre.match(line)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d',
filename, linen, name, prev)
# Get the start symbol
def _get_linepath(item):
_filename = inspect.getfile(item)
_source = open(_filename).readlines()
lineno = _source.index(inspect.getsourcelines(item)[0][0]) + 1
return '{}:{}'.format(_filename, lineno)
def print_infos(solver):
print('Model: \n%s' % solver.model)
print('Solver: \n%s' % solver)
print('Data Augmentation Function: \n')
print(''.join(['\t' + i for i in inspect.getsourcelines(data_augm)[0]]))
print('Custom Weight Decay Update Rule: \n')
print(''.join(['\t' + i for i in inspect.getsourcelines(custom_update_decay)[0]]))
def source(self, command : str = None):
'''
Displays my full source code or for a specific command
To display the source code of a subcommand you have to separate it by
periods, e.g. tag.create for the create subcommand of the tag command
Based on [R. Danny](https://github.com/Rapptz/RoboDanny)'s source command
'''
source_url = "https://github.com/Harmon758/Harmonbot"
if command is None:
await self.bot.embed_reply(source_url)
return
code_path = command.split('.')
obj = self.bot
for cmd in code_path:
try:
obj = obj.get_command(cmd)
if obj is None:
await self.bot.embed_reply("Could not find the command " + cmd)
return
except AttributeError:
await self.bot.embed_reply("{0.name} command has no subcommands".format(obj))
return
# since we found the command we're looking for, presumably anyway, let's
# try to access the code itself
src = obj.callback.__code__
lines, firstlineno = inspect.getsourcelines(src)
## if not obj.callback.__module__.startswith("discord"):
# not a built-in command
location = os.path.relpath(src.co_filename).replace('\\', '/')
## else:
## location = obj.callback.__module__.replace('.', '/') + ".py"
## source_url = "https://github.com/Rapptz/discord.py"
final_url = '<{}/blob/master/Discord/{}#L{}-L{}>'.format(source_url, location, firstlineno, firstlineno + len(lines) - 1)
await self.bot.embed_reply(final_url)
def get_source_code(func):
source_lines = inspect.getsourcelines(func)[0]
source_lines = format(source_lines)
if source_lines[0][0] == '@':
# if the first line is a decorator, remove it
source_lines = source_lines[1:]
source = ''.join(source_lines)
return source
def formatrepr(self):
tblines = []
addline = tblines.append
stack = [self.request._pyfuncitem.obj]
stack.extend(map(lambda x: x.func, self.fixturestack))
msg = self.msg
if msg is not None:
# the last fixture raise an error, let's present
# it at the requesting side
stack = stack[:-1]
for function in stack:
fspath, lineno = getfslineno(function)
try:
lines, _ = inspect.getsourcelines(get_real_func(function))
except (IOError, IndexError, TypeError):
error_msg = "file %s, line %s: source code not available"
addline(error_msg % (fspath, lineno+1))
else:
addline("file %s, line %s" % (fspath, lineno+1))
for i, line in enumerate(lines):
line = line.rstrip()
addline(" " + line)
if line.lstrip().startswith('def'):
break
if msg is None:
fm = self.request._fixturemanager
available = []
parentid = self.request._pyfuncitem.parent.nodeid
for name, fixturedefs in fm._arg2fixturedefs.items():
faclist = list(fm._matchfactories(fixturedefs, parentid))
if faclist and name not in available:
available.append(name)
msg = "fixture %r not found" % (self.argname,)
msg += "\n available fixtures: %s" %(", ".join(sorted(available)),)
msg += "\n use 'pytest --fixtures [testpath]' for help on them."
return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
def makeTestSuite():
import inspect
suite = TestSuite()
suite.addTest( PyparsingTestInit() )
test_case_classes = ParseTestCase.__subclasses__()
# put classes in order as they are listed in the source code
test_case_classes.sort(key=lambda cls: inspect.getsourcelines(cls)[1])
test_case_classes.remove(PyparsingTestInit)
# test_case_classes.remove(ParseASMLTest)
test_case_classes.remove(EnablePackratParsing)
if IRON_PYTHON_ENV:
test_case_classes.remove(OriginalTextForTest)
suite.addTests(T() for T in test_case_classes)
if TEST_USING_PACKRAT:
# retest using packrat parsing (disable those tests that aren't compatible)
suite.addTest( EnablePackratParsing() )
unpackrattables = [ PyparsingTestInit, EnablePackratParsing, RepeaterTest, ]
# add tests to test suite a second time, to run with packrat parsing
# (leaving out those that we know wont work with packrat)
packratTests = [t.__class__() for t in suite._tests
if t.__class__ not in unpackrattables]
suite.addTests( packratTests )
return suite
def __get_source(self, func):
"""Fetches source of the function"""
hashf = hash(func)
if hashf not in self.__sourcesHM:
#get lines of the source and adjust indent
sourcelines = inspect.getsourcelines(func)[0]
#remove indentation from the first line
sourcelines[0] = sourcelines[0].lstrip()
self.__sourcesHM[hashf] = "".join(sourcelines)
return self.__sourcesHM[hashf]
def dump(self, filename, module, functions):
self.output_ = []
self.dump_tests(filename, functions)
for line in inspect.getsourcelines(module)[0]:
line = line.replace('\n', '')
if line.startswith('import '):
self.imports_.add((line.replace('import ', ''),))
if line.startswith('from '):
self.imports_.add(tuple(line.replace('from ', '').replace('import ','').split(' ')))
return '\n'.join(self.format_imports() + self.output_)
def test_generate_lambda_handler(self):
cli._generate_lambda_handler(
{'function': {'module': 'my_module', 'app': 'my_app'}},
output='_slam.yaml')
with open('_slam.yaml') as f:
handler = f.read()
os.remove('_slam.yaml')
self.assertIn('from my_module import my_app', handler)
self.assertIn(''.join(inspect.getsourcelines(
cli._run_lambda_function)[0][1:]), handler)
_test_unittest2_with.py 文件源码
项目:devsecops-example-helloworld
作者: boozallen
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def testAssertWarnsRegexContext(self):
# Same as above, but with assertWarnsRegex as a context manager
def _runtime_warn(msg):
warnings.warn(msg, RuntimeWarning)
_runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
with self.assertWarnsRegex(RuntimeWarning, "o+") as cm:
_runtime_warn("foox")
self.assertIsInstance(cm.warning, RuntimeWarning)
self.assertEqual(cm.warning.args[0], "foox")
self.assertIn("_test_unittest2_with.py", cm.filename)
self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
pass
# Failure when another warning is triggered
with catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
with self.assertWarnsRegex(DeprecationWarning, "o+"):
_runtime_warn("foox")
# Failure when message doesn't match
with self.assertRaises(self.failureException):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
# A little trickier: we ask RuntimeWarnings to be raised, and then
# check for some of them. It is implementation-defined whether
# non-matching RuntimeWarnings are simply re-raised, or produce a
# failureException.
with catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises((RuntimeWarning, self.failureException)):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
def get_line_no(self, obj):
"""Gets the source line number of this object. None if `obj` code cannot be found.
"""
try:
lineno = getsourcelines(obj)[1]
except:
# no code found
lineno = None
return lineno
def get_line_no(self, obj):
"""Gets the source line number of this object. None if `obj` code cannot be found.
"""
try:
lineno = getsourcelines(obj)[1]
except:
# no code found
lineno = None
return lineno
def print_infos(solver):
print('Model: \n%s' % solver.model)
print('Solver: \n%s' % solver)
print('Data Augmentation Function: \n')
print(''.join(['\t' + i for i in inspect.getsourcelines(data_augm)[0]]))
print('Custom Weight Decay Update Rule: \n')
print(''.join(['\t' + i for i in inspect.getsourcelines(custom_update_decay)[0]]))
def class_to_source_link(cls):
module_name = cls.__module__
assert module_name[:6] == 'keras.'
path = module_name.replace('.', '/')
path += '.py'
line = inspect.getsourcelines(cls)[-1]
link = 'https://github.com/fchollet/keras/blob/master/' + path + '#L' + str(line)
return '[[source]](' + link + ')'
def linkcode_resolve(domain, info):
if domain != 'py' or not info['module']:
return None
rtd_version = os.environ.get('READTHEDOCS_VERSION')
if rtd_version == 'latest':
tag = 'master'
else:
tag = 'v{}'.format(__version__)
# Import the object from module path
obj = _import_object_from_name(info['module'], info['fullname'])
# If it's not defined in the internal module, return None.
mod = inspect.getmodule(obj)
if mod is None:
return None
if not (mod.__name__ == 'cupy' or mod.__name__.startswith('cupy.')):
return None
# Get the source file name and line number at which obj is defined.
try:
filename = inspect.getsourcefile(obj)
except TypeError:
# obj is not a module, class, function, ..etc.
return None
# inspect can return None for cython objects
if filename is None:
return None
# Get the source line number
_, linenum = inspect.getsourcelines(obj)
assert isinstance(linenum, six.integer_types)
filename = os.path.realpath(filename)
relpath = _get_source_relative_path(filename)
return 'https://github.com/cupy/cupy/blob/{}/{}#L{}'.format(
tag, relpath, linenum)
def validate_module(self, module):
lines, linen = inspect.getsourcelines(module)
fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(')
sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=')
counthash = {}
linen += 1
for line in lines:
m = fre.match(line)
if not m:
m = sre.match(line)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.error('%s:%d: Rule %s redefined. Previously defined on line %d', filename, linen, name, prev)
self.error = True
linen += 1
# -----------------------------------------------------------------------------
# lex(module)
#
# Build all of the regular expression rules from definitions in the supplied module
# -----------------------------------------------------------------------------