id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
144,048 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/ast.py
|
scss.ast.UnaryOp
|
class UnaryOp(Expression):
def __repr__(self):
return '<%s(%s, %s)>' % (self.__class__.__name__, repr(self.op), repr(self.operand))
def __init__(self, op, operand):
self.op = op
self.operand = operand
def evaluate(self, calculator, divide=False):
return self.op(self.operand.evaluate(calculator, divide=True))
|
class UnaryOp(Expression):
def __repr__(self):
pass
def __init__(self, op, operand):
pass
def evaluate(self, calculator, divide=False):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 2 | 3 | 5 | 10 | 2 | 8 | 6 | 4 | 0 | 8 | 6 | 4 | 1 | 2 | 0 | 3 |
144,049 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/ast.py
|
scss.ast.Variable
|
class Variable(Expression):
def __repr__(self):
return '<%s(%s)>' % (self.__class__.__name__, repr(self.name))
def __init__(self, name):
self.name = name
def evaluate(self, calculator, divide=False):
try:
value = calculator.namespace.variable(self.name)
except KeyError:
if calculator.undefined_variables_fatal:
raise SyntaxError("Undefined variable: '%s'." % self.name)
else:
log.error("Undefined variable '%s'", self.name, extra={'stack': True})
return Undefined()
else:
if isinstance(value, six.string_types):
log.warn(
"Expected a Sass type for the value of {0}, "
"but found a string expression: {1!r}"
.format(self.name, value)
)
evald = calculator.evaluate_expression(value)
if evald is not None:
return evald
return value
|
class Variable(Expression):
def __repr__(self):
pass
def __init__(self, name):
pass
def evaluate(self, calculator, divide=False):
pass
| 4 | 0 | 8 | 0 | 8 | 0 | 2 | 0 | 1 | 3 | 1 | 0 | 3 | 1 | 3 | 5 | 27 | 2 | 25 | 7 | 21 | 0 | 20 | 7 | 16 | 5 | 2 | 3 | 7 |
144,050 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/calculator.py
|
scss.calculator.Calculator
|
class Calculator(object):
"""Expression evaluator."""
ast_cache = {}
def __init__(
self, namespace=None,
ignore_parse_errors=False,
undefined_variables_fatal=True,
):
if namespace is None:
self.namespace = Namespace()
else:
self.namespace = namespace
self.ignore_parse_errors = ignore_parse_errors
self.undefined_variables_fatal = undefined_variables_fatal
def _pound_substitute(self, result):
expr = result.group(1)
value = self.evaluate_expression(expr)
if value is None:
return self.apply_vars(expr)
elif value.is_null:
return ""
else:
return dequote(value.render())
def do_glob_math(self, cont):
"""Performs #{}-interpolation. The result is always treated as a fixed
syntactic unit and will not be re-evaluated.
"""
# TODO that's a lie! this should be in the parser for most cases.
if not isinstance(cont, six.string_types):
warn(FutureWarning(
"do_glob_math was passed a non-string {0!r} "
"-- this will no longer be supported in pyScss 2.0"
.format(cont)
))
cont = six.text_type(cont)
if '#{' not in cont:
return cont
cont = _expr_glob_re.sub(self._pound_substitute, cont)
return cont
def apply_vars(self, cont):
# TODO this is very complicated. it should go away once everything
# valid is actually parseable.
if isinstance(cont, six.string_types) and '$' in cont:
try:
# Optimization: the full cont is a variable in the context,
cont = self.namespace.variable(cont)
except KeyError:
# Interpolate variables:
def _av(m):
v = None
n = m.group(2)
try:
v = self.namespace.variable(n)
except KeyError:
if self.undefined_variables_fatal:
raise SyntaxError("Undefined variable: '%s'." % n)
else:
log.error("Undefined variable '%s'", n, extra={'stack': True})
return n
else:
if v:
if not isinstance(v, Value):
raise TypeError(
"Somehow got a variable {0!r} "
"with a non-Sass value: {1!r}"
.format(n, v)
)
v = v.render()
# TODO this used to test for _dequote
if m.group(1):
v = dequote(v)
else:
v = m.group(0)
return v
cont = _interpolate_re.sub(_av, cont)
else:
# Variable succeeded, so we need to render it
cont = cont.render()
# TODO this is surprising and shouldn't be here
cont = self.do_glob_math(cont)
return cont
def calculate(self, expression, divide=False):
result = self.evaluate_expression(expression, divide=divide)
if result is None:
return String.unquoted(self.apply_vars(expression))
return result
# TODO only used by magic-import...?
def interpolate(self, var):
value = self.namespace.variable(var)
if var != value and isinstance(value, six.string_types):
_vi = self.evaluate_expression(value)
if _vi is not None:
value = _vi
return value
def evaluate_expression(self, expr, divide=False):
try:
ast = self.parse_expression(expr)
except SassError as e:
if self.ignore_parse_errors:
return None
raise
try:
return ast.evaluate(self, divide=divide)
except Exception as e:
six.reraise(SassEvaluationError, SassEvaluationError(e, expression=expr), sys.exc_info()[2])
def parse_expression(self, expr, target='goal'):
if isinstance(expr, six.text_type):
# OK
pass
elif isinstance(expr, six.binary_type):
# Dubious
warn(FutureWarning(
"parse_expression was passed binary data {0!r} "
"-- this will no longer be supported in pyScss 2.0"
.format(expr)
))
# Don't guess an encoding; you reap what you sow
expr = six.text_type(expr)
else:
raise TypeError("Expected string, got %r" % (expr,))
key = (target, expr)
if key in self.ast_cache:
return self.ast_cache[key]
try:
parser = SassExpression(SassExpressionScanner(expr))
ast = getattr(parser, target)()
except SyntaxError as e:
raise SassParseError(e, expression=expr, expression_pos=parser._char_pos)
self.ast_cache[key] = ast
return ast
def parse_interpolations(self, string):
"""Parse a string for interpolations, but don't treat anything else as
Sass syntax. Returns an AST node.
"""
# Shortcut: if there are no #s in the string in the first place, it
# must not have any interpolations, right?
if '#' not in string:
return Literal(String.unquoted(string))
return self.parse_expression(string, 'goal_interpolated_literal')
def parse_vars_and_interpolations(self, string):
"""Parse a string for variables and interpolations, but don't treat
anything else as Sass syntax. Returns an AST node.
"""
# Shortcut: if there are no #s or $s in the string in the first place,
# it must not have anything of interest.
if '#' not in string and '$' not in string:
return Literal(String.unquoted(string))
return self.parse_expression(
string, 'goal_interpolated_literal_with_vars')
|
class Calculator(object):
'''Expression evaluator.'''
def __init__(
self, namespace=None,
ignore_parse_errors=False,
undefined_variables_fatal=True,
):
pass
def _pound_substitute(self, result):
pass
def do_glob_math(self, cont):
'''Performs #{}-interpolation. The result is always treated as a fixed
syntactic unit and will not be re-evaluated.
'''
pass
def apply_vars(self, cont):
pass
def _av(m):
pass
def calculate(self, expression, divide=False):
pass
def interpolate(self, var):
pass
def evaluate_expression(self, expr, divide=False):
pass
def parse_expression(self, expr, target='goal'):
pass
def parse_interpolations(self, string):
'''Parse a string for interpolations, but don't treat anything else as
Sass syntax. Returns an AST node.
'''
pass
def parse_vars_and_interpolations(self, string):
'''Parse a string for variables and interpolations, but don't treat
anything else as Sass syntax. Returns an AST node.
'''
pass
| 12 | 4 | 16 | 1 | 13 | 3 | 3 | 0.24 | 1 | 14 | 9 | 0 | 10 | 3 | 10 | 10 | 170 | 21 | 123 | 33 | 107 | 29 | 99 | 27 | 87 | 6 | 1 | 3 | 35 |
144,051 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/compiler.py
|
scss.compiler.Compilation
|
class Compilation(object):
"""A single run of a compiler."""
def __init__(self, compiler):
self.compiler = compiler
self.ignore_parse_errors = compiler.ignore_parse_errors
# TODO this needs a write barrier, so assignment can't overwrite what's
# in the original namespaces
# TODO or maybe the extensions themselves should take care of that, so
# it IS possible to overwrite from within sass, but only per-instance?
self.root_namespace = Namespace.derive_from(*(
ext.namespace for ext in compiler.extensions
if ext.namespace
))
self.sources = []
self.source_index = {}
self.dependency_map = defaultdict(frozenset)
self.rules = []
def should_scope_loop_in_rule(self, rule):
"""Return True iff a looping construct (@each, @for, @while, @if)
should get its own scope, as is standard Sass behavior.
"""
return rule.legacy_compiler_options.get(
'control_scoping', self.compiler.loops_have_own_scopes)
def add_source(self, source):
if source.key in self.source_index:
return self.source_index[source.key]
self.sources.append(source)
self.source_index[source.key] = source
return source
def run(self):
# Any @import will add the source file to self.sources and infect this
# list, so make a quick copy to insulate against that
# TODO maybe @import should just not do that?
for source_file in list(self.sources):
rule = SassRule(
source_file=source_file,
lineno=1,
unparsed_contents=source_file.contents,
namespace=self.root_namespace,
)
self.rules.append(rule)
self.manage_children(rule, scope=None)
self._warn_unused_imports(rule)
# Run through all the rules and apply @extends in a separate pass
self.rules = self.apply_extends(self.rules)
output, total_selectors = self.create_css(self.rules)
if total_selectors > 65534:
log.warning("Maximum number of supported selectors in Internet Explorer (65534) exceeded!")
return output
def parse_selectors(self, raw_selectors):
"""
Parses out the old xCSS "foo extends bar" syntax.
Returns a 2-tuple: a set of selectors, and a set of extended selectors.
"""
# Fix tabs and spaces in selectors
raw_selectors = _spaces_re.sub(' ', raw_selectors)
parts = _xcss_extends_re.split(raw_selectors, 1) # handle old xCSS extends
if len(parts) > 1:
unparsed_selectors, unsplit_parents = parts
# Multiple `extends` are delimited by `&`
unparsed_parents = unsplit_parents.split('&')
else:
unparsed_selectors, = parts
unparsed_parents = ()
selectors = Selector.parse_many(unparsed_selectors)
parents = [Selector.parse_one(parent) for parent in unparsed_parents]
return selectors, parents
def _warn_unused_imports(self, rule):
if not rule.legacy_compiler_options.get(
'warn_unused', self.compiler.warn_unused_imports):
return
for name, file_and_line in rule.namespace.unused_imports():
log.warn("Unused @import: '%s' (%s)", name, file_and_line)
def _make_calculator(self, namespace):
return Calculator(
namespace,
ignore_parse_errors=self.ignore_parse_errors,
undefined_variables_fatal=self.compiler.undefined_variables_fatal,
)
# @print_timing(4)
def manage_children(self, rule, scope):
try:
self._manage_children_impl(rule, scope)
except SassBaseError as e:
e.add_rule(rule)
raise
except Exception as e:
raise SassError(e, rule=rule)
def _manage_children_impl(self, rule, scope):
calculator = self._make_calculator(rule.namespace)
for c_lineno, c_property, c_codestr in locate_blocks(rule.unparsed_contents):
block = UnparsedBlock(rule, c_lineno, c_property, c_codestr)
####################################################################
# At (@) blocks
if block.is_atrule:
# TODO particularly wild idea: allow extensions to handle
# unrecognized blocks, and get the pyscss stuff out of the
# core? even move the core stuff into the core extension?
code = block.directive
code = '_at_' + code.lower().replace(' ', '_')[1:]
try:
method = getattr(self, code)
except AttributeError:
if block.unparsed_contents is None:
rule.properties.append((block.prop, None))
elif scope is None: # needs to have no scope to crawl down the nested rules
self._nest_at_rules(rule, scope, block)
else:
method(calculator, rule, scope, block)
####################################################################
# Properties
elif block.unparsed_contents is None:
self._get_properties(rule, scope, block)
# Nested properties
elif block.is_scope:
if block.header.unscoped_value:
# Possibly deal with default unscoped value
self._get_properties(rule, scope, block)
rule.unparsed_contents = block.unparsed_contents
subscope = (scope or '') + block.header.scope + '-'
self.manage_children(rule, subscope)
####################################################################
# Nested rules
elif scope is None: # needs to have no scope to crawl down the nested rules
self._nest_rules(rule, scope, block)
def _at_warn(self, calculator, rule, scope, block):
"""
Implements @warn
"""
value = calculator.calculate(block.argument)
log.warn(repr(value))
def _at_print(self, calculator, rule, scope, block):
"""
Implements @print
"""
value = calculator.calculate(block.argument)
sys.stderr.write("%s\n" % value)
def _at_raw(self, calculator, rule, scope, block):
"""
Implements @raw
"""
value = calculator.calculate(block.argument)
sys.stderr.write("%s\n" % repr(value))
def _at_dump_context(self, calculator, rule, scope, block):
"""
Implements @dump_context
"""
sys.stderr.write("%s\n" % repr(rule.namespace._variables))
def _at_dump_functions(self, calculator, rule, scope, block):
"""
Implements @dump_functions
"""
sys.stderr.write("%s\n" % repr(rule.namespace._functions))
def _at_dump_mixins(self, calculator, rule, scope, block):
"""
Implements @dump_mixins
"""
sys.stderr.write("%s\n" % repr(rule.namespace._mixins))
def _at_dump_imports(self, calculator, rule, scope, block):
"""
Implements @dump_imports
"""
sys.stderr.write("%s\n" % repr(rule.namespace._imports))
def _at_dump_options(self, calculator, rule, scope, block):
"""
Implements @dump_options
"""
sys.stderr.write("%s\n" % repr(rule.options))
def _at_debug(self, calculator, rule, scope, block):
"""
Implements @debug
"""
setting = block.argument.strip()
if setting.lower() in ('1', 'true', 't', 'yes', 'y', 'on'):
setting = True
elif setting.lower() in ('0', 'false', 'f', 'no', 'n', 'off', 'undefined'):
setting = False
self.ignore_parse_errors = setting
log.info("Debug mode is %s", 'On' if self.ignore_parse_errors else 'Off')
def _at_pdb(self, calculator, rule, scope, block):
"""
Implements @pdb
"""
try:
import ipdb as pdb
except ImportError:
import pdb
pdb.set_trace()
def _at_extend(self, calculator, rule, scope, block):
"""
Implements @extend
"""
from scss.selector import Selector
selectors = calculator.apply_vars(block.argument)
rule.extends_selectors.extend(Selector.parse_many(selectors))
def _at_return(self, calculator, rule, scope, block):
"""
Implements @return
"""
# TODO should assert this only happens within a @function
ret = calculator.calculate(block.argument)
raise SassReturn(ret)
# @print_timing(10)
def _at_option(self, calculator, rule, scope, block):
"""
Implements @option
"""
# TODO This only actually supports "style" (which only really makes
# sense as the first thing in a single input file) or "warn_unused"
# (which only makes sense at file level /at best/). Explore either
# replacing this with a better mechanism or dropping it entirely.
# Note also that all rules share the same underlying legacy option
# dict, so the rules aren't even lexically scoped like you might think,
# and @importing a file can change the compiler! That seems totally
# wrong.
for option in block.argument.split(','):
key, colon, value = option.partition(':')
key = key.strip().lower().replace('-', '_')
value = value.strip().lower()
if value in ('1', 'true', 't', 'yes', 'y', 'on'):
value = True
elif value in ('0', 'false', 'f', 'no', 'n', 'off', 'undefined'):
value = False
elif not colon:
value = True
if key == 'compress':
warn_deprecated(
rule,
"The 'compress' @option is deprecated. "
"Please use 'style' instead."
)
key = 'style'
value = 'compressed' if value else 'legacy'
if key in ('short_colors', 'reverse_colors'):
warn_deprecated(
rule,
"The '{0}' @option no longer has any effect."
.format(key),
)
return
elif key == 'style':
try:
OutputStyle[value]
except KeyError:
raise SassError("No such output style: {0}".format(value))
elif key in ('warn_unused', 'control_scoping'):
# TODO deprecate control_scoping? or add it to compiler?
if not isinstance(value, bool):
raise SassError("The '{0}' @option requires a bool, not {1!r}".format(key, value))
else:
raise SassError("Unknown @option: {0}".format(key))
rule.legacy_compiler_options[key] = value
def _get_funct_def(self, rule, calculator, argument):
funct, lpar, argstr = argument.partition('(')
funct = calculator.do_glob_math(funct)
funct = normalize_var(funct.strip())
argstr = argstr.strip()
# Parse arguments with the argspec rule
if lpar:
if not argstr.endswith(')'):
raise SyntaxError("Expected ')', found end of line for %s (%s)" % (funct, rule.file_and_line))
argstr = argstr[:-1].strip()
else:
# Whoops, no parens at all. That's like calling with no arguments.
argstr = ''
argspec_node = calculator.parse_expression(argstr, target='goal_argspec')
return funct, argspec_node
def _populate_namespace_from_call(self, name, callee_namespace, mixin, args, kwargs):
# Mutation protection
args = list(args)
kwargs = OrderedDict(kwargs)
#m_params = mixin[0]
#m_defaults = mixin[1]
#m_codestr = mixin[2]
pristine_callee_namespace = mixin[3]
callee_argspec = mixin[4]
import_key = mixin[5]
callee_calculator = self._make_calculator(callee_namespace)
# Populate the mixin/function's namespace with its arguments
for var_name, node in callee_argspec.iter_def_argspec():
if args:
# If there are positional arguments left, use the first
value = args.pop(0)
elif var_name in kwargs:
# Try keyword arguments
value = kwargs.pop(var_name)
elif node is not None:
# OK, try the default argument. Using callee_calculator means
# that default values of arguments can refer to earlier
# arguments' values; yes, that is how Sass works.
value = node.evaluate(callee_calculator, divide=True)
else:
# TODO this should raise
value = Undefined()
callee_namespace.set_variable(var_name, value, local_only=True)
if callee_argspec.slurp:
# Slurpy var gets whatever is left
# TODO should preserve the order of extra kwargs
sass_kwargs = []
for key, value in kwargs.items():
sass_kwargs.append((String(key[1:]), value))
callee_namespace.set_variable(
callee_argspec.slurp.name,
Arglist(args, sass_kwargs))
args = []
kwargs = {}
elif callee_argspec.inject:
# Callee namespace gets all the extra kwargs whether declared or
# not
for var_name, value in kwargs.items():
callee_namespace.set_variable(var_name, value, local_only=True)
kwargs = {}
# TODO would be nice to say where the mixin/function came from
if kwargs:
raise NameError("%s has no such argument %s" % (name, kwargs.keys()[0]))
if args:
raise NameError("%s received extra arguments: %r" % (name, args))
pristine_callee_namespace.use_import(import_key)
return callee_namespace
# @print_timing(10)
def _at_function(self, calculator, rule, scope, block):
"""
Implements @mixin and @function
"""
if not block.argument:
raise SyntaxError("%s requires a function name (%s)" % (block.directive, rule.file_and_line))
funct, argspec_node = self._get_funct_def(rule, calculator, block.argument)
defaults = {}
new_params = []
for var_name, default in argspec_node.iter_def_argspec():
new_params.append(var_name)
if default is not None:
defaults[var_name] = default
# TODO a function or mixin is re-parsed every time it's called; there's
# no AST for anything but expressions :(
mixin = [rule.source_file, block.lineno, block.unparsed_contents, rule.namespace, argspec_node, rule.source_file]
if block.directive == '@function':
def _call(mixin):
def __call(namespace, *args, **kwargs):
source_file = mixin[0]
lineno = mixin[1]
m_codestr = mixin[2]
pristine_callee_namespace = mixin[3]
callee_namespace = pristine_callee_namespace.derive()
# TODO CallOp converts Sass names to Python names, so we
# have to convert them back to Sass names. would be nice
# to avoid this back-and-forth somehow
kwargs = OrderedDict(
(normalize_var('$' + key), value)
for (key, value) in kwargs.items())
self._populate_namespace_from_call(
"Function {0}".format(funct),
callee_namespace, mixin, args, kwargs)
_rule = SassRule(
source_file=source_file,
lineno=lineno,
unparsed_contents=m_codestr,
namespace=callee_namespace,
# rule
import_key=rule.import_key,
legacy_compiler_options=rule.legacy_compiler_options,
options=rule.options,
properties=rule.properties,
extends_selectors=rule.extends_selectors,
ancestry=rule.ancestry,
nested=rule.nested,
)
# TODO supposed to throw an error if there's a slurpy arg
# but keywords() is never called on it
try:
self.manage_children(_rule, scope)
except SassReturn as e:
return e.retval
else:
return Null()
__call._pyscss_needs_namespace = True
return __call
_mixin = _call(mixin)
_mixin.mixin = mixin
mixin = _mixin
if block.directive == '@mixin':
add = rule.namespace.set_mixin
elif block.directive == '@function':
add = rule.namespace.set_function
# Register the mixin for every possible arity it takes
if argspec_node.slurp or argspec_node.inject:
add(funct, None, mixin)
else:
while len(new_params):
add(funct, len(new_params), mixin)
param = new_params.pop()
if param not in defaults:
break
if not new_params:
add(funct, 0, mixin)
_at_mixin = _at_function
# @print_timing(10)
def _at_include(self, calculator, rule, scope, block):
"""
Implements @include, for @mixins
"""
caller_namespace = rule.namespace
caller_calculator = self._make_calculator(caller_namespace)
funct, caller_argspec = self._get_funct_def(rule, caller_calculator, block.argument)
# Render the passed arguments, using the caller's namespace
args, kwargs = caller_argspec.evaluate_call_args(caller_calculator)
argc = len(args) + len(kwargs)
try:
mixin = caller_namespace.mixin(funct, argc)
except KeyError:
try:
# TODO maybe? don't do this, once '...' works
# Fallback to single parameter:
mixin = caller_namespace.mixin(funct, 1)
except KeyError:
log.error("Mixin not found: %s:%d (%s)", funct, argc, rule.file_and_line, extra={'stack': True})
return
else:
args = [List(args, use_comma=True)]
# TODO what happens to kwargs?
source_file = mixin[0]
lineno = mixin[1]
m_codestr = mixin[2]
pristine_callee_namespace = mixin[3]
callee_argspec = mixin[4]
if caller_argspec.inject and callee_argspec.inject:
# DEVIATION: Pass the ENTIRE local namespace to the mixin (yikes)
callee_namespace = Namespace.derive_from(
caller_namespace,
pristine_callee_namespace)
else:
callee_namespace = pristine_callee_namespace.derive()
self._populate_namespace_from_call(
"Mixin {0}".format(funct),
callee_namespace, mixin, args, kwargs)
_rule = SassRule(
# These must be file and line in which the @include occurs
source_file=rule.source_file,
lineno=rule.lineno,
# These must be file and line in which the @mixin was defined
from_source_file=source_file,
from_lineno=lineno,
unparsed_contents=m_codestr,
namespace=callee_namespace,
# rule
import_key=rule.import_key,
legacy_compiler_options=rule.legacy_compiler_options,
options=rule.options,
properties=rule.properties,
extends_selectors=rule.extends_selectors,
ancestry=rule.ancestry,
nested=rule.nested,
)
_rule.options['@content'] = block.unparsed_contents
self.manage_children(_rule, scope)
# @print_timing(10)
def _at_content(self, calculator, rule, scope, block):
"""
Implements @content
"""
if '@content' not in rule.options:
log.error("Content string not found for @content (%s)", rule.file_and_line)
rule.unparsed_contents = rule.options.pop('@content', '')
self.manage_children(rule, scope)
# @print_timing(10)
def _at_import(self, calculator, rule, scope, block):
"""
Implements @import
Load and import mixins and functions and rules
"""
# TODO it would be neat to opt into warning that you're using
# values/functions from a file you didn't explicitly import
# TODO base-level directives, like @mixin or @charset, aren't allowed
# to be @imported into a nested block
# TODO i'm not sure we disallow them nested in the first place
# TODO @import is disallowed within mixins, control directives
# TODO @import doesn't take a block -- that's probably an issue with a
# lot of our directives
# TODO if there's any #{}-interpolation in the AST, this should become
# a CSS import (though in practice Ruby only even evaluates it in url()
# -- in a string it's literal!)
sass_paths = calculator.evaluate_expression(block.argument)
css_imports = []
for sass_path in sass_paths:
# These are the rules for when an @import is interpreted as a CSS
# import:
if (
# If it's a url()
isinstance(sass_path, Url) or
# If it's not a string (including `"foo" screen`, a List)
not isinstance(sass_path, String) or
# If the filename begins with an http protocol
sass_path.value.startswith(('http://', 'https://')) or
# If the filename ends with .css
sass_path.value.endswith(self.compiler.static_extensions)):
css_imports.append(sass_path.render(compress=False))
continue
# Should be left with a plain String
name = sass_path.value
source = None
for extension in self.compiler.extensions:
source = extension.handle_import(name, self, rule)
if source:
break
else:
# Didn't find anything!
raise SassImportError(name, self.compiler, rule=rule)
source = self.add_source(source)
if rule.namespace.has_import(source):
# If already imported in this scope, skip
# TODO this might not be right -- consider if you @import a
# file at top level, then @import it inside a selector block!
continue
_rule = SassRule(
source_file=source,
lineno=block.lineno,
unparsed_contents=source.contents,
# rule
legacy_compiler_options=rule.legacy_compiler_options,
options=rule.options,
properties=rule.properties,
extends_selectors=rule.extends_selectors,
ancestry=rule.ancestry,
namespace=rule.namespace,
)
rule.namespace.add_import(source, rule)
self.manage_children(_rule, scope)
# Create a new @import rule for each import determined to be CSS
for import_ in css_imports:
# TODO this seems extremely janky (surely we should create an
# actual new Rule), but the CSS rendering doesn't understand how to
# print rules without blocks
# TODO if this ever creates a new Rule, shuffle stuff around so
# this is still hoisted to the top
rule.properties.append(('@import ' + import_, None))
# @print_timing(10)
def _at_if(self, calculator, rule, scope, block):
"""
Implements @if and @else if
"""
# "@if" indicates whether any kind of `if` since the last `@else` has
# succeeded, in which case `@else if` should be skipped
if block.directive != '@if':
if '@if' not in rule.options:
raise SyntaxError("@else with no @if (%s)" % (rule.file_and_line,))
if rule.options['@if']:
# Last @if succeeded; stop here
return
condition = calculator.calculate(block.argument)
if condition:
inner_rule = rule.copy()
inner_rule.unparsed_contents = block.unparsed_contents
if not self.should_scope_loop_in_rule(inner_rule):
# DEVIATION: Allow not creating a new namespace
inner_rule.namespace = rule.namespace
self.manage_children(inner_rule, scope)
rule.options['@if'] = condition
_at_else_if = _at_if
# @print_timing(10)
def _at_else(self, calculator, rule, scope, block):
"""
Implements @else
"""
if '@if' not in rule.options:
log.error("@else with no @if (%s)", rule.file_and_line)
val = rule.options.pop('@if', True)
if not val:
inner_rule = rule.copy()
inner_rule.unparsed_contents = block.unparsed_contents
inner_rule.namespace = rule.namespace # DEVIATION: Commenting this line gives the Sass bahavior
inner_rule.unparsed_contents = block.unparsed_contents
self.manage_children(inner_rule, scope)
# @print_timing(10)
def _at_for(self, calculator, rule, scope, block):
"""
Implements @for
"""
var, _, name = block.argument.partition(' from ')
frm, _, through = name.partition(' through ')
if through:
inclusive = True
else:
inclusive = False
frm, _, through = frm.partition(' to ')
frm = calculator.calculate(frm)
through = calculator.calculate(through)
try:
frm = int(float(frm))
through = int(float(through))
except ValueError:
return
if frm > through:
# DEVIATION: allow reversed '@for .. from .. through' (same as enumerate() and range())
frm, through = through, frm
rev = reversed
else:
rev = lambda x: x
var = var.strip()
var = calculator.do_glob_math(var)
var = normalize_var(var)
inner_rule = rule.copy()
inner_rule.unparsed_contents = block.unparsed_contents
if not self.should_scope_loop_in_rule(inner_rule):
# DEVIATION: Allow not creating a new namespace
inner_rule.namespace = rule.namespace
if inclusive:
through += 1
for i in rev(range(frm, through)):
inner_rule.namespace.set_variable(var, Number(i))
self.manage_children(inner_rule, scope)
# @print_timing(10)
def _at_each(self, calculator, rule, scope, block):
"""
Implements @each
"""
varstring, _, valuestring = block.argument.partition(' in ')
values = calculator.calculate(valuestring)
if not values:
return
varlist = [
normalize_var(calculator.do_glob_math(var.strip()))
# TODO use list parsing here
for var in varstring.split(",")
]
# `@each $foo, in $bar` unpacks, but `@each $foo in $bar` does not!
unpack = len(varlist) > 1
if not varlist[-1]:
varlist.pop()
inner_rule = rule.copy()
inner_rule.unparsed_contents = block.unparsed_contents
if not self.should_scope_loop_in_rule(inner_rule):
# DEVIATION: Allow not creating a new namespace
inner_rule.namespace = rule.namespace
for v in List.from_maybe(values):
if unpack:
v = List.from_maybe(v)
for i, var in enumerate(varlist):
if i >= len(v):
value = Null()
else:
value = v[i]
inner_rule.namespace.set_variable(var, value)
else:
inner_rule.namespace.set_variable(varlist[0], v)
self.manage_children(inner_rule, scope)
# @print_timing(10)
def _at_while(self, calculator, rule, scope, block):
"""
Implements @while
"""
first_condition = condition = calculator.calculate(block.argument)
while condition:
inner_rule = rule.copy()
inner_rule.unparsed_contents = block.unparsed_contents
if not self.should_scope_loop_in_rule(inner_rule):
# DEVIATION: Allow not creating a new namespace
inner_rule.namespace = rule.namespace
self.manage_children(inner_rule, scope)
condition = calculator.calculate(block.argument)
rule.options['@if'] = first_condition
# @print_timing(10)
def _at_variables(self, calculator, rule, scope, block):
"""
Implements @variables and @vars
"""
warn_deprecated(
rule,
"@variables and @vars are deprecated. "
"Just assign variables at top-level.")
_rule = rule.copy()
_rule.unparsed_contents = block.unparsed_contents
_rule.namespace = rule.namespace
_rule.properties = []
self.manage_children(_rule, scope)
_at_vars = _at_variables
# @print_timing(10)
def _get_properties(self, rule, scope, block):
"""
Implements properties and variables extraction and assignment
"""
prop, raw_value = (_prop_split_re.split(block.prop, 1) + [None])[:2]
if raw_value is not None:
raw_value = raw_value.strip()
try:
is_var = (block.prop[len(prop)] == '=')
except IndexError:
is_var = False
if is_var:
warn_deprecated(rule, "Assignment with = is deprecated; use : instead.")
calculator = self._make_calculator(rule.namespace)
prop = prop.strip()
prop = calculator.do_glob_math(prop)
if not prop:
return
_prop = (scope or '') + prop
if is_var or prop.startswith('$') and raw_value is not None:
# Pop off any flags: !default, !global
is_default = False
is_global = True # eventually sass will default this to false
while True:
splits = raw_value.rsplit(None, 1)
if len(splits) < 2 or not splits[1].startswith('!'):
break
raw_value, flag = splits
if flag == '!default':
is_default = True
elif flag == '!global':
is_global = True
else:
raise ValueError("Unrecognized flag: {0}".format(flag))
# Variable assignment
_prop = normalize_var(_prop)
try:
existing_value = rule.namespace.variable(_prop)
except KeyError:
existing_value = None
is_defined = existing_value is not None and not existing_value.is_null
if is_default and is_defined:
pass
else:
if is_defined and prop.startswith('$') and prop[1].isupper():
log.warn("Constant %r redefined", prop)
# Variable assignment is an expression, so it always performs
# real division
value = calculator.calculate(raw_value, divide=True)
rule.namespace.set_variable(
_prop, value, local_only=not is_global)
else:
# Regular property destined for output
_prop = calculator.apply_vars(_prop)
if raw_value is None:
value = None
else:
value = calculator.calculate(raw_value)
if value is None:
pass
elif isinstance(value, six.string_types):
# TODO kill this branch
pass
else:
if value.is_null:
return
style = rule.legacy_compiler_options.get(
'style', self.compiler.output_style)
compress = style == 'compressed'
value = value.render(compress=compress)
rule.properties.append((_prop, value))
# @print_timing(10)
def _nest_at_rules(self, rule, scope, block):
"""
Implements @-blocks
"""
# TODO handle @charset, probably?
# Interpolate the current block
# TODO this seems like it should be done in the block header. and more
# generally?
calculator = self._make_calculator(rule.namespace)
if block.header.argument:
# TODO is this correct? do ALL at-rules ALWAYS allow both vars and
# interpolation?
node = calculator.parse_vars_and_interpolations(
block.header.argument)
block.header.argument = node.evaluate(calculator).render()
# TODO merge into RuleAncestry
new_ancestry = list(rule.ancestry.headers)
if block.directive == '@media' and new_ancestry:
for i, header in reversed(list(enumerate(new_ancestry))):
if header.is_selector:
continue
elif header.directive == '@media':
new_ancestry[i] = BlockAtRuleHeader(
'@media',
"%s and %s" % (header.argument, block.argument))
break
else:
new_ancestry.insert(i, block.header)
else:
new_ancestry.insert(0, block.header)
else:
new_ancestry.append(block.header)
rule.descendants += 1
new_rule = SassRule(
source_file=rule.source_file,
import_key=rule.import_key,
lineno=block.lineno,
num_header_lines=block.header.num_lines,
unparsed_contents=block.unparsed_contents,
legacy_compiler_options=rule.legacy_compiler_options,
options=rule.options.copy(),
#properties
#extends_selectors
ancestry=RuleAncestry(new_ancestry),
namespace=rule.namespace.derive(),
nested=rule.nested + 1,
)
self.rules.append(new_rule)
rule.namespace.use_import(rule.source_file)
self.manage_children(new_rule, scope)
self._warn_unused_imports(new_rule)
# @print_timing(10)
def _nest_rules(self, rule, scope, block):
"""
Implements Nested CSS rules
"""
calculator = self._make_calculator(rule.namespace)
raw_selectors = calculator.do_glob_math(block.prop)
# DEVIATION: ruby sass doesn't support bare variables in selectors
raw_selectors = calculator.apply_vars(raw_selectors)
c_selectors, c_parents = self.parse_selectors(raw_selectors)
if c_parents:
warn_deprecated(
rule,
"The XCSS 'a extends b' syntax is deprecated. "
"Use 'a { @extend b; }' instead."
)
new_ancestry = rule.ancestry.with_nested_selectors(c_selectors)
rule.descendants += 1
new_rule = SassRule(
source_file=rule.source_file,
import_key=rule.import_key,
lineno=block.lineno,
num_header_lines=block.header.num_lines,
unparsed_contents=block.unparsed_contents,
legacy_compiler_options=rule.legacy_compiler_options,
options=rule.options.copy(),
#properties
extends_selectors=c_parents,
ancestry=new_ancestry,
namespace=rule.namespace.derive(),
nested=rule.nested + 1,
)
self.rules.append(new_rule)
rule.namespace.use_import(rule.source_file)
self.manage_children(new_rule, scope)
self._warn_unused_imports(new_rule)
# @print_timing(3)
def apply_extends(self, rules):
"""Run through the given rules and translate all the pending @extends
declarations into real selectors on parent rules.
The list is modified in-place and also sorted in dependency order.
"""
# Game plan: for each rule that has an @extend, add its selectors to
# every rule that matches that @extend.
# First, rig a way to find arbitrary selectors quickly. Most selectors
# revolve around elements, classes, and IDs, so parse those out and use
# them as a rough key. Ignore order and duplication for now.
key_to_selectors = defaultdict(set)
selector_to_rules = defaultdict(set)
rule_selector_order = {}
order = 0
for rule in rules:
for selector in rule.selectors:
for key in selector.lookup_key():
key_to_selectors[key].add(selector)
selector_to_rules[selector].add(rule)
rule_selector_order[rule, selector] = order
order += 1
# Now go through all the rules with an @extends and find their parent
# rules.
for rule in rules:
for selector in rule.extends_selectors:
# This is a little dirty. intersection isn't a class method.
# Don't think about it too much.
candidates = set.intersection(*(
key_to_selectors[key] for key in selector.lookup_key()))
extendable_selectors = [
candidate for candidate in candidates
if candidate.is_superset_of(selector)]
if not extendable_selectors:
# TODO implement !optional
warn_deprecated(
rule,
"Can't find any matching rules to extend {0!r} -- this "
"will be fatal in 2.0, unless !optional is specified!"
.format(selector.render()))
continue
# Armed with a set of selectors that this rule can extend, do
# some substitution and modify the appropriate parent rules.
# One tricky bit: it's possible we're extending two selectors
# that both exist in the same parent rule, in which case we
# want to extend in the order the original selectors appear in
# that rule.
known_parents = []
for extendable_selector in extendable_selectors:
parent_rules = selector_to_rules[extendable_selector]
for parent_rule in parent_rules:
if parent_rule is rule:
# Don't extend oneself
continue
known_parents.append(
(parent_rule, extendable_selector))
# This will put our parents back in their original order
known_parents.sort(key=rule_selector_order.__getitem__)
for parent_rule, extendable_selector in known_parents:
more_parent_selectors = []
for rule_selector in rule.selectors:
more_parent_selectors.extend(
extendable_selector.substitute(
selector, rule_selector))
for parent in more_parent_selectors:
# Update indices, in case later rules try to extend
# this one
for key in parent.lookup_key():
key_to_selectors[key].add(parent)
selector_to_rules[parent].add(parent_rule)
rule_selector_order[parent_rule, parent] = order
order += 1
parent_rule.ancestry = (
parent_rule.ancestry.with_more_selectors(
more_parent_selectors))
# Remove placeholder-only rules
return [rule for rule in rules if not rule.is_pure_placeholder]
# @print_timing(3)
def create_css(self, rules):
"""
Generate the final CSS string
"""
style = rules[0].legacy_compiler_options.get(
'style', self.compiler.output_style)
debug_info = self.compiler.generate_source_map
if style == 'legacy':
sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', ' ', False, '', '\n', '\n', '\n', debug_info
elif style == 'compressed':
sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = False, '', '', False, '', '', '', '', False
elif style == 'compact':
sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', '', False, '\n', ' ', '\n', ' ', debug_info
elif style == 'expanded':
sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', ' ', False, '\n', '\n', '\n', '\n', debug_info
else: # if style == 'nested':
sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', ' ', True, '\n', '\n', '\n', ' ', debug_info
return self._create_css(rules, sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg)
def _textwrap(self, txt, width=70):
if not hasattr(self, '_textwrap_wordsep_re'):
self._textwrap_wordsep_re = re.compile(r'(?<=,)\s+')
self._textwrap_strings_re = re.compile(r'''(["'])(?:(?!\1)[^\\]|\\.)*\1''')
# First, remove commas from anything within strings (marking commas as \0):
def _repl(m):
ori = m.group(0)
fin = ori.replace(',', '\0')
if ori != fin:
subs[fin] = ori
return fin
subs = {}
txt = self._textwrap_strings_re.sub(_repl, txt)
# Mark split points for word separators using (marking spaces with \1):
txt = self._textwrap_wordsep_re.sub('\1', txt)
# Replace all the strings back:
for fin, ori in subs.items():
txt = txt.replace(fin, ori)
# Split in chunks:
chunks = txt.split('\1')
# Break in lines of at most long_width width appending chunks:
ln = ''
lines = []
long_width = int(width * 1.2)
for chunk in chunks:
_ln = ln + ' ' if ln else ''
_ln += chunk
if len(ln) >= width or len(_ln) >= long_width:
if ln:
lines.append(ln)
_ln = chunk
ln = _ln
if ln:
lines.append(ln)
return lines
def _create_css(self, rules, sc=True, sp=' ', tb=' ', nst=True, srnl='\n', nl='\n', rnl='\n', lnl='', debug_info=False):
super_selector = self.compiler.super_selector
if super_selector:
super_selector += ' '
skip_selectors = False
prev_ancestry_headers = []
total_selectors = 0
result = ''
dangling_property = False
separate = False
nesting = current_nesting = last_nesting = -1 if nst else 0
nesting_stack = []
for rule in rules:
nested = rule.nested
if nested <= 1:
separate = True
if nst:
last_nesting = current_nesting
current_nesting = nested
delta_nesting = current_nesting - last_nesting
if delta_nesting > 0:
nesting_stack += [nesting] * delta_nesting
elif delta_nesting < 0:
nesting_stack = nesting_stack[:delta_nesting]
nesting = nesting_stack[-1]
if rule.is_empty:
continue
if nst:
nesting += 1
ancestry = rule.ancestry
ancestry_len = len(ancestry)
first_mismatch = 0
for i, (old_header, new_header) in enumerate(zip(prev_ancestry_headers, ancestry.headers)):
if old_header != new_header:
first_mismatch = i
break
# When sc is False, sets of properties are printed without a
# trailing semicolon. If the previous block isn't being closed,
# that trailing semicolon needs adding in to separate the last
# property from the next rule.
if not sc and dangling_property and first_mismatch >= len(prev_ancestry_headers):
result += ';'
# Close blocks and outdent as necessary
for i in range(len(prev_ancestry_headers), first_mismatch, -1):
result += tb * (i - 1) + '}' + rnl
# Open new blocks as necessary
for i in range(first_mismatch, ancestry_len):
header = ancestry.headers[i]
if separate:
if result:
result += srnl
separate = False
if debug_info:
def _print_debug_info(filename, lineno):
if debug_info == 'comments':
result = tb * (i + nesting) + "/* file: %s, line: %s */" % (filename, lineno) + nl
else:
filename = _escape_chars_re.sub(r'\\\1', filename)
result = tb * (i + nesting) + "@media -sass-debug-info{filename{font-family:file\:\/\/%s}line{font-family:\\00003%s}}" % (filename, lineno) + nl
return result
if rule.lineno and rule.source_file:
result += _print_debug_info(rule.source_file.path, rule.lineno)
if rule.from_lineno and rule.from_source_file:
result += _print_debug_info(rule.from_source_file.path, rule.from_lineno)
if header.is_selector:
header_string = header.render(sep=',' + sp, super_selector=super_selector)
if nl:
header_string = (nl + tb * (i + nesting)).join(self._textwrap(header_string))
else:
header_string = header.render()
result += tb * (i + nesting) + header_string + sp + '{' + nl
if header.is_selector:
total_selectors += 1
prev_ancestry_headers = ancestry.headers
dangling_property = False
if not skip_selectors:
result += self._print_properties(rule.properties, sc, sp, tb * (ancestry_len + nesting), nl, lnl)
dangling_property = True
# Close all remaining blocks
for i in reversed(range(len(prev_ancestry_headers))):
result += tb * i + '}' + rnl
# Always end with a newline, even in compressed mode
if not result.endswith('\n'):
result += '\n'
return (result, total_selectors)
def _print_properties(self, properties, sc=True, sp=' ', tb='', nl='\n', lnl=' '):
result = ''
last_prop_index = len(properties) - 1
for i, (name, value) in enumerate(properties):
if value is None:
prop = name
elif value:
if nl:
value = (nl + tb + tb).join(self._textwrap(value))
prop = name + ':' + sp + value
else:
# Empty string means there's supposed to be a value but it
# evaluated to nothing; skip this
# TODO interacts poorly with last_prop_index
continue
if i == last_prop_index:
if sc:
result += tb + prop + ';' + lnl
else:
result += tb + prop + lnl
else:
result += tb + prop + ';' + nl
return result
|
class Compilation(object):
'''A single run of a compiler.'''
def __init__(self, compiler):
pass
def should_scope_loop_in_rule(self, rule):
'''Return True iff a looping construct (@each, @for, @while, @if)
should get its own scope, as is standard Sass behavior.
'''
pass
def add_source(self, source):
pass
def run(self):
pass
def parse_selectors(self, raw_selectors):
'''
Parses out the old xCSS "foo extends bar" syntax.
Returns a 2-tuple: a set of selectors, and a set of extended selectors.
'''
pass
def _warn_unused_imports(self, rule):
pass
def _make_calculator(self, namespace):
pass
def manage_children(self, rule, scope):
pass
def _manage_children_impl(self, rule, scope):
pass
def _at_warn(self, calculator, rule, scope, block):
'''
Implements @warn
'''
pass
def _at_print(self, calculator, rule, scope, block):
'''
Implements @print
'''
pass
def _at_raw(self, calculator, rule, scope, block):
'''
Implements @raw
'''
pass
def _at_dump_context(self, calculator, rule, scope, block):
'''
Implements @dump_context
'''
pass
def _at_dump_functions(self, calculator, rule, scope, block):
'''
Implements @dump_functions
'''
pass
def _at_dump_mixins(self, calculator, rule, scope, block):
'''
Implements @dump_mixins
'''
pass
def _at_dump_imports(self, calculator, rule, scope, block):
'''
Implements @dump_imports
'''
pass
def _at_dump_options(self, calculator, rule, scope, block):
'''
Implements @dump_options
'''
pass
def _at_debug(self, calculator, rule, scope, block):
'''
Implements @debug
'''
pass
def _at_pdb(self, calculator, rule, scope, block):
'''
Implements @pdb
'''
pass
def _at_extend(self, calculator, rule, scope, block):
'''
Implements @extend
'''
pass
def _at_return(self, calculator, rule, scope, block):
'''
Implements @return
'''
pass
def _at_option(self, calculator, rule, scope, block):
'''
Implements @option
'''
pass
def _get_funct_def(self, rule, calculator, argument):
pass
def _populate_namespace_from_call(self, name, callee_namespace, mixin, args, kwargs):
pass
def _at_function(self, calculator, rule, scope, block):
'''
Implements @mixin and @function
'''
pass
def _call(mixin):
pass
def __call(namespace, *args, **kwargs):
pass
def _at_include(self, calculator, rule, scope, block):
'''
Implements @include, for @mixins
'''
pass
def _at_content(self, calculator, rule, scope, block):
'''
Implements @content
'''
pass
def _at_import(self, calculator, rule, scope, block):
'''
Implements @import
Load and import mixins and functions and rules
'''
pass
def _at_if(self, calculator, rule, scope, block):
'''
Implements @if and @else if
'''
pass
def _at_else(self, calculator, rule, scope, block):
'''
Implements @else
'''
pass
def _at_for(self, calculator, rule, scope, block):
'''
Implements @for
'''
pass
def _at_each(self, calculator, rule, scope, block):
'''
Implements @each
'''
pass
def _at_while(self, calculator, rule, scope, block):
'''
Implements @while
'''
pass
def _at_variables(self, calculator, rule, scope, block):
'''
Implements @variables and @vars
'''
pass
def _get_properties(self, rule, scope, block):
'''
Implements properties and variables extraction and assignment
'''
pass
def _nest_at_rules(self, rule, scope, block):
'''
Implements @-blocks
'''
pass
def _nest_rules(self, rule, scope, block):
'''
Implements Nested CSS rules
'''
pass
def apply_extends(self, rules):
'''Run through the given rules and translate all the pending @extends
declarations into real selectors on parent rules.
The list is modified in-place and also sorted in dependency order.
'''
pass
def create_css(self, rules):
'''
Generate the final CSS string
'''
pass
def _textwrap(self, txt, width=70):
pass
def _repl(m):
pass
def _create_css(self, rules, sc=True, sp=' ', tb=' ', nst=True, srnl='\n', nl='\n', rnl='\n', lnl='', debug_info=False):
pass
def _print_debug_info(filename, lineno):
pass
def _print_properties(self, properties, sc=True, sp=' ', tb='', nl='\n', lnl=' '):
pass
| 47 | 31 | 28 | 3 | 19 | 6 | 5 | 0.34 | 1 | 38 | 19 | 0 | 42 | 9 | 42 | 42 | 1,242 | 168 | 804 | 228 | 754 | 276 | 637 | 226 | 587 | 26 | 1 | 5 | 211 |
144,052 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/compiler.py
|
scss.compiler.Compiler
|
class Compiler(object):
"""A Sass compiler. Stores settings and knows how to fire off a
compilation. Main entry point into compiling Sass.
"""
def __init__(
self, root=Path(), search_path=(),
namespace=None, extensions=(CoreExtension,),
import_static_css=False,
output_style='nested', generate_source_map=False,
live_errors=False, warn_unused_imports=False,
ignore_parse_errors=False,
loops_have_own_scopes=True,
undefined_variables_fatal=True,
super_selector='',
):
"""Configure a compiler.
:param root: Directory to treat as the "project root". Search paths
and some custom extensions (e.g. Compass) are relative to this
directory. Defaults to the current directory.
:type root: :class:`pathlib.Path`
:param search_path: List of paths to search for ``@import``s, relative
to ``root``. Absolute and parent paths are allowed here, but
``@import`` will refuse to load files that aren't in one of the
directories here. Defaults to only the root.
:type search_path: list of strings, :class:`pathlib.Path` objects, or
something that implements a similar interface (useful for custom
pseudo filesystems)
"""
# TODO perhaps polite to automatically cast any string paths to Path?
# but have to be careful since the api explicitly allows dummy objects.
if root is None:
self.root = None
else:
self.root = root.resolve()
self.search_path = tuple(
self.normalize_path(path)
for path in search_path
)
self.extensions = []
if namespace is not None:
self.extensions.append(NamespaceAdapterExtension(namespace))
for extension in extensions:
if isinstance(extension, Extension):
self.extensions.append(extension)
elif (isinstance(extension, type) and
issubclass(extension, Extension)):
self.extensions.append(extension())
elif isinstance(extension, Namespace):
self.extensions.append(
NamespaceAdapterExtension(extension))
else:
raise TypeError(
"Expected an Extension or Namespace, got: {0!r}"
.format(extension)
)
if import_static_css:
self.dynamic_extensions = ('.scss', '.sass', '.css')
self.static_extensions = ()
else:
self.dynamic_extensions = ('.scss', '.sass')
self.static_extensions = ('.css',)
self.output_style = output_style
self.generate_source_map = generate_source_map
self.live_errors = live_errors
self.warn_unused_imports = warn_unused_imports
self.ignore_parse_errors = ignore_parse_errors
self.loops_have_own_scopes = loops_have_own_scopes
self.undefined_variables_fatal = undefined_variables_fatal
self.super_selector = super_selector
def normalize_path(self, path):
if isinstance(path, six.string_types):
path = Path(path)
if path.is_absolute():
return path
if self.root is None:
raise IOError("Can't make absolute path when root is None")
return self.root / path
def make_compilation(self):
return Compilation(self)
def call_and_catch_errors(self, f, *args, **kwargs):
"""Call the given function with the given arguments. If it succeeds,
return its return value. If it raises a :class:`scss.errors.SassError`
and `live_errors` is turned on, return CSS containing a traceback and
error message.
"""
try:
return f(*args, **kwargs)
except SassError as e:
if self.live_errors:
# TODO should this setting also capture and display warnings?
return e.to_css()
else:
raise
def compile(self, *filenames):
# TODO this doesn't spit out the compilation itself, so if you want to
# get something out besides just the output, you have to copy this
# method. that sucks.
# TODO i think the right thing is to get all the constructors out of
# SourceFile, since it's really the compiler that knows the import
# paths and should be consulted about this. reconsider all this (but
# preserve it for now, SIGH) once importers are a thing
compilation = self.make_compilation()
for filename in filenames:
# TODO maybe SourceFile should not be exposed to the end user, and
# instead Compilation should have methods for add_string etc. that
# can call normalize_path.
# TODO it's not possible to inject custom files into the
# /compiler/ as persistent across compiles, nor to provide "fake"
# imports. do we want the former? is the latter better suited to
# an extension?
source = SourceFile.from_filename(self.normalize_path(filename))
compilation.add_source(source)
return self.call_and_catch_errors(compilation.run)
def compile_sources(self, *sources):
# TODO this api is not the best please don't use it. this all needs to
# be vastly simplified, still, somehow.
compilation = self.make_compilation()
for source in sources:
compilation.add_source(source)
return self.call_and_catch_errors(compilation.run)
def compile_string(self, string):
source = SourceFile.from_string(string)
compilation = self.make_compilation()
compilation.add_source(source)
return self.call_and_catch_errors(compilation.run)
|
class Compiler(object):
'''A Sass compiler. Stores settings and knows how to fire off a
compilation. Main entry point into compiling Sass.
'''
def __init__(
self, root=Path(), search_path=(),
namespace=None, extensions=(CoreExtension,),
import_static_css=False,
output_style='nested', generate_source_map=False,
live_errors=False, warn_unused_imports=False,
ignore_parse_errors=False,
loops_have_own_scopes=True,
undefined_variables_fatal=True,
super_selector='',
):
'''Configure a compiler.
:param root: Directory to treat as the "project root". Search paths
and some custom extensions (e.g. Compass) are relative to this
directory. Defaults to the current directory.
:type root: :class:`pathlib.Path`
:param search_path: List of paths to search for ``@import``s, relative
to ``root``. Absolute and parent paths are allowed here, but
``@import`` will refuse to load files that aren't in one of the
directories here. Defaults to only the root.
:type search_path: list of strings, :class:`pathlib.Path` objects, or
something that implements a similar interface (useful for custom
pseudo filesystems)
'''
pass
def normalize_path(self, path):
pass
def make_compilation(self):
pass
def call_and_catch_errors(self, f, *args, **kwargs):
'''Call the given function with the given arguments. If it succeeds,
return its return value. If it raises a :class:`scss.errors.SassError`
and `live_errors` is turned on, return CSS containing a traceback and
error message.
'''
pass
def compile(self, *filenames):
pass
def compile_sources(self, *sources):
pass
def compile_string(self, string):
pass
| 8 | 3 | 18 | 1 | 12 | 5 | 3 | 0.47 | 1 | 11 | 7 | 0 | 7 | 13 | 7 | 7 | 136 | 11 | 85 | 40 | 67 | 40 | 61 | 29 | 53 | 8 | 1 | 2 | 21 |
144,053 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/compiler.py
|
scss.compiler.OutputStyle
|
class OutputStyle(Enum):
nested = ()
compact = ()
compressed = ()
expanded = ()
legacy = ()
|
class OutputStyle(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.17 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 7 | 1 | 6 | 6 | 5 | 1 | 6 | 6 | 5 | 0 | 4 | 0 | 0 |
144,054 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/compiler.py
|
scss.compiler.SassDeprecationWarning
|
class SassDeprecationWarning(UserWarning):
# Note: DO NOT inherit from DeprecationWarning; it's turned off by default
# in 2.7 and later!
pass
|
class SassDeprecationWarning(UserWarning):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 4 | 0 | 2 | 1 | 1 | 2 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
144,055 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/compiler.py
|
scss.compiler.SassReturn
|
class SassReturn(SassBaseError):
"""Special control-flow exception used to hop up the stack from a Sass
function's ``@return``.
"""
def __init__(self, retval):
super(SassReturn, self).__init__()
self.retval = retval
def __str__(self):
return "Returning {0!r}".format(self.retval)
|
class SassReturn(SassBaseError):
'''Special control-flow exception used to hop up the stack from a Sass
function's ``@return``.
'''
def __init__(self, retval):
pass
def __str__(self):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.5 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 18 | 10 | 1 | 6 | 4 | 3 | 3 | 6 | 4 | 3 | 1 | 4 | 0 | 2 |
144,056 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/errors.py
|
scss.errors.SassBaseError
|
class SassBaseError(Exception):
"""Base class for all errors caused by Sass code.
Shouldn't be raising this directly; use or create a subclass instead.
"""
def __init__(self, rule=None):
super(SassBaseError, self).__init__()
self.rule_stack = []
if rule is not None:
self.add_rule(rule)
def add_rule(self, rule):
"""Add a new rule to the "stack" of rules -- this is used to track,
e.g., how a file was ultimately imported.
"""
self.rule_stack.append(rule)
def format_file_and_line(self, rule):
return "line {rule.lineno} of {rule.source_file.path}".format(
rule=rule,
)
def format_sass_stack(self):
"""Return a "traceback" of Sass imports."""
if not self.rule_stack:
return ""
ret = ["on ", self.format_file_and_line(self.rule_stack[0]), "\n"]
last_file = self.rule_stack[0].source_file
# TODO this could go away if rules knew their import chains...
# TODO this doesn't mention mixins or function calls. really need to
# track the call stack better. atm we skip other calls in the same
# file because most of them are just nesting, but they might not be!
# TODO the line number is wrong here for @imports, because we don't
# have access to the UnparsedBlock representing the import!
# TODO @content is completely broken; it's basically textual inclusion
for rule in self.rule_stack[1:]:
if rule.source_file is not last_file:
ret.extend((
"imported from ", self.format_file_and_line(rule), "\n"))
last_file = rule.source_file
return "".join(ret)
def format_message(self):
return ""
def __str__(self):
return "{message}\n{sass_stack}".format(
message=self.format_message(),
sass_stack=self.format_sass_stack(),
)
|
class SassBaseError(Exception):
'''Base class for all errors caused by Sass code.
Shouldn't be raising this directly; use or create a subclass instead.
'''
def __init__(self, rule=None):
pass
def add_rule(self, rule):
'''Add a new rule to the "stack" of rules -- this is used to track,
e.g., how a file was ultimately imported.
'''
pass
def format_file_and_line(self, rule):
pass
def format_sass_stack(self):
'''Return a "traceback" of Sass imports.'''
pass
def format_message(self):
pass
def __str__(self):
pass
| 7 | 3 | 7 | 1 | 5 | 2 | 2 | 0.47 | 1 | 1 | 0 | 5 | 6 | 1 | 6 | 16 | 55 | 11 | 30 | 11 | 23 | 14 | 24 | 11 | 17 | 4 | 3 | 2 | 10 |
144,057 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/errors.py
|
scss.errors.SassError
|
class SassError(SassBaseError):
"""Error class that wraps another exception and attempts to bolt on some
useful context.
"""
def __init__(self, exc, expression=None, expression_pos=None, **kwargs):
super(SassError, self).__init__(**kwargs)
self.exc = exc
self.expression = expression
self.expression_pos = expression_pos
_, _, self.original_traceback = sys.exc_info()
def format_prefix(self):
"""Return the general name of the error and the contents of the rule or
property that caused the failure. This is the initial part of the
error message and should be error-specific.
"""
# TODO this contains NULs and line numbers; could be much prettier
if self.rule_stack:
return (
"Error parsing block:\n" +
" " + self.rule_stack[0].unparsed_contents + "\n"
)
else:
return "Unknown error\n"
def format_python_stack(self):
"""Return a traceback of Python frames, from where the error occurred
to where it was first caught and wrapped.
"""
ret = ["Traceback:\n"]
ret.extend(traceback.format_tb(self.original_traceback))
return "".join(ret)
def format_original_error(self):
"""Return the typical "TypeError: blah blah" for the original wrapped
error.
"""
# TODO eventually we'll have sass-specific errors that will want nicer
# "names" in browser display and stderr
return "".join((
type(self.exc).__name__, ": ", six.text_type(self.exc), "\n",
))
def __str__(self):
try:
prefix = self.format_prefix()
sass_stack = self.format_sass_stack()
python_stack = self.format_python_stack()
original_error = self.format_original_error()
# TODO not very well-specified whether these parts should already
# end in newlines, or how many
return prefix + "\n" + sass_stack + python_stack + original_error
except Exception:
# "unprintable error" is not helpful
return six.text_type(self.exc)
def to_css(self):
"""Return a stylesheet that will show the wrapped error at the top of
the browser window.
"""
# TODO should this include the traceback? any security concerns?
prefix = self.format_prefix()
original_error = self.format_original_error()
sass_stack = self.format_sass_stack()
message = prefix + "\n" + sass_stack + original_error
# Super simple escaping: only quotes and newlines are illegal in css
# strings
message = message.replace('\\', '\\\\')
message = message.replace('"', '\\"')
# use the maximum six digits here so it doesn't eat any following
# characters that happen to look like hex
message = message.replace('\n', '\\00000A')
return BROWSER_ERROR_TEMPLATE.format('"' + message + '"')
|
class SassError(SassBaseError):
'''Error class that wraps another exception and attempts to bolt on some
useful context.
'''
def __init__(self, exc, expression=None, expression_pos=None, **kwargs):
pass
def format_prefix(self):
'''Return the general name of the error and the contents of the rule or
property that caused the failure. This is the initial part of the
error message and should be error-specific.
'''
pass
def format_python_stack(self):
'''Return a traceback of Python frames, from where the error occurred
to where it was first caught and wrapped.
'''
pass
def format_original_error(self):
'''Return the typical "TypeError: blah blah" for the original wrapped
error.
'''
pass
def __str__(self):
pass
def to_css(self):
'''Return a stylesheet that will show the wrapped error at the top of
the browser window.
'''
pass
| 7 | 5 | 12 | 1 | 7 | 4 | 1 | 0.66 | 1 | 2 | 0 | 2 | 6 | 4 | 6 | 22 | 79 | 11 | 41 | 20 | 34 | 27 | 35 | 20 | 28 | 2 | 4 | 1 | 8 |
144,058 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/errors.py
|
scss.errors.SassEvaluationError
|
class SassEvaluationError(SassError):
"""Error raised when evaluating a parsed expression fails."""
def format_prefix(self):
# TODO boy this is getting repeated a lot
# TODO would be nice for the AST to have position information
# TODO might be nice to print the AST and indicate where the failure
# was?
decorated_expr, line = add_error_marker(self.expression, self.expression_pos or -1)
return """Error evaluating expression:\n{0}\n""".format(decorated_expr)
|
class SassEvaluationError(SassError):
'''Error raised when evaluating a parsed expression fails.'''
def format_prefix(self):
pass
| 2 | 1 | 7 | 0 | 3 | 4 | 1 | 1.25 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 23 | 10 | 1 | 4 | 3 | 2 | 5 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
144,059 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/ast.py
|
scss.ast.FunctionLiteral
|
class FunctionLiteral(Expression):
"""Wraps an existing AST node in a literal (unevaluated) function call."""
def __init__(self, child, function_name):
self.child = child
self.function_name = function_name
def evaluate(self, calculator, divide=False):
child = self.child.evaluate(calculator, divide)
if isinstance(child, String):
contents = child.value
quotes = child.quotes
else:
# TODO compress
contents = child.render()
quotes = None
# TODO unclear if this is the right place for this logic, or if it
# should go in the Function constructor, or should be passed in
# explicitly by the grammar, or even if Url should go away entirely
if self.function_name == "url":
return Url(contents, quotes=quotes)
else:
return Function(contents, self.function_name, quotes=quotes)
|
class FunctionLiteral(Expression):
'''Wraps an existing AST node in a literal (unevaluated) function call.'''
def __init__(self, child, function_name):
pass
def evaluate(self, calculator, divide=False):
pass
| 3 | 1 | 10 | 1 | 8 | 2 | 2 | 0.31 | 1 | 3 | 3 | 0 | 2 | 2 | 2 | 4 | 23 | 2 | 16 | 8 | 13 | 5 | 14 | 8 | 11 | 3 | 2 | 1 | 4 |
144,060 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/extension/compass/layouts.py
|
scss.extension.compass.layouts.HorizontalSpritesLayout
|
class HorizontalSpritesLayout(SpritesLayout):
def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None, position=None):
super(HorizontalSpritesLayout, self).__init__(blocks, padding, margin, ppadding, pmargin)
self.width = sum(block[0] for block in self.blocks)
self.height = max(block[1] for block in self.blocks)
if position is None:
position = [0.0] * self.num_blocks
elif not isinstance(position, (tuple, list)):
position = [position] * self.num_blocks
self.position = position
def __iter__(self):
cx = 0
for i, block in enumerate(self.blocks):
w, h, width, height, i = block
margin, padding = self.margin[i], self.padding[i]
pmargin, ppadding = self.pmargin[i], self.ppadding[i]
position = self.position[i]
cssw = width + padding[3] + padding[1] + int(round(width * (ppadding[3] + ppadding[1]))) # image width plus padding
cssh = height + padding[0] + padding[2] + int(round(height * (ppadding[0] + ppadding[2]))) # image height plus padding
cssx = cx + margin[3] + int(round(width * pmargin[3])) # anchored at x
cssy = int(round((self.height - cssh) * position)) # centered vertically
x = cssx + padding[3] + int(round(width * ppadding[3])) # image drawn offset to account for padding
y = cssy + padding[0] + int(round(height * ppadding[0])) # image drawn offset to account for padding
yield x, y, width, height, cssx, cssy, cssw, cssh
cx += cssw + margin[3] + margin[1] + int(round(width * (pmargin[3] + pmargin[1])))
|
class HorizontalSpritesLayout(SpritesLayout):
def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None, position=None):
pass
def __iter__(self):
pass
| 3 | 0 | 13 | 1 | 12 | 3 | 3 | 0.24 | 1 | 5 | 0 | 0 | 2 | 3 | 2 | 3 | 28 | 3 | 25 | 18 | 22 | 6 | 24 | 18 | 21 | 3 | 2 | 1 | 5 |
144,061 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/types.py
|
scss.types.Color
|
class Color(Value):
sass_type_name = 'color'
original_literal = None
def __init__(self, tokens):
self.tokens = tokens
self.value = (0, 0, 0, 1)
if tokens is None:
self.value = (0, 0, 0, 1)
elif isinstance(tokens, Color):
self.value = tokens.value
else:
raise TypeError("Can't make Color from %r" % (tokens,))
### Alternate constructors
@classmethod
def from_rgb(cls, red, green, blue, alpha=1.0, original_literal=None):
red = _constrain(red)
green = _constrain(green)
blue = _constrain(blue)
alpha = _constrain(alpha)
self = cls.__new__(cls) # TODO
self.tokens = None
# TODO really should store these things internally as 0-1, but can't
# until stuff stops examining .value directly
self.value = (red * 255.0, green * 255.0, blue * 255.0, alpha)
if original_literal is not None:
self.original_literal = original_literal
return self
@classmethod
def from_hsl(cls, hue, saturation, lightness, alpha=1.0):
hue = _constrain(hue)
saturation = _constrain(saturation)
lightness = _constrain(lightness)
alpha = _constrain(alpha)
r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation)
return cls.from_rgb(r, g, b, alpha)
@classmethod
def from_hex(cls, hex_string, literal=False):
if not hex_string.startswith('#'):
raise ValueError("Expected #abcdef, got %r" % (hex_string,))
if literal:
original_literal = hex_string
else:
original_literal = None
hex_string = hex_string[1:]
# Always include the alpha channel
if len(hex_string) == 3:
hex_string += 'f'
elif len(hex_string) == 6:
hex_string += 'ff'
# Now there should be only two possibilities. Normalize to a list of
# two hex digits
if len(hex_string) == 4:
chunks = [ch * 2 for ch in hex_string]
elif len(hex_string) == 8:
chunks = [
hex_string[0:2], hex_string[2:4], hex_string[4:6], hex_string[6:8]
]
rgba = [int(ch, 16) / 255 for ch in chunks]
return cls.from_rgb(*rgba, original_literal=original_literal)
@classmethod
def from_name(cls, name):
"""Build a Color from a CSS color name."""
self = cls.__new__(cls) # TODO
self.original_literal = name
r, g, b, a = COLOR_NAMES[name]
self.value = r, g, b, a
return self
### Accessors
@property
def rgb(self):
# TODO: deprecate, relies on internals
return tuple(self.value[:3])
@property
def rgba(self):
return (
self.value[0] / 255,
self.value[1] / 255,
self.value[2] / 255,
self.value[3],
)
@property
def hsl(self):
rgba = self.rgba
h, l, s = colorsys.rgb_to_hls(*rgba[:3])
return h, s, l
@property
def alpha(self):
return self.value[3]
@property
def rgba255(self):
return (
int(self.value[0] * 1 + 0.5),
int(self.value[1] * 1 + 0.5),
int(self.value[2] * 1 + 0.5),
int(self.value[3] * 255 + 0.5),
)
def __repr__(self):
return "<{0} {1}>".format(type(self).__name__, self.render())
def __hash__(self):
return hash(self.value)
def __eq__(self, other):
if not isinstance(other, Color):
return Boolean(False)
# Scale channels to 255 and round to integers; this allows only 8-bit
# color, but Ruby sass makes the same assumption, and otherwise it's
# easy to get lots of float errors for HSL colors.
left = tuple(round(n) for n in self.rgba255)
right = tuple(round(n) for n in other.rgba255)
return Boolean(left == right)
def __add__(self, other):
if isinstance(other, (Color, Number)):
return self._operate(other, operator.add)
else:
return super(Color, self).__add__(other)
def __sub__(self, other):
if isinstance(other, (Color, Number)):
return self._operate(other, operator.sub)
else:
return super(Color, self).__sub__(other)
def __mul__(self, other):
if isinstance(other, (Color, Number)):
return self._operate(other, operator.mul)
else:
return super(Color, self).__mul__(other)
def __div__(self, other):
if isinstance(other, (Color, Number)):
return self._operate(other, operator.div)
else:
return super(Color, self).__div__(other)
def _operate(self, other, op):
if isinstance(other, Number):
if not other.is_unitless:
raise ValueError("Expected unitless Number, got %r" % (other,))
other_rgb = (other.value,) * 3
elif isinstance(other, Color):
if self.alpha != other.alpha:
raise ValueError("Alpha channels must match between %r and %r"
% (self, other))
other_rgb = other.rgb
else:
raise TypeError("Expected Color or Number, got %r" % (other,))
new_rgb = [
min(255., max(0., op(left, right)))
# for from_rgb
/ 255.
for (left, right) in zip(self.rgb, other_rgb)
]
return Color.from_rgb(*new_rgb, alpha=self.alpha)
def render(self, compress=False):
"""Return a rendered representation of the color. If `compress` is
true, the shortest possible representation is used; otherwise, named
colors are rendered as names and all others are rendered as hex (or
with the rgba function).
"""
if not compress and self.original_literal:
return self.original_literal
candidates = []
# TODO this assumes CSS resolution is 8-bit per channel, but so does
# Ruby.
r, g, b, a = self.value
r, g, b = int(round(r)), int(round(g)), int(round(b))
# Build a candidate list in order of preference. If `compress` is
# True, the shortest candidate is used; otherwise, the first candidate
# is used.
# Try color name
key = r, g, b, a
if key in COLOR_LOOKUP:
candidates.append(COLOR_LOOKUP[key])
if a == 1:
# Hex is always shorter than function notation
if all(ch % 17 == 0 for ch in (r, g, b)):
candidates.append("#%1x%1x%1x" % (r // 17, g // 17, b // 17))
else:
candidates.append("#%02x%02x%02x" % (r, g, b))
else:
# Can't use hex notation for RGBA
if compress:
sp = ''
else:
sp = ' '
candidates.append("rgba(%d,%s%d,%s%d,%s%.6g)" % (r, sp, g, sp, b, sp, a))
if compress:
return min(candidates, key=len)
else:
return candidates[0]
|
class Color(Value):
def __init__(self, tokens):
pass
@classmethod
def from_rgb(cls, red, green, blue, alpha=1.0, original_literal=None):
pass
@classmethod
def from_hsl(cls, hue, saturation, lightness, alpha=1.0):
pass
@classmethod
def from_hex(cls, hex_string, literal=False):
pass
@classmethod
def from_name(cls, name):
'''Build a Color from a CSS color name.'''
pass
@property
def rgb(self):
pass
@property
def rgba(self):
pass
@property
def hsl(self):
pass
@property
def alpha(self):
pass
@property
def rgba255(self):
pass
def __repr__(self):
pass
def __hash__(self):
pass
def __eq__(self, other):
pass
def __add__(self, other):
pass
def __sub__(self, other):
pass
def __mul__(self, other):
pass
def __div__(self, other):
pass
def _operate(self, other, op):
pass
def render(self, compress=False):
'''Return a rendered representation of the color. If `compress` is
true, the shortest possible representation is used; otherwise, named
colors are rendered as names and all others are rendered as hex (or
with the rgba function).
'''
pass
| 29 | 2 | 10 | 1 | 8 | 2 | 2 | 0.2 | 1 | 9 | 2 | 0 | 15 | 2 | 19 | 44 | 229 | 44 | 159 | 50 | 130 | 32 | 118 | 41 | 98 | 7 | 2 | 2 | 43 |
144,062 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/errors.py
|
scss.errors.SassSyntaxError
|
class SassSyntaxError(SassBaseError):
"""Generic syntax error thrown by the guts of the expression parser;
usually caught and wrapped later on.
"""
def __init__(self, input_string, position, desired_tokens):
super(SassSyntaxError, self).__init__()
self.input_string = input_string
self.position = position
self.desired_tokens = desired_tokens
def __str__(self):
# TODO this doesn't show the rule stack; should inherit from SassError
# instead?
if self.position == 0:
after = "Syntax error"
else:
after = "Syntax error after {0!r}".format(
self.input_string[max(0, self.position - 20):self.position])
found = "Found {0!r}".format(
self.input_string[self.position:self.position + 10])
if not self.desired_tokens:
expected = "but can't figure out what that means"
elif len(self.desired_tokens) == 1:
expected = "but expected {0}".format(
''.join(self.desired_tokens))
else:
expected = "but expected one of {0}".format(
', '.join(sorted(self.desired_tokens)))
return "{after}: {found} {expected}".format(
after=after,
found=found,
expected=expected,
)
|
class SassSyntaxError(SassBaseError):
'''Generic syntax error thrown by the guts of the expression parser;
usually caught and wrapped later on.
'''
def __init__(self, input_string, position, desired_tokens):
pass
def __str__(self):
pass
| 3 | 1 | 16 | 2 | 13 | 1 | 3 | 0.19 | 1 | 1 | 0 | 0 | 2 | 3 | 2 | 18 | 37 | 5 | 27 | 9 | 24 | 5 | 16 | 9 | 13 | 4 | 4 | 1 | 5 |
144,063 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/extension/compass/layouts.py
|
scss.extension.compass.layouts.DiagonalSpritesLayout
|
class DiagonalSpritesLayout(SpritesLayout):
def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None):
super(DiagonalSpritesLayout, self).__init__(blocks, padding, margin, ppadding, pmargin)
self.width = sum(block[0] for block in self.blocks)
self.height = sum(block[1] for block in self.blocks)
def __iter__(self):
cx, cy = 0, 0
for i, block in enumerate(self.blocks):
w, h, width, height, i = block
margin, padding = self.margin[i], self.padding[i]
pmargin, ppadding = self.pmargin[i], self.ppadding[i]
cssw = width + padding[3] + padding[1] + int(round(width * (ppadding[3] + ppadding[1]))) # image width plus padding
cssh = height + padding[0] + padding[2] + int(round(height * (ppadding[0] + ppadding[2]))) # image height plus padding
cssx = cx + margin[3] + int(round(width * pmargin[3])) # anchored at x
cssy = cy + margin[0] + int(round(height * pmargin[0])) # anchored at y
x = cssx + padding[3] + int(round(width * ppadding[3])) # image drawn offset to account for padding
y = cssy + padding[0] + int(round(height * ppadding[0])) # image drawn offset to account for padding
yield x, y, width, height, cssx, cssy, cssw, cssh
cx += cssw + margin[3] + margin[1] + int(round(width * (pmargin[3] + pmargin[1])))
cy += cssh + margin[0] + margin[2] + int(round(height * (pmargin[0] + pmargin[2])))
|
class DiagonalSpritesLayout(SpritesLayout):
def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None):
pass
def __iter__(self):
pass
| 3 | 0 | 10 | 0 | 10 | 3 | 2 | 0.3 | 1 | 3 | 0 | 0 | 2 | 2 | 2 | 3 | 21 | 1 | 20 | 16 | 17 | 6 | 20 | 16 | 17 | 2 | 2 | 1 | 3 |
144,064 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/extension/compass/__init__.py
|
scss.extension.compass.CompassExtension
|
class CompassExtension(Extension):
name = 'compass'
namespace = Namespace()
def handle_import(self, name, compilation, rule):
"""Implementation of Compass's "magic" imports, which generate
spritesheets on the fly, given either a wildcard or the name of a
directory.
"""
from .sprites import sprite_map
# TODO check that the found file is actually under the root
if callable(config.STATIC_ROOT):
files = sorted(config.STATIC_ROOT(name))
else:
glob_path = os.path.join(config.STATIC_ROOT, name)
files = glob.glob(glob_path)
files = sorted((fn[len(config.STATIC_ROOT):], None) for fn in files)
if not files:
return
# Build magic context
calculator = compilation._make_calculator(rule.namespace)
map_name = os.path.normpath(os.path.dirname(name)).replace('\\', '_').replace('/', '_')
kwargs = {}
# TODO this is all kinds of busted. rule.context hasn't existed for
# ages.
def setdefault(var, val):
_var = '$' + map_name + '-' + var
if _var in rule.context:
kwargs[var] = calculator.interpolate(rule.context[_var], rule, self._library)
else:
rule.context[_var] = val
kwargs[var] = calculator.interpolate(val, rule, self._library)
return rule.context[_var]
setdefault('sprite-base-class', String('.' + map_name + '-sprite', quotes=None))
setdefault('sprite-dimensions', Boolean(False))
position = setdefault('position', Number(0, '%'))
spacing = setdefault('spacing', Number(0))
repeat = setdefault('repeat', String('no-repeat', quotes=None))
names = tuple(os.path.splitext(os.path.basename(file))[0] for file, storage in files)
for n in names:
setdefault(n + '-position', position)
setdefault(n + '-spacing', spacing)
setdefault(n + '-repeat', repeat)
rule.context['$' + map_name + '-' + 'sprites'] = sprite_map(name, **kwargs)
generated_code = '''
@import "compass/utilities/sprites/base";
// All sprites should extend this class
// The %(map_name)s-sprite mixin will do so for you.
#{$%(map_name)s-sprite-base-class} {
background: $%(map_name)s-sprites;
}
// Use this to set the dimensions of an element
// based on the size of the original image.
@mixin %(map_name)s-sprite-dimensions($name) {
@include sprite-dimensions($%(map_name)s-sprites, $name);
}
// Move the background position to display the sprite.
@mixin %(map_name)s-sprite-position($name, $offset-x: 0, $offset-y: 0) {
@include sprite-position($%(map_name)s-sprites, $name, $offset-x, $offset-y);
}
// Extends the sprite base class and set the background position for the desired sprite.
// It will also apply the image dimensions if $dimensions is true.
@mixin %(map_name)s-sprite($name, $dimensions: $%(map_name)s-sprite-dimensions, $offset-x: 0, $offset-y: 0) {
@extend #{$%(map_name)s-sprite-base-class};
@include sprite($%(map_name)s-sprites, $name, $dimensions, $offset-x, $offset-y);
}
@mixin %(map_name)s-sprites($sprite-names, $dimensions: $%(map_name)s-sprite-dimensions) {
@include sprites($%(map_name)s-sprites, $sprite-names, $%(map_name)s-sprite-base-class, $dimensions);
}
// Generates a class for each sprited image.
@mixin all-%(map_name)s-sprites($dimensions: $%(map_name)s-sprite-dimensions) {
@include %(map_name)s-sprites(%(sprites)s, $dimensions);
}
''' % {'map_name': map_name, 'sprites': ' '.join(names)}
return SourceFile.from_string(generated_code)
|
class CompassExtension(Extension):
def handle_import(self, name, compilation, rule):
'''Implementation of Compass's "magic" imports, which generate
spritesheets on the fly, given either a wildcard or the name of a
directory.
'''
pass
def setdefault(var, val):
pass
| 3 | 1 | 46 | 6 | 35 | 5 | 3 | 0.15 | 1 | 5 | 4 | 0 | 1 | 0 | 1 | 4 | 87 | 13 | 65 | 18 | 61 | 10 | 35 | 18 | 31 | 4 | 2 | 1 | 6 |
144,065 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/extension/api.py
|
scss.extension.api.Cache
|
class Cache(object):
"""Serves as a local memory cache storage for extensions usage.
"""
_cache = {}
def __init__(self, prefix=None):
self.prefix = prefix
def get(self, key, default=None):
try:
return self.__class__._cache[self.prefix][key]
except KeyError:
if default is _no_default:
raise
return default
def set(self, key, value):
self.__class__._cache.setdefault(self.prefix, {})[key] = value
def clear_cache(self, key=None):
if key:
try:
del self.__class__._cache[self.prefix][key]
except KeyError:
pass
else:
self.__class__._cache.clear()
def __len__(self):
return len(self.__class__._cache.setdefault(self.prefix, {}))
def __iter__(self):
return iter(self.__class__._cache.setdefault(self.prefix, {}))
def __getitem__(self, key):
return self.get(key, _no_default)
def __setitem__(self, key, value):
return self.set(key, value)
def __delitem__(self, key):
self.clear_cache(key)
|
class Cache(object):
'''Serves as a local memory cache storage for extensions usage.
'''
def __init__(self, prefix=None):
pass
def get(self, key, default=None):
pass
def set(self, key, value):
pass
def clear_cache(self, key=None):
pass
def __len__(self):
pass
def __iter__(self):
pass
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
| 10 | 1 | 3 | 0 | 3 | 0 | 1 | 0.06 | 1 | 1 | 0 | 0 | 9 | 1 | 9 | 9 | 42 | 9 | 31 | 12 | 21 | 2 | 30 | 12 | 20 | 3 | 1 | 2 | 13 |
144,066 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/extension/api.py
|
scss.extension.api.Extension
|
class Extension(object):
"""An extension to the Sass compile process. Subclass to add your own
behavior.
Methods are hooks, called by the compiler at certain points. Each
extension is considered in the order it's provided.
"""
# TODO unsure how this could work given that we'd have to load modules for
# it to be available
name = None
"""A unique name for this extension, which will allow it to be referenced
from the command line.
"""
namespace = None
"""An optional :class:`scss.namespace.Namespace` that will be injected into
the compiler.
"""
def __init__(self):
pass
def __repr__(self):
return "<{0}>".format(type(self).__name__)
def handle_import(self, name, compilation, rule):
"""Attempt to resolve an import. Called once for every Sass string
listed in an ``@import`` statement. Imports that Sass dictates should
be converted to plain CSS imports do NOT trigger this hook.
So this::
@import url(foo), "bar", "baz";
would call `handle_import` twice: once with "bar", once with "baz".
Return a :class:`scss.source.SourceFile` if you want to handle the
import, or None if you don't. (This method returns None by default, so
if you don't care about hooking imports, just don't implement it.)
This method is tried on every registered `Extension` in order, until
one of them returns successfully.
A good example is the core Sass import machinery, which is implemented
with this hook; see the source code of the core extension.
"""
pass
|
class Extension(object):
'''An extension to the Sass compile process. Subclass to add your own
behavior.
Methods are hooks, called by the compiler at certain points. Each
extension is considered in the order it's provided.
'''
def __init__(self):
pass
def __repr__(self):
pass
def handle_import(self, name, compilation, rule):
'''Attempt to resolve an import. Called once for every Sass string
listed in an ``@import`` statement. Imports that Sass dictates should
be converted to plain CSS imports do NOT trigger this hook.
So this::
@import url(foo), "bar", "baz";
would call `handle_import` twice: once with "bar", once with "baz".
Return a :class:`scss.source.SourceFile` if you want to handle the
import, or None if you don't. (This method returns None by default, so
if you don't care about hooking imports, just don't implement it.)
This method is tried on every registered `Extension` in order, until
one of them returns successfully.
A good example is the core Sass import machinery, which is implemented
with this hook; see the source code of the core extension.
'''
pass
| 4 | 2 | 8 | 2 | 2 | 5 | 1 | 3 | 1 | 1 | 0 | 6 | 3 | 0 | 3 | 3 | 47 | 11 | 9 | 6 | 5 | 27 | 9 | 6 | 5 | 1 | 1 | 0 | 3 |
144,067 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/extension/bootstrap.py
|
scss.extension.bootstrap.BootstrapExtension
|
class BootstrapExtension(Extension):
name = 'bootstrap'
namespace = Namespace()
|
class BootstrapExtension(Extension):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
144,068 |
Kronuz/pyScss
|
Kronuz_pyScss/scss/extension/api.py
|
scss.extension.api.NamespaceAdapterExtension
|
class NamespaceAdapterExtension(Extension):
"""Trivial wrapper that adapts a bare :class:`scss.namespace.Namespace`
into a full extension.
"""
def __init__(self, namespace):
self.namespace = namespace
|
class NamespaceAdapterExtension(Extension):
'''Trivial wrapper that adapts a bare :class:`scss.namespace.Namespace`
into a full extension.
'''
def __init__(self, namespace):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 4 | 7 | 1 | 3 | 3 | 1 | 3 | 3 | 3 | 1 | 1 | 2 | 0 | 1 |
144,069 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/root_element/callable_element_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.root_element.callable_element_type.CallableElement
|
class CallableElement(root_element.RootElement):
"""
Class used for representing tCallableElement of BPMN 2.0 graph.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(CallableElement, self).__init__()
self.__name = None
def get_name(self):
"""
Getter for 'name' field.
:return:a value of 'name' field.
"""
return self.__name
def set_name(self, value):
"""
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
"""
if value is None:
self.__name = value
elif not isinstance(value, str):
raise TypeError("Name must be set to a String")
else:
self.__name = value
|
class CallableElement(root_element.RootElement):
'''
Class used for representing tCallableElement of BPMN 2.0 graph.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_name(self):
'''
Getter for 'name' field.
:return:a value of 'name' field.
'''
pass
def set_name(self, value):
'''
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 1.15 | 1 | 3 | 0 | 1 | 3 | 1 | 3 | 7 | 31 | 3 | 13 | 5 | 9 | 15 | 11 | 5 | 7 | 3 | 3 | 1 | 5 |
144,070 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/participant_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.participant_type.Participant
|
class Participant(base_element.BaseElement):
"""
Class used for representing tParticipant of BPMN 2.0 graph
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- process_ref: an ID of referenced message element. Must be either None (process_ref is optional according to
BPMN 2.0 XML Schema) or String.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(Participant, self).__init__()
self.__name = None
self.__process_ref = None
def get_name(self):
"""
Getter for 'name' field.
:return:a value of 'name' field.
"""
return self.__name
def set_name(self, value):
"""
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
"""
if value is None:
self.__name = value
elif not isinstance(value, str):
raise TypeError("Name must be set to a String")
else:
self.__name = value
def get_process_ref(self):
"""
Getter for 'process_ref' field.
:return:a value of 'process_ref' field.
"""
return self.__process_ref
def set_process_ref(self, value):
"""
Setter for 'process_ref' field.
:param value - a new value of 'process_ref' field. Must be either None (process_ref is optional according to
BPMN 2.0 XML Schema) or String.
"""
if not isinstance(value, str):
raise TypeError("ProcessRef must be set to a String")
self.__process_ref = value
|
class Participant(base_element.BaseElement):
'''
Class used for representing tParticipant of BPMN 2.0 graph
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- process_ref: an ID of referenced message element. Must be either None (process_ref is optional according to
BPMN 2.0 XML Schema) or String.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_name(self):
'''
Getter for 'name' field.
:return:a value of 'name' field.
'''
pass
def set_name(self, value):
'''
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
'''
pass
def get_process_ref(self):
'''
Getter for 'process_ref' field.
:return:a value of 'process_ref' field.
'''
pass
def set_process_ref(self, value):
'''
Setter for 'process_ref' field.
:param value - a new value of 'process_ref' field. Must be either None (process_ref is optional according to
BPMN 2.0 XML Schema) or String.
'''
pass
| 6 | 6 | 8 | 0 | 4 | 4 | 2 | 1.4 | 1 | 3 | 0 | 0 | 5 | 2 | 5 | 8 | 53 | 5 | 20 | 8 | 14 | 28 | 18 | 8 | 12 | 3 | 2 | 1 | 8 |
144,071 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/message_flow_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.message_flow_type.MessageFlow
|
class MessageFlow(base_element.BaseElement):
"""
Class used for representing tMessageFlow of BPMN 2.0 graph
"""
def __init__(self, source_ref, target_ref):
"""
Default constructor, initializes object fields with new instances.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- source_ref: an ID of source node. Required field. Must be a String type.
- target_ref: an ID of target node. Required field. Must be a String type.
- message_ref: an ID of referenced message element. Must be either None (message_ref is optional according to
BPMN 2.0 XML Schema) or String.
"""
if source_ref is None or not isinstance(source_ref, str):
raise TypeError("SourceRef is required and must be set to a String")
if target_ref is None or not isinstance(source_ref, str):
raise TypeError("TargetRef is required and must be set to a String")
super(MessageFlow, self).__init__()
self.__name = None
self.__source_ref = source_ref
self.__target_ref = target_ref
self.__message_ref = None
def get_name(self):
"""
Getter for 'name' field.
:return:a value of 'name' field.
"""
return self.__name
def set_name(self, value):
"""
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
"""
if value is None:
self.__name = value
elif not isinstance(value, str):
raise TypeError("Name must be set to a String")
else:
self.__name = value
def get_source_ref(self):
"""
Getter for 'source_ref' field.
:return: value of 'source_ref' field.
"""
return self.__source_ref
def set_source_ref(self, value):
"""
Setter for 'source_ref' field.
:param value - a new value of 'source_ref' field. Must be a String type.
"""
if value is None or not isinstance(value, str):
raise TypeError("SourceRef is required and must be set to a String")
else:
self.__source_ref = value
def get_target_ref(self):
"""
Getter for 'target_ref' field.
:return: value of 'target_ref' field.
"""
return self.__target_ref
def set_target_ref(self, value):
"""
Setter for 'target_ref' field.
:param value - a new value of 'target_ref' field. Must be a String type.
"""
if value is None or not isinstance(value, str):
raise TypeError("TargetRef is required and must be set to a String")
else:
self.__target_ref = value
def get_message_ref(self):
"""
Getter for 'message_ref' field.
:return: value of 'message_ref' field.
"""
return self.__message_ref
def set_message_ref(self, value):
"""
Setter for 'message_ref' field.
:param value - a new value of 'message_ref' field. Must be either None (message_ref is optional according to
BPMN 2.0 XML Schema) or String.
"""
if value is None:
self.__message_ref = value
if not isinstance(value, str):
raise TypeError("MessageRef must be set to a String")
else:
self.__message_ref = value
|
class MessageFlow(base_element.BaseElement):
'''
Class used for representing tMessageFlow of BPMN 2.0 graph
'''
def __init__(self, source_ref, target_ref):
'''
Default constructor, initializes object fields with new instances.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- source_ref: an ID of source node. Required field. Must be a String type.
- target_ref: an ID of target node. Required field. Must be a String type.
- message_ref: an ID of referenced message element. Must be either None (message_ref is optional according to
BPMN 2.0 XML Schema) or String.
'''
pass
def get_name(self):
'''
Getter for 'name' field.
:return:a value of 'name' field.
'''
pass
def set_name(self, value):
'''
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
'''
pass
def get_source_ref(self):
'''
Getter for 'source_ref' field.
:return: value of 'source_ref' field.
'''
pass
def set_source_ref(self, value):
'''
Setter for 'source_ref' field.
:param value - a new value of 'source_ref' field. Must be a String type.
'''
pass
def get_target_ref(self):
'''
Getter for 'target_ref' field.
:return: value of 'target_ref' field.
'''
pass
def set_target_ref(self, value):
'''
Setter for 'target_ref' field.
:param value - a new value of 'target_ref' field. Must be a String type.
'''
pass
def get_message_ref(self):
'''
Getter for 'message_ref' field.
:return: value of 'message_ref' field.
'''
pass
def set_message_ref(self, value):
'''
Setter for 'message_ref' field.
:param value - a new value of 'message_ref' field. Must be either None (message_ref is optional according to
BPMN 2.0 XML Schema) or String.
'''
pass
| 10 | 10 | 10 | 0 | 5 | 5 | 2 | 1.07 | 1 | 3 | 0 | 0 | 9 | 4 | 9 | 12 | 99 | 10 | 43 | 14 | 33 | 46 | 38 | 14 | 28 | 3 | 2 | 1 | 17 |
144,072 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/root_element/event_definition_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.root_element.event_definition_type.EventDefinition
|
class EventDefinition(root_element.RootElement):
"""
Class used for representing tEventDefinition of BPMN 2.0 graph.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(EventDefinition, self).__init__()
|
class EventDefinition(root_element.RootElement):
'''
Class used for representing tEventDefinition of BPMN 2.0 graph.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 5 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
144,073 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/lane_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.lane_type.Lane
|
class Lane(base_element.BaseElement):
"""
Class used for representing tLane of BPMN 2.0 graph.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- flow_node_ref_list: a list of String objects (ID of referenced nodes).
- child_lane_set: an object of LaneSet type.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(Lane, self).__init__()
self.__name = None
self.__flow_node_ref_list = []
self.__child_lane_set = None
def get_name(self):
"""
Getter for 'name' field.
:return: value of 'name' field.
"""
return self.__name
def set_name(self, value):
"""
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
"""
if value is None:
self.__name = value
elif not isinstance(value, str):
raise TypeError("Name must be set to a String")
else:
self.__name = value
def get_flow_node_ref_list(self):
"""
Getter for 'flow_node_ref' field.
:return:a value of 'flow_node_ref' field.
"""
return self.__flow_node_ref_list
def set_flow_node_ref_list(self, value):
"""
Setter for 'flow_node_ref' field.
:param value - a new value of 'flow_node_ref' field. Must be a list of String objects (ID of referenced nodes).
"""
if value is None or not isinstance(value, list):
raise TypeError("FlowNodeRefList new value must be a list")
else:
for element in value:
if not isinstance(element, str):
raise TypeError("FlowNodeRefList elements in variable must be of String class")
self.__flow_node_ref_list = value
def get_child_lane_set(self):
"""
Getter for 'child_lane_set' field.
:return:a value of 'child_lane_set' field.
"""
return self.__child_lane_set
def set_child_lane_set(self, value):
"""
Setter for 'child_lane_set' field.
:param value - a new value of 'child_lane_set' field. Must be an object of LaneSet type.
"""
if value is None:
self.__child_lane_set = value
elif not isinstance(value, lane_set.LaneSet):
raise TypeError("ChildLaneSet must be a LaneSet")
else:
self.__child_lane_set = value
|
class Lane(base_element.BaseElement):
'''
Class used for representing tLane of BPMN 2.0 graph.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- flow_node_ref_list: a list of String objects (ID of referenced nodes).
- child_lane_set: an object of LaneSet type.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_name(self):
'''
Getter for 'name' field.
:return: value of 'name' field.
'''
pass
def set_name(self, value):
'''
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
'''
pass
def get_flow_node_ref_list(self):
'''
Getter for 'flow_node_ref' field.
:return:a value of 'flow_node_ref' field.
'''
pass
def set_flow_node_ref_list(self, value):
'''
Setter for 'flow_node_ref' field.
:param value - a new value of 'flow_node_ref' field. Must be a list of String objects (ID of referenced nodes).
'''
pass
def get_child_lane_set(self):
'''
Getter for 'child_lane_set' field.
:return:a value of 'child_lane_set' field.
'''
pass
def set_child_lane_set(self, value):
'''
Setter for 'child_lane_set' field.
:param value - a new value of 'child_lane_set' field. Must be an object of LaneSet type.
'''
pass
| 8 | 8 | 9 | 0 | 5 | 4 | 2 | 1.03 | 1 | 5 | 1 | 0 | 7 | 3 | 7 | 10 | 76 | 7 | 34 | 12 | 26 | 35 | 29 | 12 | 21 | 4 | 2 | 3 | 14 |
144,074 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/lane_set_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.lane_set_type.LaneSet
|
class LaneSet(base_element.BaseElement):
"""
Class used for representing tSetLane of BPMN 2.0 graph.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- lane_list: a list of Lane objects.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(LaneSet, self).__init__()
self.__name = None
self.__lane_list = []
def get_name(self):
"""
Getter for 'name' field.
:return: value of 'name' field.
"""
return self.__name
def set_name(self, value):
"""
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
"""
if value is None:
self.__name = value
elif not isinstance(value, str):
raise TypeError("Name must be set to a String")
else:
self.__name = value
def get_lane_list(self):
"""
Getter for 'lane_list' field.
:return: value of 'lane_list' field.
"""
return self.__lane_list
def set_lane_list(self, value):
"""
Setter for 'lane_list' field.
:param value - a new value of 'lane_list' field. Must be a list of Lane objects
"""
if value is None or not isinstance(value, list):
raise TypeError("LaneList new value must be a list")
else:
for element in value:
if not isinstance(element, lane.Lane):
raise TypeError("LaneList elements in variable must be of Lane class")
self.__lane_list = value
|
class LaneSet(base_element.BaseElement):
'''
Class used for representing tSetLane of BPMN 2.0 graph.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
- lane_list: a list of Lane objects.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_name(self):
'''
Getter for 'name' field.
:return: value of 'name' field.
'''
pass
def set_name(self, value):
'''
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
'''
pass
def get_lane_list(self):
'''
Getter for 'lane_list' field.
:return: value of 'lane_list' field.
'''
pass
def set_lane_list(self, value):
'''
Setter for 'lane_list' field.
:param value - a new value of 'lane_list' field. Must be a list of Lane objects
'''
pass
| 6 | 6 | 9 | 0 | 5 | 4 | 2 | 1.08 | 1 | 5 | 1 | 0 | 5 | 2 | 5 | 8 | 55 | 5 | 24 | 9 | 18 | 26 | 21 | 9 | 15 | 4 | 2 | 3 | 10 |
144,075 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/gateways/parallel_gateway_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.gateways.parallel_gateway_type.ParallelGateway
|
class ParallelGateway(gateway.Gateway):
"""
Class used for representing tParallelGateway of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(ParallelGateway, self).__init__()
|
class ParallelGateway(gateway.Gateway):
'''
Class used for representing tParallelGateway of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 15 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 5 | 0 | 1 |
144,076 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/gateways/gateway_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.gateways.gateway_type.Gateway
|
class Gateway(flow_node.FlowNode):
"""
Class used for representing tGateway of BPMN 2.0 graph
"""
__gateway_directions_list = ["Unspecified", "Converging", "Diverging", "Mixed"]
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(Gateway, self).__init__()
self.__gateway_direction = "Unspecified"
def get_gateway_direction(self):
"""
Getter for 'gateway_direction' field.
:return:a value of 'gateway_direction' field.
"""
return self.__gateway_direction
def set_gateway_direction(self, value):
"""
Setter for 'gateway_direction' field.
:param value - a new value of 'gateway_direction' field.
"""
if value is None or not isinstance(value, str):
raise TypeError("GatewayDirection must be set to a String")
elif value not in Gateway.__gateway_directions_list:
raise ValueError("GatewayDirection must be one of specified values: 'Unspecified', 'Converging', "
"'Diverging', 'Mixed'")
else:
self.__gateway_direction = value
|
class Gateway(flow_node.FlowNode):
'''
Class used for representing tGateway of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_gateway_direction(self):
'''
Getter for 'gateway_direction' field.
:return:a value of 'gateway_direction' field.
'''
pass
def set_gateway_direction(self, value):
'''
Setter for 'gateway_direction' field.
:param value - a new value of 'gateway_direction' field.
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 0.93 | 1 | 4 | 0 | 3 | 3 | 1 | 3 | 14 | 32 | 3 | 15 | 6 | 11 | 14 | 12 | 6 | 8 | 3 | 4 | 1 | 5 |
144,077 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/root_element/process_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.root_element.process_type.Process
|
class Process(callable_element.CallableElement):
"""
Class used for representing tProcess of BPMN 2.0 graph.
"""
__process_type_list = ["None", "Public", "Private"]
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(Process, self).__init__()
self.__process_type = "None"
self.__is_closed = False
self.__is_executable = False
self.__lane_set_list = []
self.__flow_element_list = []
def get_process_type(self):
"""
Getter for 'process_type' field.
:return:a value of 'process_type' field.
"""
return self.__process_type
def set_process_type(self, value):
"""
Setter for 'process_type' field.
:param value - a new value of 'process_type' field.
"""
if value is None or not isinstance(value, str):
raise TypeError("ProcessType must be set to a String")
elif value not in Process.__process_type_list:
raise ValueError("ProcessType must be one of specified values: 'None', 'Public', 'Private'")
else:
self.__process_type = value
def is_closed(self):
"""
Getter for 'is_closed' field.
:return: value of 'is_closed' field.
"""
return self.__is_closed
def set_is_closed(self, value):
"""
Setter for 'is_closed' field.
:param value - a new value of 'is_closed' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("IsClosed must be set to a bool")
else:
self.__is_closed = value
def is_executable(self):
"""
Getter for 'is_executable' field.
:return: value of 'is_executable' field.
"""
return self.__is_executable
def set_is_executable(self, value):
"""
Setter for 'is_executable' field.
:param value - a new value of 'is_executable' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("IsExecutable must be set to a bool")
else:
self.__is_executable = value
def get_lane_set_list(self):
"""
Getter for 'lane_set_list' field.
:return:a value of 'lane_set_list' field.
"""
return self.__lane_set_list
def set_lane_set_list(self, value):
"""
Setter for 'lane_set_list' field.
:param value - a new value of 'lane_set_list' field. Must be a list
"""
if value is None or not isinstance(value, list):
raise TypeError("LaneSetList new value must be a list")
else:
for element in value:
if not isinstance(element, lane_set.LaneSet):
raise TypeError("LaneSetList elements in variable must be of LaneSet class")
self.__lane_set_list = value
def get_flow_element_list(self):
"""
Getter for 'flow_element_list' field.
:return:a value of 'flow_element_list' field.
"""
return self.__flow_element_list
def set_flow_element_list(self, value):
"""
Setter for 'flow_element_list' field.
:param value - a new value of 'flow_element_list' field. Must be a list
"""
if value is None or not isinstance(value, list):
raise TypeError("FlowElementList new value must be a list")
else:
for element in value:
if not isinstance(element, flow_element.FlowElement):
raise TypeError("FlowElementList elements in variable must be of FlowElement class")
self.__flow_element_list = value
|
class Process(callable_element.CallableElement):
'''
Class used for representing tProcess of BPMN 2.0 graph.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_process_type(self):
'''
Getter for 'process_type' field.
:return:a value of 'process_type' field.
'''
pass
def set_process_type(self, value):
'''
Setter for 'process_type' field.
:param value - a new value of 'process_type' field.
'''
pass
def is_closed(self):
'''
Getter for 'is_closed' field.
:return: value of 'is_closed' field.
'''
pass
def set_is_closed(self, value):
'''
Setter for 'is_closed' field.
:param value - a new value of 'is_closed' field. Must be a boolean type. Does not accept None value.
'''
pass
def is_executable(self):
'''
Getter for 'is_executable' field.
:return: value of 'is_executable' field.
'''
pass
def set_is_executable(self, value):
'''
Setter for 'is_executable' field.
:param value - a new value of 'is_executable' field. Must be a boolean type. Does not accept None value.
'''
pass
def get_lane_set_list(self):
'''
Getter for 'lane_set_list' field.
:return:a value of 'lane_set_list' field.
'''
pass
def set_lane_set_list(self, value):
'''
Setter for 'lane_set_list' field.
:param value - a new value of 'lane_set_list' field. Must be a list
'''
pass
def get_flow_element_list(self):
'''
Getter for 'flow_element_list' field.
:return:a value of 'flow_element_list' field.
'''
pass
def set_flow_element_list(self, value):
'''
Setter for 'flow_element_list' field.
:param value - a new value of 'flow_element_list' field. Must be a list
'''
pass
| 12 | 12 | 8 | 0 | 5 | 4 | 2 | 0.88 | 1 | 8 | 2 | 0 | 11 | 5 | 11 | 18 | 109 | 11 | 52 | 20 | 40 | 46 | 46 | 20 | 34 | 4 | 4 | 3 | 21 |
144,078 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/gateways/exclusive_gateway_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.gateways.exclusive_gateway_type.ExclusiveGateway
|
class ExclusiveGateway(gateway.Gateway):
"""
Class used for representing tExclusiveGateway of BPMN 2.0 graph
Fields (except inherited):
- default: ID of default flow of gateway. Must be either None (default is optional according to BPMN 2.0 XML Schema)
or String.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(ExclusiveGateway, self).__init__()
self.__default = None
def get_default(self):
"""
Getter for 'default' field.
:return:a value of 'default' field.
"""
return self.__default
def set_default(self, value):
"""
Setter for 'default' field.
:param value - a new value of 'default' field. Must be either None (default is optional according to
BPMN 2.0 XML Schema) or String.
"""
if value is None:
self.__default = value
elif not isinstance(value, str):
raise TypeError("Default must be set to a String")
else:
self.__default = value
|
class ExclusiveGateway(gateway.Gateway):
'''
Class used for representing tExclusiveGateway of BPMN 2.0 graph
Fields (except inherited):
- default: ID of default flow of gateway. Must be either None (default is optional according to BPMN 2.0 XML Schema)
or String.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_default(self):
'''
Getter for 'default' field.
:return:a value of 'default' field.
'''
pass
def set_default(self, value):
'''
Setter for 'default' field.
:param value - a new value of 'default' field. Must be either None (default is optional according to
BPMN 2.0 XML Schema) or String.
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 1.38 | 1 | 3 | 0 | 0 | 3 | 1 | 3 | 17 | 34 | 3 | 13 | 5 | 9 | 18 | 11 | 5 | 7 | 3 | 5 | 1 | 5 |
144,079 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/flow_node_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.flow_node_type.FlowNode
|
class FlowNode(flow_element_type.FlowElement):
"""
Class used for representing tFlowNode of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
Fields (except inherited):
- incoming_list: a list of IDs (String type) of incoming flows.
- outgoing_list: a list of IDs (String type) of outgoing flows.
"""
super(FlowNode, self).__init__()
self.__incoming_list = []
self.__outgoing_list = []
def get_incoming(self):
"""
Getter for 'incoming' field.
:return:a value of 'incoming' field.
"""
return self.__incoming_list
def set_incoming(self, value):
"""
Setter for 'incoming' field.
:param value - a new value of 'incoming' field. List of IDs (String type) of incoming flows.
"""
if not isinstance(value, list):
raise TypeError("IncomingList new value must be a list")
for element in value:
if not isinstance(element, str):
raise TypeError("IncomingList elements in variable must be of String class")
self.__incoming_list = value
def get_outgoing(self):
"""
Getter for 'outgoing' field.
:return:a value of 'outgoing' field.
"""
return self.__outgoing_list
def set_outgoing(self, value):
"""
Setter for 'outgoing' field.
:param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows.
"""
if not isinstance(value, list):
raise TypeError("OutgoingList new value must be a list")
for element in value:
if not isinstance(element, str):
raise TypeError("OutgoingList elements in variable must be of String class")
self.__outgoing_list = value
|
class FlowNode(flow_element_type.FlowElement):
'''
Class used for representing tFlowNode of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
Fields (except inherited):
- incoming_list: a list of IDs (String type) of incoming flows.
- outgoing_list: a list of IDs (String type) of outgoing flows.
'''
pass
def get_incoming(self):
'''
Getter for 'incoming' field.
:return:a value of 'incoming' field.
'''
pass
def set_incoming(self, value):
'''
Setter for 'incoming' field.
:param value - a new value of 'incoming' field. List of IDs (String type) of incoming flows.
'''
pass
def get_outgoing(self):
'''
Getter for 'outgoing' field.
:return:a value of 'outgoing' field.
'''
pass
def set_outgoing(self, value):
'''
Setter for 'outgoing' field.
:param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows.
'''
pass
| 6 | 6 | 9 | 0 | 4 | 4 | 2 | 1.09 | 1 | 4 | 0 | 3 | 5 | 2 | 5 | 11 | 53 | 5 | 23 | 10 | 17 | 25 | 23 | 10 | 17 | 4 | 3 | 2 | 11 |
144,080 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/base_element_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.base_element_type.BaseElement
|
class BaseElement(object):
"""
Class used for representing tBaseElement of BPMN 2.0 graph.
Fields:
- id: an ID of element. Must be either None (ID is optional according to BPMN 2.0 XML Schema) or String.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
self.__id = None
def get_id(self):
"""
Getter for 'id' field.
:return: value of 'id' field.
"""
return self.__id
def set_id(self, value):
"""
Setter for 'id' field.
:param value - a new value of 'id' field. Must be either None (ID is optional according to BPMN 2.0 XML Schema)
or String type.
"""
if value is None:
self.__id = value
if not isinstance(value, str):
raise TypeError("ID must be set to a String")
else:
self.__id = value
|
class BaseElement(object):
'''
Class used for representing tBaseElement of BPMN 2.0 graph.
Fields:
- id: an ID of element. Must be either None (ID is optional according to BPMN 2.0 XML Schema) or String.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_id(self):
'''
Getter for 'id' field.
:return: value of 'id' field.
'''
pass
def set_id(self, value):
'''
Setter for 'id' field.
:param value - a new value of 'id' field. Must be either None (ID is optional according to BPMN 2.0 XML Schema)
or String type.
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 1.42 | 1 | 2 | 0 | 6 | 3 | 1 | 3 | 3 | 32 | 3 | 12 | 5 | 8 | 17 | 11 | 5 | 7 | 3 | 1 | 1 | 5 |
144,081 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/gateways/inclusive_gateway_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.gateways.inclusive_gateway_type.InclusiveGateway
|
class InclusiveGateway(gateway.Gateway):
"""
Class used for representing tInclusiveGateway of BPMN 2.0 graph
Fields (except inherited):
- default: ID of default flow of gateway. Must be either None (default is optional according to BPMN 2.0 XML Schema)
or String.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(InclusiveGateway, self).__init__()
self.__default = None
def get_default(self):
"""
Getter for 'default' field.
:return:a value of 'default' field.
"""
return self.__default
def set_default(self, value):
"""
Setter for 'default' field.
:param value - a new value of 'default' field. Must be either None (default is optional according to
BPMN 2.0 XML Schema) or String.
"""
if value is None:
self.__default = value
elif not isinstance(value, str):
raise TypeError("Default must be set to a String")
else:
self.__default = value
|
class InclusiveGateway(gateway.Gateway):
'''
Class used for representing tInclusiveGateway of BPMN 2.0 graph
Fields (except inherited):
- default: ID of default flow of gateway. Must be either None (default is optional according to BPMN 2.0 XML Schema)
or String.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_default(self):
'''
Getter for 'default' field.
:return:a value of 'default' field.
'''
pass
def set_default(self, value):
'''
Setter for 'default' field.
:param value - a new value of 'default' field. Must be either None (default is optional according to
BPMN 2.0 XML Schema) or String.
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 1.38 | 1 | 3 | 0 | 0 | 3 | 1 | 3 | 17 | 34 | 3 | 13 | 5 | 9 | 18 | 11 | 5 | 7 | 3 | 5 | 1 | 5 |
144,082 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/events/throw_event_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.events.throw_event_type.ThrowEvent
|
class ThrowEvent(event.Event):
"""
Class used for representing tThrowEvent of BPMN 2.0 graph
Fields (except inherited):
- event_definition_list: a list of EventDefinition objects. Optional value.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(ThrowEvent, self).__init__()
self.__event_definition_list = []
def get_event_definition_list(self):
"""
Getter for 'event_definition_list' field.
:return: value of 'event_definition_list' field.
"""
return self.__event_definition_list
def set_event_definition_list(self, value):
"""
Setter for 'event_definition_list' field.
:param value - a new value of 'event_definition_list' field. Must be a list of EventDefinition objects
"""
if value is None or not isinstance(value, list):
raise TypeError("EventDefinitionList new value must be a list")
else:
for element in value:
if not isinstance(element, event_definition.EventDefinition):
raise TypeError("EventDefinitionList elements in variable must be of Lane class")
self.__event_definition_list = value
|
class ThrowEvent(event.Event):
'''
Class used for representing tThrowEvent of BPMN 2.0 graph
Fields (except inherited):
- event_definition_list: a list of EventDefinition objects. Optional value.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_event_definition_list(self):
'''
Getter for 'event_definition_list' field.
:return: value of 'event_definition_list' field.
'''
pass
def set_event_definition_list(self, value):
'''
Setter for 'event_definition_list' field.
:param value - a new value of 'event_definition_list' field. Must be a list of EventDefinition objects
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 1.14 | 1 | 4 | 1 | 2 | 3 | 1 | 3 | 15 | 33 | 3 | 14 | 6 | 10 | 16 | 13 | 6 | 9 | 4 | 5 | 3 | 6 |
144,083 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/root_element/root_element_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.root_element.root_element_type.RootElement
|
class RootElement(base_element.BaseElement):
"""
Class used for representing tRootElement of BPMN 2.0 graph.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(RootElement, self).__init__()
|
class RootElement(base_element.BaseElement):
'''
Class used for representing tRootElement of BPMN 2.0 graph.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 2 | 1 | 0 | 1 | 4 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
144,084 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/events/start_event_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.events.start_event_type.StartEvent
|
class StartEvent(catch_event.CatchEvent):
"""
Class used for representing tStartEvent of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(StartEvent, self).__init__()
|
class StartEvent(catch_event.CatchEvent):
'''
Class used for representing tStartEvent of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 18 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 6 | 0 | 1 |
144,085 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/events/intermediate_throw_event_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.events.intermediate_throw_event_type.IntermediateThrowEvent
|
class IntermediateThrowEvent(throw_event.ThrowEvent):
"""
Class used for representing tIntermediateThrowEvent of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(IntermediateThrowEvent, self).__init__()
|
class IntermediateThrowEvent(throw_event.ThrowEvent):
'''
Class used for representing tIntermediateThrowEvent of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 16 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 6 | 0 | 1 |
144,086 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/condition_expression_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.condition_expression_type.ConditionExpression
|
class ConditionExpression(object):
"""
Class used for representing condition expression in sequence flow
Fields:
- condition: condition expression. Required field. Must be a String.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(ConditionExpression, self).__init__()
self.__condition = None
def get_condition(self):
"""
Getter for 'condition' field.
:return:a value of 'condition' field.
"""
return self.__condition
def set_condition(self, value):
"""
Setter for 'condition' field.
:param value - a new value of 'condition' field. Required field. Must be a String.
"""
if value is None or not isinstance(value, str):
raise TypeError("Condition is required and must be set to a String")
else:
self.__condition = value
|
class ConditionExpression(object):
'''
Class used for representing condition expression in sequence flow
Fields:
- condition: condition expression. Required field. Must be a String.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_condition(self):
'''
Getter for 'condition' field.
:return:a value of 'condition' field.
'''
pass
def set_condition(self, value):
'''
Setter for 'condition' field.
:param value - a new value of 'condition' field. Required field. Must be a String.
'''
pass
| 4 | 4 | 7 | 0 | 3 | 4 | 1 | 1.45 | 1 | 3 | 0 | 0 | 3 | 1 | 3 | 3 | 30 | 3 | 11 | 5 | 7 | 16 | 10 | 5 | 6 | 2 | 1 | 1 | 4 |
144,087 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/activities/task_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.activities.task_type.Task
|
class Task(activity.Activity):
"""
Class used for representing tTask of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(Task, self).__init__()
|
class Task(activity.Activity):
'''
Class used for representing tTask of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 15 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 5 | 0 | 1 |
144,088 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/activities/subprocess_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.activities.subprocess_type.SubProcess
|
class SubProcess(activity.Activity):
"""
Class used for representing tSubProcess of BPMN 2.0 graph
Fields (except inherited):
- lane_set_list: a list of LaneSet objects.
- flow_element_list: a list of FlowElement objects.
- triggered_by_event: a boolean value..
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(SubProcess, self).__init__()
self.__triggered_by_event = False
self.__lane_set_list = []
self.__flow_element_list = []
def triggered_by_event(self):
"""
Getter for 'triggered_by_event' field.
:return: value of 'triggered_by_event' field.
"""
return self.__triggered_by_event
def set_triggered_by_event(self, value):
"""
Setter for 'triggered_by_event' field.
:param value - a new value of 'triggered_by_event' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("TriggeredByEvent must be set to a bool")
else:
self.__triggered_by_event = value
def get_lane_set_list(self):
"""
Getter for 'lane_set_list' field.
:return:a value of 'lane_set_list' field.
"""
return self.__lane_set_list
def set_lane_set_list(self, value):
"""
Setter for 'lane_set_list' field.
:param value - a new value of 'lane_set_list' field. Must be a list
"""
if value is None or not isinstance(value, list):
raise TypeError("LaneSetList new value must be a list")
else:
for element in value:
if not isinstance(element, lane_set.LaneSet):
raise TypeError("LaneSetList elements in variable must be of LaneSet class")
self.__lane_set_list = value
def get_flow_element_list(self):
"""
Getter for 'flow_element_list' field.
:return:a value of 'flow_element_list' field.
"""
return self.__flow_element_list
def set_flow_element_list(self, value):
"""
Setter for 'flow_element_list' field.
:param value - a new value of 'flow_element_list' field. Must be a list
"""
if value is None or not isinstance(value, list):
raise TypeError("FlowElementList new value must be a list")
else:
for element in value:
if not isinstance(element, flow_element.FlowElement):
raise TypeError("FlowElementList elements in variable must be of FlowElement class")
self.__flow_element_list = value
|
class SubProcess(activity.Activity):
'''
Class used for representing tSubProcess of BPMN 2.0 graph
Fields (except inherited):
- lane_set_list: a list of LaneSet objects.
- flow_element_list: a list of FlowElement objects.
- triggered_by_event: a boolean value..
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def triggered_by_event(self):
'''
Getter for 'triggered_by_event' field.
:return: value of 'triggered_by_event' field.
'''
pass
def set_triggered_by_event(self, value):
'''
Setter for 'triggered_by_event' field.
:param value - a new value of 'triggered_by_event' field. Must be a boolean type. Does not accept None value.
'''
pass
def get_lane_set_list(self):
'''
Getter for 'lane_set_list' field.
:return:a value of 'lane_set_list' field.
'''
pass
def set_lane_set_list(self, value):
'''
Setter for 'lane_set_list' field.
:param value - a new value of 'lane_set_list' field. Must be a list
'''
pass
def get_flow_element_list(self):
'''
Getter for 'flow_element_list' field.
:return:a value of 'flow_element_list' field.
'''
pass
def set_flow_element_list(self, value):
'''
Setter for 'flow_element_list' field.
:param value - a new value of 'flow_element_list' field. Must be a list
'''
pass
| 8 | 8 | 8 | 0 | 5 | 4 | 2 | 1.03 | 1 | 5 | 1 | 0 | 7 | 3 | 7 | 21 | 74 | 7 | 33 | 13 | 25 | 34 | 30 | 13 | 22 | 4 | 5 | 3 | 14 |
144,089 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/activities/activity_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.activities.activity_type.Activity
|
class Activity(flow_node.FlowNode):
"""
Class used for representing tActivity of BPMN 2.0 graph
Fields (except inherited):
- default: ID of default flow of gateway. Must be either None (default is optional according to BPMN 2.0 XML Schema)
or String.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(Activity, self).__init__()
self.__default = None
def get_default(self):
"""
Getter for 'default' field.
:return:a value of 'default' field.
"""
return self.__default
def set_default(self, value):
"""
Setter for 'default' field.
:param value - a new value of 'default' field. Must be either None (default is optional according to
BPMN 2.0 XML Schema) or String.
"""
if value is None:
self.__default = value
elif not isinstance(value, str):
raise TypeError("Default must be set to a String")
else:
self.__default = value
|
class Activity(flow_node.FlowNode):
'''
Class used for representing tActivity of BPMN 2.0 graph
Fields (except inherited):
- default: ID of default flow of gateway. Must be either None (default is optional according to BPMN 2.0 XML Schema)
or String.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_default(self):
'''
Getter for 'default' field.
:return:a value of 'default' field.
'''
pass
def set_default(self, value):
'''
Setter for 'default' field.
:param value - a new value of 'default' field. Must be either None (default is optional according to
BPMN 2.0 XML Schema) or String.
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 1.38 | 1 | 3 | 0 | 2 | 3 | 1 | 3 | 14 | 34 | 3 | 13 | 5 | 9 | 18 | 11 | 5 | 7 | 3 | 4 | 1 | 5 |
144,090 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_python_consts.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_python_consts.Consts
|
class Consts(object):
"""
Class used to unify the different constant values used in entire project
"""
# BPMN 2.0 element attribute names
id = "id"
name = "name"
# Flow nodes cannot use "name" parameter in dictionary, due to the errors with PyDot
node_name = "node_name"
gateway_direction = "gatewayDirection"
default = "default"
instantiate = "instantiate"
event_gateway_type = "eventGatewayType"
source_ref = "sourceRef"
target_ref = "targetRef"
triggered_by_event = "triggeredByEvent"
parallel_multiple = "parallelMultiple"
cancel_activity = "cancelActivity"
attached_to_ref = "attachedToRef"
is_interrupting = "isInterrupting"
is_closed = "isClosed"
is_executable = "isExecutable"
is_expanded = "isExpanded"
is_horizontal = "isHorizontal"
is_collection = "isCollection"
process_type = "processType"
sequence_flow = "sequenceFlow"
condition_expression = "conditionExpression"
message_flow = "messageFlow"
message_flows = "messageFlows"
# CSV literals
csv_order = "Order"
csv_activity = "Activity"
csv_condition = "Condition"
csv_who = "Who"
csv_subprocess = "Subprocess"
csv_terminated = "Terminated"
# BPMN 2.0 diagram interchange element attribute names
bpmn_element = "bpmnElement"
height = "height"
width = "width"
x = "x"
y = "y"
# BPMN 2.0 element names
definitions = "definitions"
collaboration = "collaboration"
participant = "participant"
participants = "participants"
process = "process"
process_ref = "processRef"
lane = "lane"
lanes = "lanes"
lane_set = "laneSet"
child_lane_set = "childLaneSet"
flow_node_ref = "flowNodeRef"
flow_node_refs = "flowNodeRefs"
task = "task"
user_task = "userTask"
service_task = "serviceTask"
manual_task = "manualTask"
subprocess = "subProcess"
data_object = "dataObject"
complex_gateway = "complexGateway"
event_based_gateway = "eventBasedGateway"
inclusive_gateway = "inclusiveGateway"
exclusive_gateway = "exclusiveGateway"
parallel_gateway = "parallelGateway"
start_event = "startEvent"
intermediate_catch_event = "intermediateCatchEvent"
end_event = "endEvent"
intermediate_throw_event = "intermediateThrowEvent"
boundary_event = "boundaryEvent"
# BPMN 2.0 diagram interchange element names
bpmn_shape = "BPMNShape"
bpmn_edge = "BPMNEdge"
# BPMN 2.0 child element names
incoming_flow = "incoming"
incoming_flow_list = "incoming_flow_list"
outgoing_flow = "outgoing"
outgoing_flow_list = "outgoing_flow_list"
waypoint = "waypoint"
waypoints = "waypoints"
# Additional parameter names
type = "type"
event_definitions = "event_definitions"
node_ids = "node_ids"
definition_type = "definition_type"
grid_column_width = 2
|
class Consts(object):
'''
Class used to unify the different constant values used in entire project
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.14 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 95 | 7 | 77 | 76 | 76 | 11 | 77 | 76 | 76 | 0 | 1 | 0 | 0 |
144,091 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/events/intermediate_catch_event_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.events.intermediate_catch_event_type.IntermediateCatchEvent
|
class IntermediateCatchEvent(catch_event.CatchEvent):
"""
Class used for representing tIntermediateCatchEvent of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(IntermediateCatchEvent, self).__init__()
|
class IntermediateCatchEvent(catch_event.CatchEvent):
'''
Class used for representing tIntermediateCatchEvent of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 18 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 6 | 0 | 1 |
144,092 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/events/catch_event_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.events.catch_event_type.CatchEvent
|
class CatchEvent(event.Event):
"""
Class used for representing tCatchEvent of BPMN 2.0 graph
Fields (except inherited):
- parallel_multiple: a boolean value. default value "false".
- event_definition_list: a list of EventDefinition objects. Optional value.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(CatchEvent, self).__init__()
self.__parallel_multiple = False
self.__event_definition_list = []
def parallel_multiple(self):
"""
Getter for 'parallel_multiple' field.
:return: value of 'parallel_multiple' field.
"""
return self.__parallel_multiple
def set_parallel_multiple(self, value):
"""
Setter for 'parallel_multiple' field.
:param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("ParallelMultiple must be set to a bool")
else:
self.__parallel_multiple = value
def get_event_definition_list(self):
"""
Getter for 'event_definition_list' field.
:return: value of 'event_definition_list' field.
"""
return self.__event_definition_list
def set_event_definition_list(self, value):
"""
Setter for 'event_definition_list' field.
:param value - a new value of 'event_definition_list' field. Must be a list of EventDefinition objects
"""
if value is None or not isinstance(value, list):
raise TypeError("EventDefinitionList new value must be a list")
else:
for element in value:
if not isinstance(element, event_definition.EventDefinition):
raise TypeError("EventDefinitionList elements in variable must be of Lane class")
self.__event_definition_list = value
|
class CatchEvent(event.Event):
'''
Class used for representing tCatchEvent of BPMN 2.0 graph
Fields (except inherited):
- parallel_multiple: a boolean value. default value "false".
- event_definition_list: a list of EventDefinition objects. Optional value.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def parallel_multiple(self):
'''
Getter for 'parallel_multiple' field.
:return: value of 'parallel_multiple' field.
'''
pass
def set_parallel_multiple(self, value):
'''
Setter for 'parallel_multiple' field.
:param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value.
'''
pass
def get_event_definition_list(self):
'''
Getter for 'event_definition_list' field.
:return: value of 'event_definition_list' field.
'''
pass
def set_event_definition_list(self, value):
'''
Setter for 'event_definition_list' field.
:param value - a new value of 'event_definition_list' field. Must be a list of EventDefinition objects
'''
pass
| 6 | 6 | 8 | 0 | 4 | 4 | 2 | 1.14 | 1 | 5 | 1 | 2 | 5 | 2 | 5 | 17 | 52 | 5 | 22 | 9 | 16 | 25 | 20 | 9 | 14 | 4 | 5 | 3 | 9 |
144,093 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/events/end_event_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.events.end_event_type.EndEvent
|
class EndEvent(throw_event.ThrowEvent):
"""
Class used for representing tEndEvent of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(EndEvent, self).__init__()
|
class EndEvent(throw_event.ThrowEvent):
'''
Class used for representing tEndEvent of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 16 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 6 | 0 | 1 |
144,094 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/events/event_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.events.event_type.Event
|
class Event(flow_node.FlowNode):
"""
Class used for representing tEvent of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(Event, self).__init__()
|
class Event(flow_node.FlowNode):
'''
Class used for representing tEvent of BPMN 2.0 graph
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 2 | 1 | 0 | 1 | 12 | 10 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
144,095 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/flow_element_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.flow_element_type.FlowElement
|
class FlowElement(base_element.BaseElement):
"""
Class used for representing tFlowElement of BPMN 2.0 graph.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
"""
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
super(FlowElement, self).__init__()
self.__name = None
def get_name(self):
"""
Getter for 'name' field.
:return:a value of 'name' field.
"""
return self.__name
def set_name(self, value):
"""
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
"""
if value is None:
self.__name = value
elif not isinstance(value, str):
raise TypeError("Name must be set to a String")
else:
self.__name = value
|
class FlowElement(base_element.BaseElement):
'''
Class used for representing tFlowElement of BPMN 2.0 graph.
Fields (except inherited):
- name: name of element. Must be either None (name is optional according to BPMN 2.0 XML Schema) or String.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_name(self):
'''
Getter for 'name' field.
:return:a value of 'name' field.
'''
pass
def set_name(self, value):
'''
Setter for 'name' field.
:param value - a new value of 'name' field. Must be either None (name is optional according to BPMN 2.0 XML
Schema) or String.
'''
pass
| 4 | 4 | 8 | 0 | 4 | 4 | 2 | 1.31 | 1 | 3 | 0 | 2 | 3 | 1 | 3 | 6 | 33 | 3 | 13 | 5 | 9 | 17 | 11 | 5 | 7 | 3 | 2 | 1 | 5 |
144,096 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_process_csv_import.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_process_csv_import.BpmnDiagramGraphCSVImport
|
class BpmnDiagramGraphCSVImport(object):
"""
Template
"""
@staticmethod
def load_diagram_from_csv(filepath, bpmn_diagram):
"""
Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath,
:param bpmn_diagram: an instance of BpmnDiagramGraph class.
"""
sequence_flows = bpmn_diagram.sequence_flows
process_elements_dict = bpmn_diagram.process_elements
diagram_attributes = bpmn_diagram.diagram_attributes
plane_attributes = bpmn_diagram.plane_attributes
process_dict = BpmnDiagramGraphCSVImport.import_csv_file_as_dict(filepath)
BpmnDiagramGraphCSVImport.populate_diagram_elements_dict(diagram_attributes)
BpmnDiagramGraphCSVImport.populate_process_elements_dict(process_elements_dict, process_dict)
BpmnDiagramGraphCSVImport.populate_plane_elements_dict(plane_attributes)
BpmnDiagramGraphCSVImport.import_nodes(process_dict, bpmn_diagram, sequence_flows)
BpmnDiagramGraphCSVImport.representation_adjustment(process_dict, bpmn_diagram, sequence_flows)
@staticmethod
def import_csv_file_as_dict(filepath):
"""
:param filepath:
:return:
"""
process_dict = pd.read_csv(filepath, index_col=0).fillna("").to_dict('index')
remove_white_spaces_in_orders(process_dict)
return process_dict
@staticmethod
def get_given_task_as_dict(csv_df, order_val):
"""
:param csv_df:
:param order_val:
:return:
"""
return csv_df.loc[csv_df[consts.Consts.csv_order] == order_val].iloc[0].to_dict()
@staticmethod
def import_nodes(process_dict, bpmn_diagram, sequence_flows):
"""
:param process_dict:
:param bpmn_diagram:
:param sequence_flows:
"""
import_nodes_info(process_dict, bpmn_diagram)
fill_graph_connections(process_dict, bpmn_diagram, sequence_flows)
@staticmethod
def populate_diagram_elements_dict(diagram_elements_dict):
"""
:param diagram_elements_dict:
"""
diagram_elements_dict[consts.Consts.id] = "diagram1"
diagram_elements_dict[consts.Consts.name] = "diagram_name"
@staticmethod
def populate_process_elements_dict(process_elements_dict, process_dict):
"""
:param process_elements_dict:
:param process_dict:
"""
process_id = default_process_id
process_element_attributes = {consts.Consts.id: default_process_id,
consts.Consts.name: "",
consts.Consts.is_closed: "false",
consts.Consts.is_executable: "false",
consts.Consts.process_type: "None",
consts.Consts.node_ids: list(process_dict.keys())}
process_elements_dict[process_id] = process_element_attributes
@staticmethod
def populate_plane_elements_dict(plane_elements_dict):
"""
:param plane_elements_dict:
"""
plane_elements_dict[consts.Consts.id] = default_plane_id
plane_elements_dict[consts.Consts.bpmn_element] = default_process_id
@staticmethod
def legacy_adjustment(bpmn_diagram):
"""
:param bpmn_diagram:
"""
for node in bpmn_diagram.get_nodes():
if node[1].get(consts.Consts.incoming_flow) is None:
node[1][consts.Consts.incoming_flow] = []
if node[1].get(consts.Consts.outgoing_flow) is None:
node[1][consts.Consts.outgoing_flow] = []
if node[1].get(consts.Consts.event_definitions) is None:
node[1][consts.Consts.event_definitions] = []
@staticmethod
def representation_adjustment(process_dict, diagram_graph, sequence_flows):
"""
:param process_dict:
:param diagram_graph:
:param sequence_flows:
"""
BpmnDiagramGraphCSVImport.legacy_adjustment(diagram_graph)
remove_goto_nodes(process_dict, diagram_graph, sequence_flows)
remove_unnecessary_merge_gateways(process_dict, diagram_graph, sequence_flows)
|
class BpmnDiagramGraphCSVImport(object):
'''
Template
'''
@staticmethod
def load_diagram_from_csv(filepath, bpmn_diagram):
'''
Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath,
:param bpmn_diagram: an instance of BpmnDiagramGraph class.
'''
pass
@staticmethod
def import_csv_file_as_dict(filepath):
'''
:param filepath:
:return:
'''
pass
@staticmethod
def get_given_task_as_dict(csv_df, order_val):
'''
:param csv_df:
:param order_val:
:return:
'''
pass
@staticmethod
def import_nodes(process_dict, bpmn_diagram, sequence_flows):
'''
:param process_dict:
:param bpmn_diagram:
:param sequence_flows:
'''
pass
@staticmethod
def populate_diagram_elements_dict(diagram_elements_dict):
'''
:param diagram_elements_dict:
'''
pass
@staticmethod
def populate_process_elements_dict(process_elements_dict, process_dict):
'''
:param process_elements_dict:
:param process_dict:
'''
pass
@staticmethod
def populate_plane_elements_dict(plane_elements_dict):
'''
:param plane_elements_dict:
'''
pass
@staticmethod
def legacy_adjustment(bpmn_diagram):
'''
:param bpmn_diagram:
'''
pass
@staticmethod
def representation_adjustment(process_dict, diagram_graph, sequence_flows):
'''
:param process_dict:
:param diagram_graph:
:param sequence_flows:
'''
pass
| 19 | 10 | 11 | 1 | 5 | 4 | 1 | 0.72 | 1 | 2 | 1 | 0 | 0 | 0 | 9 | 9 | 118 | 20 | 57 | 28 | 38 | 41 | 43 | 19 | 33 | 5 | 1 | 2 | 13 |
144,097 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/graph/classes/sequence_flow_type.py
|
KrzyHonk_bpmn-python.bpmn_python.graph.classes.sequence_flow_type.SequenceFlow
|
class SequenceFlow(flow_element.FlowElement):
"""
Class used for representing tSequenceFlow of BPMN 2.0 graph.
Fields (except inherited):
- source_ref: an ID of source node. Required field. Must be a String type.
- target_ref: an ID of target node. Required field. Must be a String type.
- condition_expression: an expression used as condition of flow (conditional flow). Must be either None
(condition_expression is optional according to BPMN 2.0 XML Schema) or String.
- is_immediate: a boolean value.
"""
def __init__(self, source_ref, target_ref):
"""
Default constructor, initializes object fields with new instances.
"""
if source_ref is None or not isinstance(source_ref, str):
raise TypeError("SourceRef is required and must be set to a String")
if target_ref is None or not isinstance(source_ref, str):
raise TypeError("TargetRef is required and must be set to a String")
super(SequenceFlow, self).__init__()
self.__source_ref = source_ref
self.__target_ref = target_ref
self.__condition_expression = None
self.__is_immediate = None
def get_source_ref(self):
"""
Getter for 'source_ref' field.
:return: value of 'source_ref' field.
"""
return self.__source_ref
def set_source_ref(self, value):
"""
Setter for 'source_ref' field.
:param value - a new value of 'source_ref' field. Required field. Must be a String type.
"""
if value is None or not isinstance(value, str):
raise TypeError("SourceRef is required and must be set to a String")
else:
self.__source_ref = value
def get_target_ref(self):
"""
Getter for 'target_ref' field.
:return: value of 'target_ref' field.
"""
return self.__target_ref
def set_target_ref(self, value):
"""
Setter for 'target_ref' field.
:param value - a new value of 'target_ref' field. Required field. Must be a String type.
"""
if value is None or not isinstance(value, str):
raise TypeError("TargetRef is required and must be set to a String")
else:
self.__target_ref = value
def is_immediate(self):
"""
Getter for 'is_immediate' field.
:return: value of 'is_immediate' field.
"""
return self.__is_immediate
def set_is_immediate(self, value):
"""
Setter for 'is_immediate' field.
:param value - a new value of 'is_immediate' field. Must be a boolean type.
"""
if value is None:
self.__is_immediate = value
elif not isinstance(value, bool):
raise TypeError("IsImediate must be set to a bool")
else:
self.__is_immediate = value
def get_condition_expression(self):
"""
Getter for 'condition_expression' field.
:return: value of 'condition_expression' field. Must be either None (condition_expression is optional according
to BPMN 2.0 XML Schema) or String.
"""
return self.__condition_expression
def set_condition_expression(self, value):
"""
Setter for 'condition_expression' field.
:param value - a new value of 'condition_expression' field.
"""
if value is None:
self.__condition_expression = value
if not isinstance(value, condition_expression.ConditionExpression):
raise TypeError("ConditionExpression must be set to an instance of class ConditionExpression")
else:
self.__condition_expression = value
|
class SequenceFlow(flow_element.FlowElement):
'''
Class used for representing tSequenceFlow of BPMN 2.0 graph.
Fields (except inherited):
- source_ref: an ID of source node. Required field. Must be a String type.
- target_ref: an ID of target node. Required field. Must be a String type.
- condition_expression: an expression used as condition of flow (conditional flow). Must be either None
(condition_expression is optional according to BPMN 2.0 XML Schema) or String.
- is_immediate: a boolean value.
'''
def __init__(self, source_ref, target_ref):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def get_source_ref(self):
'''
Getter for 'source_ref' field.
:return: value of 'source_ref' field.
'''
pass
def set_source_ref(self, value):
'''
Setter for 'source_ref' field.
:param value - a new value of 'source_ref' field. Required field. Must be a String type.
'''
pass
def get_target_ref(self):
'''
Getter for 'target_ref' field.
:return: value of 'target_ref' field.
'''
pass
def set_target_ref(self, value):
'''
Setter for 'target_ref' field.
:param value - a new value of 'target_ref' field. Required field. Must be a String type.
'''
pass
def is_immediate(self):
'''
Getter for 'is_immediate' field.
:return: value of 'is_immediate' field.
'''
pass
def set_is_immediate(self, value):
'''
Setter for 'is_immediate' field.
:param value - a new value of 'is_immediate' field. Must be a boolean type.
'''
pass
def get_condition_expression(self):
'''
Getter for 'condition_expression' field.
:return: value of 'condition_expression' field. Must be either None (condition_expression is optional according
to BPMN 2.0 XML Schema) or String.
'''
pass
def set_condition_expression(self, value):
'''
Setter for 'condition_expression' field.
:param value - a new value of 'condition_expression' field.
'''
pass
| 10 | 10 | 9 | 0 | 5 | 4 | 2 | 1.05 | 1 | 5 | 1 | 0 | 9 | 4 | 9 | 15 | 98 | 10 | 43 | 14 | 33 | 45 | 38 | 14 | 28 | 3 | 3 | 1 | 17 |
144,098 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/bpmn_editor_import_test.py
|
bpmn_editor_import_test.BPMNEditorTests
|
class BPMNEditorTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using an example BPMN diagram created in BPMNEditor.
"""
output_directory = "./output/test-bpmneditor/"
example_path = "../examples/xml_import_export/bpmn_editor_simple_example.xml"
output_file_with_di = "BPMNEditor-example-output.xml"
output_file_no_di = "BPMNEditor-example-output-no-di.xml"
output_dot_file = "BPMNEditor-example"
output_png_file = "BPMNEditor-example"
def test_loadBPMNEditorDiagram(self):
"""
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
def test_loadBPMNEditorDiagramAndVisualize(self):
"""
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
# Uncomment line below to get a simple view of created diagram
# visualizer.visualize_diagram(bpmn_graph)
visualizer.bpmn_diagram_to_dot_file(bpmn_graph, self.output_directory + self.output_dot_file)
visualizer.bpmn_diagram_to_png(bpmn_graph, self.output_directory + self.output_png_file)
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
|
class BPMNEditorTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using an example BPMN diagram created in BPMNEditor.
'''
def test_loadBPMNEditorDiagram(self):
'''
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
'''
pass
def test_loadBPMNEditorDiagramAndVisualize(self):
'''
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
'''
pass
| 3 | 3 | 11 | 0 | 6 | 5 | 1 | 0.68 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 74 | 34 | 2 | 19 | 11 | 16 | 13 | 19 | 11 | 16 | 1 | 2 | 0 | 2 |
144,099 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_diagram_exception.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_diagram_exception.BpmnPythonError
|
class BpmnPythonError(Exception):
"""
Custom BpmnPythonError exception
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
|
class BpmnPythonError(Exception):
'''
Custom BpmnPythonError exception
'''
def __init__(self, value):
pass
def __str__(self):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.6 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 12 | 9 | 1 | 5 | 4 | 2 | 3 | 5 | 4 | 2 | 1 | 3 | 0 | 2 |
144,100 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_diagram_export.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_diagram_export.BpmnDiagramGraphExport
|
class BpmnDiagramGraphExport(object):
"""
Class BPMNDiagramGraphExport provides methods for exporting BPMNDiagramGraph into BPMN 2.0 XML file.
As a utility class, it only contains static methods.
This class is meant to be used from BPMNDiagramGraph class.
"""
def __init__(self):
pass
# String "constants" used in multiple places
bpmndi_namespace = "bpmndi:"
@staticmethod
def export_task_info(node_params, output_element):
"""
Adds Task node attributes to exported XML element
:param node_params: dictionary with given task parameters,
:param output_element: object representing BPMN XML 'task' element.
"""
if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None:
output_element.set(consts.Consts.default, node_params[consts.Consts.default])
@staticmethod
def export_subprocess_info(bpmn_diagram, subprocess_params, output_element):
"""
Adds Subprocess node attributes to exported XML element
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,
:param subprocess_params: dictionary with given subprocess parameters,
:param output_element: object representing BPMN XML 'subprocess' element.
"""
output_element.set(consts.Consts.triggered_by_event, subprocess_params[consts.Consts.triggered_by_event])
if consts.Consts.default in subprocess_params and subprocess_params[consts.Consts.default] is not None:
output_element.set(consts.Consts.default, subprocess_params[consts.Consts.default])
# for each node in graph add correct type of element, its attributes and BPMNShape element
subprocess_id = subprocess_params[consts.Consts.id]
nodes = bpmn_diagram.get_nodes_list_by_process_id(subprocess_id)
for node in nodes:
node_id = node[0]
params = node[1]
BpmnDiagramGraphExport.export_node_data(bpmn_diagram, node_id, params, output_element)
# for each edge in graph add sequence flow element, its attributes and BPMNEdge element
flows = bpmn_diagram.get_flows_list_by_process_id(subprocess_id)
for flow in flows:
params = flow[2]
BpmnDiagramGraphExport.export_flow_process_data(params, output_element)
@staticmethod
def export_data_object_info(bpmn_diagram, data_object_params, output_element):
"""
Adds DataObject node attributes to exported XML element
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,
:param data_object_params: dictionary with given subprocess parameters,
:param output_element: object representing BPMN XML 'subprocess' element.
"""
output_element.set(consts.Consts.is_collection, data_object_params[consts.Consts.is_collection])
# TODO Complex gateway not fully supported
# need to find out how sequence of conditions is represented in BPMN 2.0 XML
@staticmethod
def export_complex_gateway_info(node_params, output_element):
"""
Adds ComplexGateway node attributes to exported XML element
:param node_params: dictionary with given complex gateway parameters,
:param output_element: object representing BPMN XML 'complexGateway' element.
"""
output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])
if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None:
output_element.set(consts.Consts.default, node_params[consts.Consts.default])
@staticmethod
def export_event_based_gateway_info(node_params, output_element):
"""
Adds EventBasedGateway node attributes to exported XML element
:param node_params: dictionary with given event based gateway parameters,
:param output_element: object representing BPMN XML 'eventBasedGateway' element.
"""
output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])
output_element.set(consts.Consts.instantiate, node_params[consts.Consts.instantiate])
output_element.set(consts.Consts.event_gateway_type, node_params[consts.Consts.event_gateway_type])
@staticmethod
def export_inclusive_exclusive_gateway_info(node_params, output_element):
"""
Adds InclusiveGateway or ExclusiveGateway node attributes to exported XML element
:param node_params: dictionary with given inclusive or exclusive gateway parameters,
:param output_element: object representing BPMN XML 'inclusiveGateway'/'exclusive' element.
"""
output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])
if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None:
output_element.set(consts.Consts.default, node_params[consts.Consts.default])
@staticmethod
def export_parallel_gateway_info(node_params, output_element):
"""
Adds parallel gateway node attributes to exported XML element
:param node_params: dictionary with given parallel gateway parameters,
:param output_element: object representing BPMN XML 'parallelGateway' element.
"""
output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])
@staticmethod
def export_catch_event_info(node_params, output_element):
"""
Adds IntermediateCatchEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
"""
output_element.set(consts.Consts.parallel_multiple, node_params[consts.Consts.parallel_multiple])
definitions = node_params[consts.Consts.event_definitions]
for definition in definitions:
definition_id = definition[consts.Consts.id]
definition_type = definition[consts.Consts.definition_type]
output_definition = eTree.SubElement(output_element, definition_type)
if definition_id != "":
output_definition.set(consts.Consts.id, definition_id)
@staticmethod
def export_start_event_info(node_params, output_element):
"""
Adds StartEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
"""
output_element.set(consts.Consts.parallel_multiple, node_params.get(consts.Consts.parallel_multiple))
output_element.set(consts.Consts.is_interrupting, node_params.get(consts.Consts.is_interrupting))
definitions = node_params.get(consts.Consts.event_definitions)
for definition in definitions:
definition_id = definition[consts.Consts.id]
definition_type = definition[consts.Consts.definition_type]
output_definition = eTree.SubElement(output_element, definition_type)
if definition_id != "":
output_definition.set(consts.Consts.id, definition_id)
@staticmethod
def export_throw_event_info(node_params, output_element):
"""
Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element
:param node_params: dictionary with given intermediate throw event parameters,
:param output_element: object representing BPMN XML 'intermediateThrowEvent' element.
"""
definitions = node_params[consts.Consts.event_definitions]
for definition in definitions:
definition_id = definition[consts.Consts.id]
definition_type = definition[consts.Consts.definition_type]
output_definition = eTree.SubElement(output_element, definition_type)
if definition_id != "":
output_definition.set(consts.Consts.id, definition_id)
@staticmethod
def export_boundary_event_info(node_params, output_element):
"""
Adds IntermediateCatchEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
"""
output_element.set(consts.Consts.parallel_multiple, node_params[consts.Consts.parallel_multiple])
output_element.set(consts.Consts.cancel_activity, node_params[consts.Consts.cancel_activity])
output_element.set(consts.Consts.attached_to_ref, node_params[consts.Consts.attached_to_ref])
definitions = node_params[consts.Consts.event_definitions]
for definition in definitions:
definition_id = definition[consts.Consts.id]
definition_type = definition[consts.Consts.definition_type]
output_definition = eTree.SubElement(output_element, definition_type)
if definition_id != "":
output_definition.set(consts.Consts.id, definition_id)
@staticmethod
def export_definitions_element():
"""
Creates root element ('definitions') for exported BPMN XML file.
:return: definitions XML element.
"""
root = eTree.Element(consts.Consts.definitions)
root.set("xmlns", "http://www.omg.org/spec/BPMN/20100524/MODEL")
root.set("xmlns:bpmndi", "http://www.omg.org/spec/BPMN/20100524/DI")
root.set("xmlns:omgdc", "http://www.omg.org/spec/DD/20100524/DC")
root.set("xmlns:omgdi", "http://www.omg.org/spec/DD/20100524/DI")
root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
root.set("targetNamespace", "http://www.signavio.com/bpmn20")
root.set("typeLanguage", "http://www.w3.org/2001/XMLSchema")
root.set("expressionLanguage", "http://www.w3.org/1999/XPath")
root.set("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
return root
@staticmethod
def export_process_element(definitions, process_id, process_attributes_dictionary):
"""
Creates process element for exported BPMN XML file.
:param process_id: string object. ID of exported process element,
:param definitions: an XML element ('definitions'), root element of BPMN 2.0 document
:param process_attributes_dictionary: dictionary that holds attribute values of 'process' element
:return: process XML element
"""
process = eTree.SubElement(definitions, consts.Consts.process)
process.set(consts.Consts.id, process_id)
process.set(consts.Consts.is_closed, process_attributes_dictionary[consts.Consts.is_closed])
process.set(consts.Consts.is_executable, process_attributes_dictionary[consts.Consts.is_executable])
process.set(consts.Consts.process_type, process_attributes_dictionary[consts.Consts.process_type])
return process
@staticmethod
def export_lane_set(process, lane_set, plane_element):
"""
Creates 'laneSet' element for exported BPMN XML file.
:param process: an XML element ('process'), from exported BPMN 2.0 document,
:param lane_set: dictionary with exported 'laneSet' element attributes and child elements,
:param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
"""
lane_set_xml = eTree.SubElement(process, consts.Consts.lane_set)
for key, value in lane_set[consts.Consts.lanes].items():
BpmnDiagramGraphExport.export_lane(lane_set_xml, key, value, plane_element)
@staticmethod
def export_child_lane_set(parent_xml_element, child_lane_set, plane_element):
"""
Creates 'childLaneSet' element for exported BPMN XML file.
:param parent_xml_element: an XML element, parent of exported 'childLaneSet' element,
:param child_lane_set: dictionary with exported 'childLaneSet' element attributes and child elements,
:param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
"""
lane_set_xml = eTree.SubElement(parent_xml_element, consts.Consts.lane_set)
for key, value in child_lane_set[consts.Consts.lanes].items():
BpmnDiagramGraphExport.export_lane(lane_set_xml, key, value, plane_element)
@staticmethod
def export_lane(parent_xml_element, lane_id, lane_attr, plane_element):
"""
Creates 'lane' element for exported BPMN XML file.
:param parent_xml_element: an XML element, parent of exported 'lane' element,
:param lane_id: string object. ID of exported lane element,
:param lane_attr: dictionary with lane element attributes,
:param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
"""
lane_xml = eTree.SubElement(parent_xml_element, consts.Consts.lane)
lane_xml.set(consts.Consts.id, lane_id)
lane_xml.set(consts.Consts.name, lane_attr[consts.Consts.name])
if consts.Consts.child_lane_set in lane_attr and len(lane_attr[consts.Consts.child_lane_set]):
child_lane_set = lane_attr[consts.Consts.child_lane_set]
BpmnDiagramGraphExport.export_child_lane_set(lane_xml, child_lane_set, plane_element)
if consts.Consts.flow_node_refs in lane_attr and len(lane_attr[consts.Consts.flow_node_refs]):
for flow_node_ref_id in lane_attr[consts.Consts.flow_node_refs]:
flow_node_ref_xml = eTree.SubElement(lane_xml, consts.Consts.flow_node_ref)
flow_node_ref_xml.text = flow_node_ref_id
output_element_di = eTree.SubElement(plane_element, BpmnDiagramGraphExport.bpmndi_namespace +
consts.Consts.bpmn_shape)
output_element_di.set(consts.Consts.id, lane_id + "_gui")
output_element_di.set(consts.Consts.bpmn_element, lane_id)
output_element_di.set(consts.Consts.is_horizontal, lane_attr[consts.Consts.is_horizontal])
bounds = eTree.SubElement(output_element_di, "omgdc:Bounds")
bounds.set(consts.Consts.width, lane_attr[consts.Consts.width])
bounds.set(consts.Consts.height, lane_attr[consts.Consts.height])
bounds.set(consts.Consts.x, lane_attr[consts.Consts.x])
bounds.set(consts.Consts.y, lane_attr[consts.Consts.y])
@staticmethod
def export_diagram_plane_elements(root, diagram_attributes, plane_attributes):
"""
Creates 'diagram' and 'plane' elements for exported BPMN XML file.
Returns a tuple (diagram, plane).
:param root: object of Element class, representing a BPMN XML root element ('definitions'),
:param diagram_attributes: dictionary that holds attribute values for imported 'BPMNDiagram' element,
:param plane_attributes: dictionary that holds attribute values for imported 'BPMNPlane' element.
"""
diagram = eTree.SubElement(root, BpmnDiagramGraphExport.bpmndi_namespace + "BPMNDiagram")
diagram.set(consts.Consts.id, diagram_attributes[consts.Consts.id])
diagram.set(consts.Consts.name, diagram_attributes[consts.Consts.name])
plane = eTree.SubElement(diagram, BpmnDiagramGraphExport.bpmndi_namespace + "BPMNPlane")
plane.set(consts.Consts.id, plane_attributes[consts.Consts.id])
plane.set(consts.Consts.bpmn_element, plane_attributes[consts.Consts.bpmn_element])
return diagram, plane
@staticmethod
def export_node_data(bpmn_diagram, process_id, params, process):
"""
Creates a new XML element (depends on node type) for given node parameters and adds it to 'process' element.
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,
:param process_id: string representing ID of given flow node,
:param params: dictionary with node parameters,
:param process: object of Element class, representing BPMN XML 'process' element (root for nodes).
"""
node_type = params[consts.Consts.type]
output_element = eTree.SubElement(process, node_type)
output_element.set(consts.Consts.id, process_id)
output_element.set(consts.Consts.name, params[consts.Consts.node_name])
for incoming in params[consts.Consts.incoming_flow]:
incoming_element = eTree.SubElement(output_element, consts.Consts.incoming_flow)
incoming_element.text = incoming
for outgoing in params[consts.Consts.outgoing_flow]:
outgoing_element = eTree.SubElement(output_element, consts.Consts.outgoing_flow)
outgoing_element.text = outgoing
if node_type == consts.Consts.task \
or node_type == consts.Consts.user_task \
or node_type == consts.Consts.service_task \
or node_type == consts.Consts.manual_task:
BpmnDiagramGraphExport.export_task_info(params, output_element)
elif node_type == consts.Consts.subprocess:
BpmnDiagramGraphExport.export_subprocess_info(bpmn_diagram, params, output_element)
elif node_type == consts.Consts.data_object:
BpmnDiagramGraphExport.export_data_object_info(bpmn_diagram, params, output_element)
elif node_type == consts.Consts.complex_gateway:
BpmnDiagramGraphExport.export_complex_gateway_info(params, output_element)
elif node_type == consts.Consts.event_based_gateway:
BpmnDiagramGraphExport.export_event_based_gateway_info(params, output_element)
elif node_type == consts.Consts.inclusive_gateway or node_type == consts.Consts.exclusive_gateway:
BpmnDiagramGraphExport.export_inclusive_exclusive_gateway_info(params, output_element)
elif node_type == consts.Consts.parallel_gateway:
BpmnDiagramGraphExport.export_parallel_gateway_info(params, output_element)
elif node_type == consts.Consts.start_event:
BpmnDiagramGraphExport.export_start_event_info(params, output_element)
elif node_type == consts.Consts.intermediate_catch_event:
BpmnDiagramGraphExport.export_catch_event_info(params, output_element)
elif node_type == consts.Consts.end_event or node_type == consts.Consts.intermediate_throw_event:
BpmnDiagramGraphExport.export_throw_event_info(params, output_element)
elif node_type == consts.Consts.boundary_event:
BpmnDiagramGraphExport.export_boundary_event_info(params, output_element)
@staticmethod
def export_node_di_data(node_id, params, plane):
"""
Creates a new BPMNShape XML element for given node parameters and adds it to 'plane' element.
:param node_id: string representing ID of given flow node,
:param params: dictionary with node parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for node DI data).
"""
output_element_di = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_shape)
output_element_di.set(consts.Consts.id, node_id + "_gui")
output_element_di.set(consts.Consts.bpmn_element, node_id)
bounds = eTree.SubElement(output_element_di, "omgdc:Bounds")
bounds.set(consts.Consts.width, params[consts.Consts.width])
bounds.set(consts.Consts.height, params[consts.Consts.height])
bounds.set(consts.Consts.x, params[consts.Consts.x])
bounds.set(consts.Consts.y, params[consts.Consts.y])
if params[consts.Consts.type] == consts.Consts.subprocess:
output_element_di.set(consts.Consts.is_expanded, params[consts.Consts.is_expanded])
@staticmethod
def export_flow_process_data(params, process):
"""
Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element.
:param params: dictionary with edge parameters,
:param process: object of Element class, representing BPMN XML 'process' element (root for sequence flows)
"""
output_flow = eTree.SubElement(process, consts.Consts.sequence_flow)
output_flow.set(consts.Consts.id, params[consts.Consts.id])
output_flow.set(consts.Consts.name, params[consts.Consts.name])
output_flow.set(consts.Consts.source_ref, params[consts.Consts.source_ref])
output_flow.set(consts.Consts.target_ref, params[consts.Consts.target_ref])
if consts.Consts.condition_expression in params:
condition_expression_params = params[consts.Consts.condition_expression]
condition_expression = eTree.SubElement(output_flow, consts.Consts.condition_expression)
condition_expression.set(consts.Consts.id, condition_expression_params[consts.Consts.id])
condition_expression.set(consts.Consts.id, condition_expression_params[consts.Consts.id])
condition_expression.text = condition_expression_params[consts.Consts.condition_expression]
output_flow.set(consts.Consts.name, condition_expression_params[consts.Consts.condition_expression])
@staticmethod
def export_flow_di_data(params, plane):
"""
Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element.
:param params: dictionary with edge parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI data).
"""
output_flow = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_edge)
output_flow.set(consts.Consts.id, params[consts.Consts.id] + "_gui")
output_flow.set(consts.Consts.bpmn_element, params[consts.Consts.id])
waypoints = params[consts.Consts.waypoints]
for waypoint in waypoints:
waypoint_element = eTree.SubElement(output_flow, "omgdi:waypoint")
waypoint_element.set(consts.Consts.x, waypoint[0])
waypoint_element.set(consts.Consts.y, waypoint[1])
@staticmethod
def export_xml_file(directory, filename, bpmn_diagram):
"""
Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).
:param directory: string representing output directory,
:param filename: string representing output file name,
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram.
"""
diagram_attributes = bpmn_diagram.diagram_attributes
plane_attributes = bpmn_diagram.plane_attributes
collaboration = bpmn_diagram.collaboration
process_elements_dict = bpmn_diagram.process_elements
definitions = BpmnDiagramGraphExport.export_definitions_element()
[_, plane] = BpmnDiagramGraphExport.export_diagram_plane_elements(definitions, diagram_attributes,
plane_attributes)
if collaboration is not None and len(collaboration) > 0:
message_flows = collaboration[consts.Consts.message_flows]
participants = collaboration[consts.Consts.participants]
collaboration_xml = eTree.SubElement(definitions, consts.Consts.collaboration)
collaboration_xml.set(consts.Consts.id, collaboration[consts.Consts.id])
for message_flow_id, message_flow_attr in message_flows.items():
message_flow = eTree.SubElement(collaboration_xml, consts.Consts.message_flow)
message_flow.set(consts.Consts.id, message_flow_id)
message_flow.set(consts.Consts.name, message_flow_attr[consts.Consts.name])
message_flow.set(consts.Consts.source_ref, message_flow_attr[consts.Consts.source_ref])
message_flow.set(consts.Consts.target_ref, message_flow_attr[consts.Consts.target_ref])
message_flow_params = bpmn_diagram.get_flow_by_id(message_flow_id)[2]
output_flow = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_edge)
output_flow.set(consts.Consts.id, message_flow_id + "_gui")
output_flow.set(consts.Consts.bpmn_element, message_flow_id)
waypoints = message_flow_params[consts.Consts.waypoints]
for waypoint in waypoints:
waypoint_element = eTree.SubElement(output_flow, "omgdi:waypoint")
waypoint_element.set(consts.Consts.x, waypoint[0])
waypoint_element.set(consts.Consts.y, waypoint[1])
for participant_id, participant_attr in participants.items():
participant = eTree.SubElement(collaboration_xml, consts.Consts.participant)
participant.set(consts.Consts.id, participant_id)
participant.set(consts.Consts.name, participant_attr[consts.Consts.name])
participant.set(consts.Consts.process_ref, participant_attr[consts.Consts.process_ref])
output_element_di = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace +
consts.Consts.bpmn_shape)
output_element_di.set(consts.Consts.id, participant_id + "_gui")
output_element_di.set(consts.Consts.bpmn_element, participant_id)
output_element_di.set(consts.Consts.is_horizontal, participant_attr[consts.Consts.is_horizontal])
bounds = eTree.SubElement(output_element_di, "omgdc:Bounds")
bounds.set(consts.Consts.width, participant_attr[consts.Consts.width])
bounds.set(consts.Consts.height, participant_attr[consts.Consts.height])
bounds.set(consts.Consts.x, participant_attr[consts.Consts.x])
bounds.set(consts.Consts.y, participant_attr[consts.Consts.y])
for process_id in process_elements_dict:
process_element_attr = process_elements_dict[process_id]
process = BpmnDiagramGraphExport.export_process_element(definitions, process_id, process_element_attr)
if consts.Consts.lane_set in process_element_attr:
BpmnDiagramGraphExport.export_lane_set(process, process_element_attr[consts.Consts.lane_set], plane)
# for each node in graph add correct type of element, its attributes and BPMNShape element
nodes = bpmn_diagram.get_nodes_list_by_process_id(process_id)
for node in nodes:
node_id = node[0]
params = node[1]
BpmnDiagramGraphExport.export_node_data(bpmn_diagram, node_id, params, process)
# BpmnDiagramGraphExport.export_node_di_data(node_id, params, plane)
# for each edge in graph add sequence flow element, its attributes and BPMNEdge element
flows = bpmn_diagram.get_flows_list_by_process_id(process_id)
for flow in flows:
params = flow[2]
BpmnDiagramGraphExport.export_flow_process_data(params, process)
# BpmnDiagramGraphExport.export_flow_di_data(params, plane)
# Export DI data
nodes = bpmn_diagram.get_nodes()
for node in nodes:
node_id = node[0]
params = node[1]
BpmnDiagramGraphExport.export_node_di_data(node_id, params, plane)
flows = bpmn_diagram.get_flows()
for flow in flows:
params = flow[2]
BpmnDiagramGraphExport.export_flow_di_data(params, plane)
BpmnDiagramGraphExport.indent(definitions)
tree = eTree.ElementTree(definitions)
try:
os.makedirs(directory)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
tree.write(directory + filename, encoding='utf-8', xml_declaration=True)
@staticmethod
def export_xml_file_no_di(directory, filename, bpmn_diagram):
"""
Exports diagram inner graph to BPMN 2.0 XML file (without Diagram Interchange data).
:param directory: string representing output directory,
:param filename: string representing output file name,
:param bpmn_diagram: BPMNDiagramGraph class instance representing a BPMN process diagram.
"""
diagram_graph = bpmn_diagram.diagram_graph
process_elements_dict = bpmn_diagram.process_elements
definitions = BpmnDiagramGraphExport.export_definitions_element()
for process_id in process_elements_dict:
process_element_attr = process_elements_dict[process_id]
process = BpmnDiagramGraphExport.export_process_element(definitions, process_id, process_element_attr)
# for each node in graph add correct type of element, its attributes and BPMNShape element
nodes = diagram_graph.nodes(data=True)
for node in nodes:
node_id = node[0]
params = node[1]
BpmnDiagramGraphExport.export_node_data(bpmn_diagram, node_id, params, process)
# for each edge in graph add sequence flow element, its attributes and BPMNEdge element
flows = diagram_graph.edges(data=True)
for flow in flows:
params = flow[2]
BpmnDiagramGraphExport.export_flow_process_data(params, process)
BpmnDiagramGraphExport.indent(definitions)
tree = eTree.ElementTree(definitions)
try:
os.makedirs(directory)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
tree.write(directory + filename, encoding='utf-8', xml_declaration=True)
# Helper methods
@staticmethod
def indent(elem, level=0):
"""
Helper function, adds indentation to XML output.
:param elem: object of Element class, representing element to which method adds intendation,
:param level: current level of intendation.
"""
i = "\n" + level * " "
j = "\n" + (level - 1) * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
BpmnDiagramGraphExport.indent(subelem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
|
class BpmnDiagramGraphExport(object):
'''
Class BPMNDiagramGraphExport provides methods for exporting BPMNDiagramGraph into BPMN 2.0 XML file.
As a utility class, it only contains static methods.
This class is meant to be used from BPMNDiagramGraph class.
'''
def __init__(self):
pass
@staticmethod
def export_task_info(node_params, output_element):
'''
Adds Task node attributes to exported XML element
:param node_params: dictionary with given task parameters,
:param output_element: object representing BPMN XML 'task' element.
'''
pass
@staticmethod
def export_subprocess_info(bpmn_diagram, subprocess_params, output_element):
'''
Adds Subprocess node attributes to exported XML element
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,
:param subprocess_params: dictionary with given subprocess parameters,
:param output_element: object representing BPMN XML 'subprocess' element.
'''
pass
@staticmethod
def export_data_object_info(bpmn_diagram, data_object_params, output_element):
'''
Adds DataObject node attributes to exported XML element
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,
:param data_object_params: dictionary with given subprocess parameters,
:param output_element: object representing BPMN XML 'subprocess' element.
'''
pass
@staticmethod
def export_complex_gateway_info(node_params, output_element):
'''
Adds ComplexGateway node attributes to exported XML element
:param node_params: dictionary with given complex gateway parameters,
:param output_element: object representing BPMN XML 'complexGateway' element.
'''
pass
@staticmethod
def export_event_based_gateway_info(node_params, output_element):
'''
Adds EventBasedGateway node attributes to exported XML element
:param node_params: dictionary with given event based gateway parameters,
:param output_element: object representing BPMN XML 'eventBasedGateway' element.
'''
pass
@staticmethod
def export_inclusive_exclusive_gateway_info(node_params, output_element):
'''
Adds InclusiveGateway or ExclusiveGateway node attributes to exported XML element
:param node_params: dictionary with given inclusive or exclusive gateway parameters,
:param output_element: object representing BPMN XML 'inclusiveGateway'/'exclusive' element.
'''
pass
@staticmethod
def export_parallel_gateway_info(node_params, output_element):
'''
Adds parallel gateway node attributes to exported XML element
:param node_params: dictionary with given parallel gateway parameters,
:param output_element: object representing BPMN XML 'parallelGateway' element.
'''
pass
@staticmethod
def export_catch_event_info(node_params, output_element):
'''
Adds IntermediateCatchEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
'''
pass
@staticmethod
def export_start_event_info(node_params, output_element):
'''
Adds StartEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
'''
pass
@staticmethod
def export_throw_event_info(node_params, output_element):
'''
Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element
:param node_params: dictionary with given intermediate throw event parameters,
:param output_element: object representing BPMN XML 'intermediateThrowEvent' element.
'''
pass
@staticmethod
def export_boundary_event_info(node_params, output_element):
'''
Adds IntermediateCatchEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
'''
pass
@staticmethod
def export_definitions_element():
'''
Creates root element ('definitions') for exported BPMN XML file.
:return: definitions XML element.
'''
pass
@staticmethod
def export_process_element(definitions, process_id, process_attributes_dictionary):
'''
Creates process element for exported BPMN XML file.
:param process_id: string object. ID of exported process element,
:param definitions: an XML element ('definitions'), root element of BPMN 2.0 document
:param process_attributes_dictionary: dictionary that holds attribute values of 'process' element
:return: process XML element
'''
pass
@staticmethod
def export_lane_set(process, lane_set, plane_element):
'''
Creates 'laneSet' element for exported BPMN XML file.
:param process: an XML element ('process'), from exported BPMN 2.0 document,
:param lane_set: dictionary with exported 'laneSet' element attributes and child elements,
:param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
'''
pass
@staticmethod
def export_child_lane_set(parent_xml_element, child_lane_set, plane_element):
'''
Creates 'childLaneSet' element for exported BPMN XML file.
:param parent_xml_element: an XML element, parent of exported 'childLaneSet' element,
:param child_lane_set: dictionary with exported 'childLaneSet' element attributes and child elements,
:param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
'''
pass
@staticmethod
def export_lane_set(process, lane_set, plane_element):
'''
Creates 'lane' element for exported BPMN XML file.
:param parent_xml_element: an XML element, parent of exported 'lane' element,
:param lane_id: string object. ID of exported lane element,
:param lane_attr: dictionary with lane element attributes,
:param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
'''
pass
@staticmethod
def export_diagram_plane_elements(root, diagram_attributes, plane_attributes):
'''
Creates 'diagram' and 'plane' elements for exported BPMN XML file.
Returns a tuple (diagram, plane).
:param root: object of Element class, representing a BPMN XML root element ('definitions'),
:param diagram_attributes: dictionary that holds attribute values for imported 'BPMNDiagram' element,
:param plane_attributes: dictionary that holds attribute values for imported 'BPMNPlane' element.
'''
pass
@staticmethod
def export_node_data(bpmn_diagram, process_id, params, process):
'''
Creates a new XML element (depends on node type) for given node parameters and adds it to 'process' element.
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,
:param process_id: string representing ID of given flow node,
:param params: dictionary with node parameters,
:param process: object of Element class, representing BPMN XML 'process' element (root for nodes).
'''
pass
@staticmethod
def export_node_di_data(node_id, params, plane):
'''
Creates a new BPMNShape XML element for given node parameters and adds it to 'plane' element.
:param node_id: string representing ID of given flow node,
:param params: dictionary with node parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for node DI data).
'''
pass
@staticmethod
def export_flow_process_data(params, process):
'''
Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element.
:param params: dictionary with edge parameters,
:param process: object of Element class, representing BPMN XML 'process' element (root for sequence flows)
'''
pass
@staticmethod
def export_flow_di_data(params, plane):
'''
Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element.
:param params: dictionary with edge parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI data).
'''
pass
@staticmethod
def export_xml_file(directory, filename, bpmn_diagram):
'''
Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).
:param directory: string representing output directory,
:param filename: string representing output file name,
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram.
'''
pass
@staticmethod
def export_xml_file_no_di(directory, filename, bpmn_diagram):
'''
Exports diagram inner graph to BPMN 2.0 XML file (without Diagram Interchange data).
:param directory: string representing output directory,
:param filename: string representing output file name,
:param bpmn_diagram: BPMNDiagramGraph class instance representing a BPMN process diagram.
'''
pass
@staticmethod
def indent(elem, level=0):
'''
Helper function, adds indentation to XML output.
:param elem: object of Element class, representing element to which method adds intendation,
:param level: current level of intendation.
'''
pass
| 50 | 25 | 20 | 2 | 12 | 6 | 3 | 0.45 | 1 | 4 | 1 | 0 | 1 | 0 | 25 | 25 | 567 | 77 | 338 | 154 | 288 | 152 | 297 | 128 | 271 | 14 | 1 | 3 | 83 |
144,101 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_diagram_import.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_diagram_import.BpmnDiagramGraphImport
|
class BpmnDiagramGraphImport(object):
"""
Class BPMNDiagramGraphImport provides methods for importing BPMN 2.0 XML file.
As a utility class, it only contains static methods. This class is meant to be used from BPMNDiagramGraph class.
"""
def __init__(self):
pass
@staticmethod
def load_diagram_from_xml(filepath, bpmn_diagram):
"""
Reads an XML file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath,
:param bpmn_diagram: an instance of BpmnDiagramGraph class.
"""
diagram_graph = bpmn_diagram.diagram_graph
sequence_flows = bpmn_diagram.sequence_flows
process_elements_dict = bpmn_diagram.process_elements
diagram_attributes = bpmn_diagram.diagram_attributes
plane_attributes = bpmn_diagram.plane_attributes
collaboration = bpmn_diagram.collaboration
document = BpmnDiagramGraphImport.read_xml_file(filepath)
# According to BPMN 2.0 XML Schema, there's only one 'BPMNDiagram' and 'BPMNPlane'
diagram_element = document.getElementsByTagNameNS("*", "BPMNDiagram")[0]
plane_element = diagram_element.getElementsByTagNameNS("*", "BPMNPlane")[0]
BpmnDiagramGraphImport.import_diagram_and_plane_attributes(diagram_attributes, plane_attributes,
diagram_element, plane_element)
BpmnDiagramGraphImport.import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict,
plane_element)
collaboration_element_list = document.getElementsByTagNameNS("*", consts.Consts.collaboration)
if collaboration_element_list is not None and len(collaboration_element_list) > 0:
# Diagram has multiple pools and lanes
collaboration_element = collaboration_element_list[0]
BpmnDiagramGraphImport.import_collaboration_element(diagram_graph, collaboration_element, collaboration)
if consts.Consts.message_flows in collaboration:
message_flows = collaboration[consts.Consts.message_flows]
else:
message_flows = {}
participants = []
if consts.Consts.participants in collaboration:
participants = collaboration[consts.Consts.participants]
for element in utils.BpmnImportUtils.iterate_elements(plane_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
if tag_name == consts.Consts.bpmn_shape:
BpmnDiagramGraphImport.import_shape_di(participants, diagram_graph, element)
elif tag_name == consts.Consts.bpmn_edge:
BpmnDiagramGraphImport.import_flow_di(diagram_graph, sequence_flows, message_flows, element)
@staticmethod
def import_collaboration_element(diagram_graph, collaboration_element, collaboration_dict):
"""
Method that imports information from 'collaboration' element.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param collaboration_element: XML doument element,
:param collaboration_dict: dictionary, that consist all information imported from 'collaboration' element.
Includes three key-value pairs - 'id' which keeps ID of collaboration element, 'participants' that keeps
information about 'participant' elements and 'message_flows' that keeps information about message flows.
"""
collaboration_dict[consts.Consts.id] = collaboration_element.getAttribute(consts.Consts.id)
collaboration_dict[consts.Consts.participants] = {}
participants_dict = collaboration_dict[consts.Consts.participants]
collaboration_dict[consts.Consts.message_flows] = {}
message_flows_dict = collaboration_dict[consts.Consts.message_flows]
for element in utils.BpmnImportUtils.iterate_elements(collaboration_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
if tag_name == consts.Consts.participant:
BpmnDiagramGraphImport.import_participant_element(diagram_graph, participants_dict, element)
elif tag_name == consts.Consts.message_flow:
BpmnDiagramGraphImport.import_message_flow_to_graph(diagram_graph, message_flows_dict, element)
@staticmethod
def import_participant_element(diagram_graph, participants_dictionary, participant_element):
"""
Adds 'participant' element to the collaboration dictionary.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param participants_dictionary: dictionary with participant element attributes. Key is participant ID, value
is a dictionary of participant attributes,
:param participant_element: object representing a BPMN XML 'participant' element.
"""
participant_id = participant_element.getAttribute(consts.Consts.id)
name = participant_element.getAttribute(consts.Consts.name)
process_ref = participant_element.getAttribute(consts.Consts.process_ref)
if participant_element.getAttribute(consts.Consts.process_ref) == '':
diagram_graph.add_node(participant_id)
diagram_graph.node[participant_id][consts.Consts.type] = consts.Consts.participant
diagram_graph.node[participant_id][consts.Consts.process] = participant_id
participants_dictionary[participant_id] = {consts.Consts.name: name, consts.Consts.process_ref: process_ref}
@staticmethod
def import_diagram_and_plane_attributes(diagram_attributes, plane_attributes, diagram_element, plane_element):
"""
Adds attributes of BPMN diagram and plane elements to appropriate
fields diagram_attributes and plane_attributes.
Diagram inner representation contains following diagram element attributes:
- id - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
- name - optional parameter, empty string by default,
Diagram inner representation contains following plane element attributes:
- id - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
- bpmnElement - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
:param diagram_attributes: dictionary that holds attribute values for imported 'BPMNDiagram' element,
:param plane_attributes: dictionary that holds attribute values for imported 'BPMNPlane' element,
:param diagram_element: object representing a BPMN XML 'diagram' element,
:param plane_element: object representing a BPMN XML 'plane' element.
"""
diagram_attributes[consts.Consts.id] = diagram_element.getAttribute(consts.Consts.id)
diagram_attributes[consts.Consts.name] = diagram_element.getAttribute(consts.Consts.name) \
if diagram_element.hasAttribute(consts.Consts.name) else ""
plane_attributes[consts.Consts.id] = plane_element.getAttribute(consts.Consts.id)
plane_attributes[consts.Consts.bpmn_element] = plane_element.getAttribute(consts.Consts.bpmn_element)
@staticmethod
def import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element):
"""
Method for importing all 'process' elements in diagram.
:param document: XML document,
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: a list of sequence flows existing in diagram,
:param process_elements_dict: dictionary that holds attribute values for imported 'process' elements. Key is
an ID of process, value - a dictionary of process attributes,
:param plane_element: object representing a BPMN XML 'plane' element.
"""
for process_element in document.getElementsByTagNameNS("*", consts.Consts.process):
BpmnDiagramGraphImport.import_process_element(process_elements_dict, process_element)
process_id = process_element.getAttribute(consts.Consts.id)
process_attributes = process_elements_dict[process_id]
lane_set_list = process_element.getElementsByTagNameNS("*", consts.Consts.lane_set)
if lane_set_list is not None and len(lane_set_list) > 0:
# according to BPMN 2.0 XML Schema, there's at most one 'laneSet' element inside 'process'
lane_set = lane_set_list[0]
BpmnDiagramGraphImport.import_lane_set_element(process_attributes, lane_set, plane_element)
for element in utils.BpmnImportUtils.iterate_elements(process_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
BpmnDiagramGraphImport.__import_element_by_tag_name(diagram_graph, sequence_flows, process_id,
process_attributes, element, tag_name)
for flow in utils.BpmnImportUtils.iterate_elements(process_element):
if flow.nodeType != flow.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(flow.tagName)
if tag_name == consts.Consts.sequence_flow:
BpmnDiagramGraphImport.import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id,
flow)
@staticmethod
def __import_element_by_tag_name(diagram_graph, sequence_flows, process_id, process_attributes, element, tag_name):
if tag_name == consts.Consts.task \
or tag_name == consts.Consts.user_task \
or tag_name == consts.Consts.service_task \
or tag_name == consts.Consts.manual_task:
BpmnDiagramGraphImport.import_task_to_graph(diagram_graph, process_id, process_attributes, element)
elif tag_name == consts.Consts.subprocess:
BpmnDiagramGraphImport.import_subprocess_to_graph(diagram_graph, sequence_flows, process_id,
process_attributes, element)
elif tag_name == consts.Consts.data_object:
BpmnDiagramGraphImport.import_data_object_to_graph(diagram_graph, process_id, process_attributes, element)
elif tag_name == consts.Consts.inclusive_gateway or tag_name == consts.Consts.exclusive_gateway:
BpmnDiagramGraphImport.import_incl_or_excl_gateway_to_graph(diagram_graph, process_id, process_attributes,
element)
elif tag_name == consts.Consts.parallel_gateway:
BpmnDiagramGraphImport.import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes,
element)
elif tag_name == consts.Consts.event_based_gateway:
BpmnDiagramGraphImport.import_event_based_gateway_to_graph(diagram_graph, process_id, process_attributes,
element)
elif tag_name == consts.Consts.complex_gateway:
BpmnDiagramGraphImport.import_complex_gateway_to_graph(diagram_graph, process_id, process_attributes,
element)
elif tag_name == consts.Consts.start_event:
BpmnDiagramGraphImport.import_start_event_to_graph(diagram_graph, process_id, process_attributes, element)
elif tag_name == consts.Consts.end_event:
BpmnDiagramGraphImport.import_end_event_to_graph(diagram_graph, process_id, process_attributes, element)
elif tag_name == consts.Consts.intermediate_catch_event:
BpmnDiagramGraphImport.import_intermediate_catch_event_to_graph(diagram_graph, process_id,
process_attributes, element)
elif tag_name == consts.Consts.intermediate_throw_event:
BpmnDiagramGraphImport.import_intermediate_throw_event_to_graph(diagram_graph, process_id,
process_attributes, element)
elif tag_name == consts.Consts.boundary_event:
BpmnDiagramGraphImport.import_boundary_event_to_graph(diagram_graph, process_id, process_attributes,
element)
@staticmethod
def import_lane_set_element(process_attributes, lane_set_element, plane_element):
"""
Method for importing 'laneSet' element from diagram file.
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param lane_set_element: XML document element,
:param plane_element: object representing a BPMN XML 'plane' element.
"""
lane_set_id = lane_set_element.getAttribute(consts.Consts.id)
lanes_attr = {}
for element in utils.BpmnImportUtils.iterate_elements(lane_set_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
if tag_name == consts.Consts.lane:
lane = element
lane_id = lane.getAttribute(consts.Consts.id)
lane_attr = BpmnDiagramGraphImport.import_lane_element(lane, plane_element)
lanes_attr[lane_id] = lane_attr
lane_set_attr = {consts.Consts.id: lane_set_id, consts.Consts.lanes: lanes_attr}
process_attributes[consts.Consts.lane_set] = lane_set_attr
@staticmethod
def import_child_lane_set_element(child_lane_set_element, plane_element):
"""
Method for importing 'childLaneSet' element from diagram file.
:param child_lane_set_element: XML document element,
:param plane_element: object representing a BPMN XML 'plane' element.
"""
lane_set_id = child_lane_set_element.getAttribute(consts.Consts.id)
lanes_attr = {}
for element in utils.BpmnImportUtils.iterate_elements(child_lane_set_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
if tag_name == consts.Consts.lane:
lane = element
lane_id = lane.getAttribute(consts.Consts.id)
lane_attr = BpmnDiagramGraphImport.import_lane_element(lane, plane_element)
lanes_attr[lane_id] = lane_attr
child_lane_set_attr = {consts.Consts.id: lane_set_id, consts.Consts.lanes: lanes_attr}
return child_lane_set_attr
@staticmethod
def import_lane_element(lane_element, plane_element):
"""
Method for importing 'laneSet' element from diagram file.
:param lane_element: XML document element,
:param plane_element: object representing a BPMN XML 'plane' element.
"""
lane_id = lane_element.getAttribute(consts.Consts.id)
lane_name = lane_element.getAttribute(consts.Consts.name)
child_lane_set_attr = {}
flow_node_refs = []
for element in utils.BpmnImportUtils.iterate_elements(lane_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
if tag_name == consts.Consts.child_lane_set:
child_lane_set_attr = BpmnDiagramGraphImport.import_child_lane_set_element(element, plane_element)
elif tag_name == consts.Consts.flow_node_ref:
flow_node_ref_id = element.firstChild.nodeValue
flow_node_refs.append(flow_node_ref_id)
lane_attr = {consts.Consts.id: lane_id, consts.Consts.name: lane_name,
consts.Consts.child_lane_set: child_lane_set_attr,
consts.Consts.flow_node_refs: flow_node_refs}
shape_element = None
for element in utils.BpmnImportUtils.iterate_elements(plane_element):
if element.nodeType != element.TEXT_NODE and element.getAttribute(consts.Consts.bpmn_element) == lane_id:
shape_element = element
if shape_element is not None:
bounds = shape_element.getElementsByTagNameNS("*", "Bounds")[0]
lane_attr[consts.Consts.is_horizontal] = shape_element.getAttribute(consts.Consts.is_horizontal)
lane_attr[consts.Consts.width] = bounds.getAttribute(consts.Consts.width)
lane_attr[consts.Consts.height] = bounds.getAttribute(consts.Consts.height)
lane_attr[consts.Consts.x] = bounds.getAttribute(consts.Consts.x)
lane_attr[consts.Consts.y] = bounds.getAttribute(consts.Consts.y)
return lane_attr
@staticmethod
def import_process_element(process_elements_dict, process_element):
"""
Adds attributes of BPMN process element to appropriate field process_attributes.
Diagram inner representation contains following process attributes:
- id - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
- isClosed - optional parameter, default value 'false',
- isExecutable - optional parameter, default value 'false',
- processType - optional parameter, default value 'None',
- node_ids - list of flow nodes IDs, associated with given process.
:param process_elements_dict: dictionary that holds attribute values for imported 'process' element. Key is
process ID, value is a dictionary of attributes,
:param process_element: object representing a BPMN XML 'process' element.
"""
process_id = process_element.getAttribute(consts.Consts.id)
process_element_attributes = {consts.Consts.id: process_element.getAttribute(consts.Consts.id),
consts.Consts.name: process_element.getAttribute(consts.Consts.name)
if process_element.hasAttribute(consts.Consts.name) else "",
consts.Consts.is_closed: process_element.getAttribute(consts.Consts.is_closed)
if process_element.hasAttribute(consts.Consts.is_closed) else "false",
consts.Consts.is_executable: process_element.getAttribute(
consts.Consts.is_executable)
if process_element.hasAttribute(consts.Consts.is_executable) else "false",
consts.Consts.process_type: process_element.getAttribute(
consts.Consts.process_type)
if process_element.hasAttribute(consts.Consts.process_type) else "None",
consts.Consts.node_ids: []}
process_elements_dict[process_id] = process_element_attributes
@staticmethod
def import_flow_node_to_graph(bpmn_graph, process_id, process_attributes, flow_node_element):
"""
Adds a new node to graph.
Input parameter is object of class xml.dom.Element.
Nodes are identified by ID attribute of Element.
Method adds basic attributes (shared by all BPMN elements) to node. Those elements are:
- id - added as key value, we assume that this is a required value,
- type - tagName of element, used to identify type of BPMN diagram element,
- name - optional attribute, empty string by default.
:param bpmn_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param flow_node_element: object representing a BPMN XML element corresponding to given flownode,
"""
element_id = flow_node_element.getAttribute(consts.Consts.id)
bpmn_graph.add_node(element_id)
bpmn_graph.node[element_id][consts.Consts.id] = element_id
bpmn_graph.node[element_id][consts.Consts.type] = \
utils.BpmnImportUtils.remove_namespace_from_tag_name(flow_node_element.tagName)
bpmn_graph.node[element_id][consts.Consts.node_name] = \
flow_node_element.getAttribute(consts.Consts.name) \
if flow_node_element.hasAttribute(consts.Consts.name) \
else ""
bpmn_graph.node[element_id][consts.Consts.process] = process_id
process_attributes[consts.Consts.node_ids].append(element_id)
# add incoming flow node list
incoming_list = []
for tmp_element in utils.BpmnImportUtils.iterate_elements(flow_node_element):
if tmp_element.nodeType != tmp_element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(tmp_element.tagName)
if tag_name == consts.Consts.incoming_flow:
incoming_value = tmp_element.firstChild.nodeValue
incoming_list.append(incoming_value)
bpmn_graph.node[element_id][consts.Consts.incoming_flow] = incoming_list
# add outgoing flow node list
outgoing_list = []
for tmp_element in utils.BpmnImportUtils.iterate_elements(flow_node_element):
if tmp_element.nodeType != tmp_element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(tmp_element.tagName)
if tag_name == consts.Consts.outgoing_flow:
outgoing_value = tmp_element.firstChild.nodeValue
outgoing_list.append(outgoing_value)
bpmn_graph.node[element_id][consts.Consts.outgoing_flow] = outgoing_list
@staticmethod
def import_task_to_graph(diagram_graph, process_id, process_attributes, task_element):
"""
Adds to graph the new element that represents BPMN task.
In our representation tasks have only basic attributes and elements, inherited from Activity type,
so this method only needs to call add_flownode_to_graph.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param task_element: object representing a BPMN XML 'task' element.
"""
BpmnDiagramGraphImport.import_activity_to_graph(diagram_graph, process_id, process_attributes, task_element)
@staticmethod
def import_subprocess_to_graph(diagram_graph, sequence_flows, process_id, process_attributes, subprocess_element):
"""
Adds to graph the new element that represents BPMN subprocess.
In addition to attributes inherited from FlowNode type, SubProcess
has additional attribute tiggeredByEvent (boolean type, default value - false).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: a list of sequence flows existing in diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param subprocess_element: object representing a BPMN XML 'subprocess' element
"""
BpmnDiagramGraphImport.import_activity_to_graph(diagram_graph, process_id, process_attributes,
subprocess_element)
subprocess_id = subprocess_element.getAttribute(consts.Consts.id)
diagram_graph.node[subprocess_id][consts.Consts.triggered_by_event] = \
subprocess_element.getAttribute(consts.Consts.triggered_by_event) \
if subprocess_element.hasAttribute(consts.Consts.triggered_by_event) else "false"
subprocess_attributes = diagram_graph.node[subprocess_id]
subprocess_attributes[consts.Consts.node_ids] = []
for element in utils.BpmnImportUtils.iterate_elements(subprocess_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
BpmnDiagramGraphImport.__import_element_by_tag_name(diagram_graph, sequence_flows, subprocess_id,
subprocess_attributes, element, tag_name)
for flow in utils.BpmnImportUtils.iterate_elements(subprocess_element):
if flow.nodeType != flow.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(flow.tagName)
if tag_name == consts.Consts.sequence_flow:
BpmnDiagramGraphImport.import_sequence_flow_to_graph(diagram_graph, sequence_flows, subprocess_id,
flow)
@staticmethod
def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element):
"""
Adds to graph the new element that represents BPMN data object.
Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param data_object_element: object representing a BPMN XML 'dataObject' element.
"""
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes,
data_object_element)
data_object_id = data_object_element.getAttribute(consts.Consts.id)
diagram_graph.node[data_object_id][consts.Consts.is_collection] = \
data_object_element.getAttribute(consts.Consts.is_collection) \
if data_object_element.hasAttribute(consts.Consts.is_collection) else "false"
@staticmethod
def import_activity_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Method that adds the new element that represents BPMN activity.
Should not be used directly, only as a part of method, that imports an element which extends Activity element
(task, subprocess etc.)
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML element which extends 'activity'.
"""
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
element_id = element.getAttribute(consts.Consts.id)
diagram_graph.node[element_id][consts.Consts.default] = element.getAttribute(consts.Consts.default) \
if element.hasAttribute(consts.Consts.default) else None
@staticmethod
def import_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN gateway.
In addition to attributes inherited from FlowNode type, Gateway
has additional attribute gatewayDirection (simple type, default value - Unspecified).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML element of Gateway type extension.
"""
element_id = element.getAttribute(consts.Consts.id)
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
diagram_graph.node[element_id][consts.Consts.gateway_direction] = \
element.getAttribute(consts.Consts.gateway_direction) \
if element.hasAttribute(consts.Consts.gateway_direction) else "Unspecified"
@staticmethod
def import_complex_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN complex gateway.
In addition to attributes inherited from Gateway type, complex gateway
has additional attribute default flow (default value - none).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'complexGateway' element.
"""
element_id = element.getAttribute(consts.Consts.id)
BpmnDiagramGraphImport.import_gateway_to_graph(diagram_graph, process_id, process_attributes, element)
diagram_graph.node[element_id][consts.Consts.default] = element.getAttribute(consts.Consts.default) \
if element.hasAttribute(consts.Consts.default) else None
# TODO sequence of conditions
# Can't get any working example of Complex gateway, so I'm not sure how exactly those conditions are kept
@staticmethod
def import_event_based_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN event based gateway.
In addition to attributes inherited from Gateway type, event based gateway has additional
attributes - instantiate (boolean type, default value - false) and eventGatewayType
(custom type tEventBasedGatewayType, default value - Exclusive).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'eventBasedGateway' element.
"""
element_id = element.getAttribute(consts.Consts.id)
BpmnDiagramGraphImport.import_gateway_to_graph(diagram_graph, process_id, process_attributes, element)
diagram_graph.node[element_id][consts.Consts.instantiate] = element.getAttribute(consts.Consts.instantiate) \
if element.hasAttribute(consts.Consts.instantiate) else "false"
diagram_graph.node[element_id][consts.Consts.event_gateway_type] = \
element.getAttribute(consts.Consts.event_gateway_type) \
if element.hasAttribute(consts.Consts.event_gateway_type) else "Exclusive"
@staticmethod
def import_incl_or_excl_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN inclusive or eclusive gateway.
In addition to attributes inherited from Gateway type, inclusive and exclusive gateway have additional
attribute default flow (default value - none).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'inclusiveGateway' or 'exclusiveGateway' element.
"""
element_id = element.getAttribute(consts.Consts.id)
BpmnDiagramGraphImport.import_gateway_to_graph(diagram_graph, process_id, process_attributes, element)
diagram_graph.node[element_id][consts.Consts.default] = element.getAttribute(consts.Consts.default) \
if element.hasAttribute(consts.Consts.default) else None
@staticmethod
def import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN parallel gateway.
Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'parallelGateway'.
"""
BpmnDiagramGraphImport.import_gateway_to_graph(diagram_graph, process_id, process_attributes, element)
@staticmethod
def import_event_definition_elements(diagram_graph, element, event_definitions):
"""
Helper function, that adds event definition elements (defines special types of events) to corresponding events.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param element: object representing a BPMN XML event element,
:param event_definitions: list of event definitions, that belongs to given event.
"""
element_id = element.getAttribute(consts.Consts.id)
event_def_list = []
for definition_type in event_definitions:
event_def_xml = element.getElementsByTagNameNS("*", definition_type)
for index in range(len(event_def_xml)):
# tuple - definition type, definition id
event_def_tmp = {consts.Consts.id: event_def_xml[index].getAttribute(consts.Consts.id),
consts.Consts.definition_type: definition_type}
event_def_list.append(event_def_tmp)
diagram_graph.node[element_id][consts.Consts.event_definitions] = event_def_list
@staticmethod
def import_start_event_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN start event.
Start event inherits attribute parallelMultiple from CatchEvent type
and sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'startEvent' element.
"""
element_id = element.getAttribute(consts.Consts.id)
start_event_definitions = {'messageEventDefinition', 'timerEventDefinition', 'conditionalEventDefinition',
'escalationEventDefinition', 'signalEventDefinition'}
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
diagram_graph.node[element_id][consts.Consts.parallel_multiple] = \
element.getAttribute(consts.Consts.parallel_multiple) \
if element.hasAttribute(consts.Consts.parallel_multiple) else "false"
diagram_graph.node[element_id][consts.Consts.is_interrupting] = \
element.getAttribute(consts.Consts.is_interrupting) \
if element.hasAttribute(consts.Consts.is_interrupting) else "true"
BpmnDiagramGraphImport.import_event_definition_elements(diagram_graph, element, start_event_definitions)
@staticmethod
def import_intermediate_catch_event_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN intermediate catch event.
Intermediate catch event inherits attribute parallelMultiple from CatchEvent type
and sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'intermediateCatchEvent' element.
"""
element_id = element.getAttribute(consts.Consts.id)
intermediate_catch_event_definitions = {'messageEventDefinition', 'timerEventDefinition',
'signalEventDefinition', 'conditionalEventDefinition',
'escalationEventDefinition'}
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
diagram_graph.node[element_id][consts.Consts.parallel_multiple] = \
element.getAttribute(consts.Consts.parallel_multiple) \
if element.hasAttribute(consts.Consts.parallel_multiple) else "false"
BpmnDiagramGraphImport.import_event_definition_elements(diagram_graph, element,
intermediate_catch_event_definitions)
@staticmethod
def import_end_event_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN end event.
End event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'endEvent' element.
"""
end_event_definitions = {'messageEventDefinition', 'signalEventDefinition', 'escalationEventDefinition',
'errorEventDefinition', 'compensateEventDefinition', 'terminateEventDefinition'}
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
BpmnDiagramGraphImport.import_event_definition_elements(diagram_graph, element, end_event_definitions)
@staticmethod
def import_intermediate_throw_event_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN intermediate throw event.
Intermediate throw event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'intermediateThrowEvent' element.
"""
intermediate_throw_event_definitions = {'messageEventDefinition', 'signalEventDefinition',
'escalationEventDefinition', 'compensateEventDefinition'}
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
BpmnDiagramGraphImport.import_event_definition_elements(diagram_graph, element,
intermediate_throw_event_definitions)
@staticmethod
def import_boundary_event_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN boundary event.
Boundary event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'endEvent' element.
"""
element_id = element.getAttribute(consts.Consts.id)
boundary_event_definitions = {'messageEventDefinition', 'timerEventDefinition', 'signalEventDefinition',
'conditionalEventDefinition', 'escalationEventDefinition', 'errorEventDefinition'}
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
diagram_graph.node[element_id][consts.Consts.parallel_multiple] = \
element.getAttribute(consts.Consts.parallel_multiple) \
if element.hasAttribute(consts.Consts.parallel_multiple) else "false"
diagram_graph.node[element_id][consts.Consts.cancel_activity] = \
element.getAttribute(consts.Consts.cancel_activity) \
if element.hasAttribute(consts.Consts.cancel_activity) else "true"
diagram_graph.node[element_id][consts.Consts.attached_to_ref] = \
element.getAttribute(consts.Consts.attached_to_ref)
BpmnDiagramGraphImport.import_event_definition_elements(diagram_graph, element,
boundary_event_definitions)
@staticmethod
def import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id, flow_element):
"""
Adds a new edge to graph and a record to sequence_flows dictionary.
Input parameter is object of class xml.dom.Element.
Edges are identified by pair of sourceRef and targetRef attributes of BPMNFlow element. We also
provide a dictionary, that maps sequenceFlow ID attribute with its sourceRef and targetRef.
Method adds basic attributes of sequenceFlow element to edge. Those elements are:
- id - added as edge attribute, we assume that this is a required value,
- name - optional attribute, empty string by default.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: dictionary (associative list) of sequence flows existing in diagram.
Key attribute is sequenceFlow ID, value is a dictionary consisting three key-value pairs: "name" (sequence
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param process_id: string object, representing an ID of process element,
:param flow_element: object representing a BPMN XML 'sequenceFlow' element.
"""
flow_id = flow_element.getAttribute(consts.Consts.id)
name = flow_element.getAttribute(consts.Consts.name) if flow_element.hasAttribute(consts.Consts.name) else ""
source_ref = flow_element.getAttribute(consts.Consts.source_ref)
target_ref = flow_element.getAttribute(consts.Consts.target_ref)
sequence_flows[flow_id] = {consts.Consts.name: name, consts.Consts.source_ref: source_ref,
consts.Consts.target_ref: target_ref}
diagram_graph.add_edge(source_ref, target_ref)
diagram_graph[source_ref][target_ref][consts.Consts.id] = flow_id
diagram_graph[source_ref][target_ref][consts.Consts.process] = process_id
diagram_graph[source_ref][target_ref][consts.Consts.name] = name
diagram_graph[source_ref][target_ref][consts.Consts.source_ref] = source_ref
diagram_graph[source_ref][target_ref][consts.Consts.target_ref] = target_ref
for element in utils.BpmnImportUtils.iterate_elements(flow_element):
if element.nodeType != element.TEXT_NODE:
tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName)
if tag_name == consts.Consts.condition_expression:
condition_expression = element.firstChild.nodeValue
diagram_graph[source_ref][target_ref][consts.Consts.condition_expression] = {
consts.Consts.id: element.getAttribute(consts.Consts.id),
consts.Consts.condition_expression: condition_expression
}
'''
# Add incoming / outgoing nodes to corresponding elements. May be redundant action since this information is
added when processing nodes, but listing incoming / outgoing nodes under node element is optional - this way
we can make sure this info will be imported.
'''
if consts.Consts.outgoing_flow not in diagram_graph.node[source_ref]:
diagram_graph.node[source_ref][consts.Consts.outgoing_flow] = []
outgoing_list = diagram_graph.node[source_ref][consts.Consts.outgoing_flow]
if flow_id not in outgoing_list:
outgoing_list.append(flow_id)
if consts.Consts.incoming_flow not in diagram_graph.node[target_ref]:
diagram_graph.node[target_ref][consts.Consts.incoming_flow] = []
incoming_list = diagram_graph.node[target_ref][consts.Consts.incoming_flow]
if flow_id not in incoming_list:
incoming_list.append(flow_id)
@staticmethod
def import_message_flow_to_graph(diagram_graph, message_flows, flow_element):
"""
Adds a new edge to graph and a record to message flows dictionary.
Input parameter is object of class xml.dom.Element.
Edges are identified by pair of sourceRef and targetRef attributes of BPMNFlow element. We also
provide a dictionary, that maps messageFlow ID attribute with its sourceRef and targetRef.
Method adds basic attributes of messageFlow element to edge. Those elements are:
- id - added as edge attribute, we assume that this is a required value,
- name - optional attribute, empty string by default.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param message_flows: dictionary (associative list) of message flows existing in diagram.
Key attribute is messageFlow ID, value is a dictionary consisting three key-value pairs: "name" (message
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param flow_element: object representing a BPMN XML 'messageFlow' element.
"""
flow_id = flow_element.getAttribute(consts.Consts.id)
name = flow_element.getAttribute(consts.Consts.name) if flow_element.hasAttribute(consts.Consts.name) else ""
source_ref = flow_element.getAttribute(consts.Consts.source_ref)
target_ref = flow_element.getAttribute(consts.Consts.target_ref)
message_flows[flow_id] = {consts.Consts.id: flow_id, consts.Consts.name: name,
consts.Consts.source_ref: source_ref,
consts.Consts.target_ref: target_ref}
diagram_graph.add_edge(source_ref, target_ref)
diagram_graph[source_ref][target_ref][consts.Consts.id] = flow_id
diagram_graph[source_ref][target_ref][consts.Consts.name] = name
diagram_graph[source_ref][target_ref][consts.Consts.source_ref] = source_ref
diagram_graph[source_ref][target_ref][consts.Consts.target_ref] = target_ref
'''
# Add incoming / outgoing nodes to corresponding elements. May be redundant action since this information is
added when processing nodes, but listing incoming / outgoing nodes under node element is optional - this way
we can make sure this info will be imported.
'''
if consts.Consts.outgoing_flow not in diagram_graph.node[source_ref]:
diagram_graph.node[source_ref][consts.Consts.outgoing_flow] = []
outgoing_list = diagram_graph.node[source_ref][consts.Consts.outgoing_flow]
if flow_id not in outgoing_list:
outgoing_list.append(flow_id)
if consts.Consts.incoming_flow not in diagram_graph.node[target_ref]:
diagram_graph.node[target_ref][consts.Consts.incoming_flow] = []
incoming_list = diagram_graph.node[target_ref][consts.Consts.incoming_flow]
if flow_id not in incoming_list:
incoming_list.append(flow_id)
@staticmethod
def import_shape_di(participants_dict, diagram_graph, shape_element):
"""
Adds Diagram Interchange information (information about rendering a diagram) to appropriate
BPMN diagram element in graph node.
We assume that those attributes are required for each BPMNShape:
- width - width of BPMNShape,
- height - height of BPMNShape,
- x - first coordinate of BPMNShape,
- y - second coordinate of BPMNShape.
:param participants_dict: dictionary with 'participant' elements attributes,
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param shape_element: object representing a BPMN XML 'BPMNShape' element.
"""
element_id = shape_element.getAttribute(consts.Consts.bpmn_element)
bounds = shape_element.getElementsByTagNameNS("*", "Bounds")[0]
if diagram_graph.has_node(element_id):
node = diagram_graph.node[element_id]
node[consts.Consts.width] = bounds.getAttribute(consts.Consts.width)
node[consts.Consts.height] = bounds.getAttribute(consts.Consts.height)
if node[consts.Consts.type] == consts.Consts.subprocess:
node[consts.Consts.is_expanded] = \
shape_element.getAttribute(consts.Consts.is_expanded) \
if shape_element.hasAttribute(consts.Consts.is_expanded) else "false"
node[consts.Consts.x] = bounds.getAttribute(consts.Consts.x)
node[consts.Consts.y] = bounds.getAttribute(consts.Consts.y)
if element_id in participants_dict:
# BPMNShape is either connected with FlowNode or Participant
participant_attr = participants_dict[element_id]
participant_attr[consts.Consts.is_horizontal] = shape_element.getAttribute(consts.Consts.is_horizontal)
participant_attr[consts.Consts.width] = bounds.getAttribute(consts.Consts.width)
participant_attr[consts.Consts.height] = bounds.getAttribute(consts.Consts.height)
participant_attr[consts.Consts.x] = bounds.getAttribute(consts.Consts.x)
participant_attr[consts.Consts.y] = bounds.getAttribute(consts.Consts.y)
@staticmethod
def import_flow_di(diagram_graph, sequence_flows, message_flows, flow_element):
"""
Adds Diagram Interchange information (information about rendering a diagram) to appropriate
BPMN sequence flow represented as graph edge.
We assume that each BPMNEdge has a list of 'waypoint' elements. BPMN 2.0 XML Schema states,
that each BPMNEdge must have at least two waypoints.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: dictionary (associative list) of sequence flows existing in diagram.
Key attribute is sequenceFlow ID, value is a dictionary consisting three key-value pairs: "name" (sequence
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param message_flows: dictionary (associative list) of message flows existing in diagram.
Key attribute is messageFlow ID, value is a dictionary consisting three key-value pairs: "name" (message
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param flow_element: object representing a BPMN XML 'BPMNEdge' element.
"""
flow_id = flow_element.getAttribute(consts.Consts.bpmn_element)
waypoints_xml = flow_element.getElementsByTagNameNS("*", consts.Consts.waypoint)
length = len(waypoints_xml)
waypoints = [None] * length
for index in range(length):
waypoint_tmp = (waypoints_xml[index].getAttribute(consts.Consts.x),
waypoints_xml[index].getAttribute(consts.Consts.y))
waypoints[index] = waypoint_tmp
flow_data = None
if flow_id in sequence_flows:
flow_data = sequence_flows[flow_id]
elif flow_id in message_flows:
flow_data = message_flows[flow_id]
if flow_data is not None:
name = flow_data[consts.Consts.name]
source_ref = flow_data[consts.Consts.source_ref]
target_ref = flow_data[consts.Consts.target_ref]
diagram_graph[source_ref][target_ref][consts.Consts.waypoints] = waypoints
diagram_graph[source_ref][target_ref][consts.Consts.name] = name
@staticmethod
def read_xml_file(filepath):
"""
Reads BPMN 2.0 XML file from given filepath and returns xml.dom.xminidom.Document object.
:param filepath: filepath of source XML file.
"""
dom_tree = minidom.parse(filepath)
return dom_tree
|
class BpmnDiagramGraphImport(object):
'''
Class BPMNDiagramGraphImport provides methods for importing BPMN 2.0 XML file.
As a utility class, it only contains static methods. This class is meant to be used from BPMNDiagramGraph class.
'''
def __init__(self):
pass
@staticmethod
def load_diagram_from_xml(filepath, bpmn_diagram):
'''
Reads an XML file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath,
:param bpmn_diagram: an instance of BpmnDiagramGraph class.
'''
pass
@staticmethod
def import_collaboration_element(diagram_graph, collaboration_element, collaboration_dict):
'''
Method that imports information from 'collaboration' element.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param collaboration_element: XML doument element,
:param collaboration_dict: dictionary, that consist all information imported from 'collaboration' element.
Includes three key-value pairs - 'id' which keeps ID of collaboration element, 'participants' that keeps
information about 'participant' elements and 'message_flows' that keeps information about message flows.
'''
pass
@staticmethod
def import_participant_element(diagram_graph, participants_dictionary, participant_element):
'''
Adds 'participant' element to the collaboration dictionary.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param participants_dictionary: dictionary with participant element attributes. Key is participant ID, value
is a dictionary of participant attributes,
:param participant_element: object representing a BPMN XML 'participant' element.
'''
pass
@staticmethod
def import_diagram_and_plane_attributes(diagram_attributes, plane_attributes, diagram_element, plane_element):
'''
Adds attributes of BPMN diagram and plane elements to appropriate
fields diagram_attributes and plane_attributes.
Diagram inner representation contains following diagram element attributes:
- id - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
- name - optional parameter, empty string by default,
Diagram inner representation contains following plane element attributes:
- id - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
- bpmnElement - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
:param diagram_attributes: dictionary that holds attribute values for imported 'BPMNDiagram' element,
:param plane_attributes: dictionary that holds attribute values for imported 'BPMNPlane' element,
:param diagram_element: object representing a BPMN XML 'diagram' element,
:param plane_element: object representing a BPMN XML 'plane' element.
'''
pass
@staticmethod
def import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element):
'''
Method for importing all 'process' elements in diagram.
:param document: XML document,
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: a list of sequence flows existing in diagram,
:param process_elements_dict: dictionary that holds attribute values for imported 'process' elements. Key is
an ID of process, value - a dictionary of process attributes,
:param plane_element: object representing a BPMN XML 'plane' element.
'''
pass
@staticmethod
def __import_element_by_tag_name(diagram_graph, sequence_flows, process_id, process_attributes, element, tag_name):
pass
@staticmethod
def import_lane_set_element(process_attributes, lane_set_element, plane_element):
'''
Method for importing 'laneSet' element from diagram file.
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param lane_set_element: XML document element,
:param plane_element: object representing a BPMN XML 'plane' element.
'''
pass
@staticmethod
def import_child_lane_set_element(child_lane_set_element, plane_element):
'''
Method for importing 'childLaneSet' element from diagram file.
:param child_lane_set_element: XML document element,
:param plane_element: object representing a BPMN XML 'plane' element.
'''
pass
@staticmethod
def import_lane_element(lane_element, plane_element):
'''
Method for importing 'laneSet' element from diagram file.
:param lane_element: XML document element,
:param plane_element: object representing a BPMN XML 'plane' element.
'''
pass
@staticmethod
def import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element):
'''
Adds attributes of BPMN process element to appropriate field process_attributes.
Diagram inner representation contains following process attributes:
- id - assumed to be required in XML file, even thought BPMN 2.0 schema doesn't say so,
- isClosed - optional parameter, default value 'false',
- isExecutable - optional parameter, default value 'false',
- processType - optional parameter, default value 'None',
- node_ids - list of flow nodes IDs, associated with given process.
:param process_elements_dict: dictionary that holds attribute values for imported 'process' element. Key is
process ID, value is a dictionary of attributes,
:param process_element: object representing a BPMN XML 'process' element.
'''
pass
@staticmethod
def import_flow_node_to_graph(bpmn_graph, process_id, process_attributes, flow_node_element):
'''
Adds a new node to graph.
Input parameter is object of class xml.dom.Element.
Nodes are identified by ID attribute of Element.
Method adds basic attributes (shared by all BPMN elements) to node. Those elements are:
- id - added as key value, we assume that this is a required value,
- type - tagName of element, used to identify type of BPMN diagram element,
- name - optional attribute, empty string by default.
:param bpmn_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param flow_node_element: object representing a BPMN XML element corresponding to given flownode,
'''
pass
@staticmethod
def import_task_to_graph(diagram_graph, process_id, process_attributes, task_element):
'''
Adds to graph the new element that represents BPMN task.
In our representation tasks have only basic attributes and elements, inherited from Activity type,
so this method only needs to call add_flownode_to_graph.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param task_element: object representing a BPMN XML 'task' element.
'''
pass
@staticmethod
def import_subprocess_to_graph(diagram_graph, sequence_flows, process_id, process_attributes, subprocess_element):
'''
Adds to graph the new element that represents BPMN subprocess.
In addition to attributes inherited from FlowNode type, SubProcess
has additional attribute tiggeredByEvent (boolean type, default value - false).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: a list of sequence flows existing in diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param subprocess_element: object representing a BPMN XML 'subprocess' element
'''
pass
@staticmethod
def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element):
'''
Adds to graph the new element that represents BPMN data object.
Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param data_object_element: object representing a BPMN XML 'dataObject' element.
'''
pass
@staticmethod
def import_activity_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Method that adds the new element that represents BPMN activity.
Should not be used directly, only as a part of method, that imports an element which extends Activity element
(task, subprocess etc.)
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML element which extends 'activity'.
'''
pass
@staticmethod
def import_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN gateway.
In addition to attributes inherited from FlowNode type, Gateway
has additional attribute gatewayDirection (simple type, default value - Unspecified).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML element of Gateway type extension.
'''
pass
@staticmethod
def import_complex_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN complex gateway.
In addition to attributes inherited from Gateway type, complex gateway
has additional attribute default flow (default value - none).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'complexGateway' element.
'''
pass
@staticmethod
def import_event_based_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN event based gateway.
In addition to attributes inherited from Gateway type, event based gateway has additional
attributes - instantiate (boolean type, default value - false) and eventGatewayType
(custom type tEventBasedGatewayType, default value - Exclusive).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'eventBasedGateway' element.
'''
pass
@staticmethod
def import_incl_or_excl_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN inclusive or eclusive gateway.
In addition to attributes inherited from Gateway type, inclusive and exclusive gateway have additional
attribute default flow (default value - none).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'inclusiveGateway' or 'exclusiveGateway' element.
'''
pass
@staticmethod
def import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN parallel gateway.
Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'parallelGateway'.
'''
pass
@staticmethod
def import_event_definition_elements(diagram_graph, element, event_definitions):
'''
Helper function, that adds event definition elements (defines special types of events) to corresponding events.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param element: object representing a BPMN XML event element,
:param event_definitions: list of event definitions, that belongs to given event.
'''
pass
@staticmethod
def import_start_event_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN start event.
Start event inherits attribute parallelMultiple from CatchEvent type
and sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'startEvent' element.
'''
pass
@staticmethod
def import_intermediate_catch_event_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN intermediate catch event.
Intermediate catch event inherits attribute parallelMultiple from CatchEvent type
and sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'intermediateCatchEvent' element.
'''
pass
@staticmethod
def import_end_event_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN end event.
End event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'endEvent' element.
'''
pass
@staticmethod
def import_intermediate_throw_event_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN intermediate throw event.
Intermediate throw event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'intermediateThrowEvent' element.
'''
pass
@staticmethod
def import_boundary_event_to_graph(diagram_graph, process_id, process_attributes, element):
'''
Adds to graph the new element that represents BPMN boundary event.
Boundary event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing an ID of process element,
:param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of
imported flow node,
:param element: object representing a BPMN XML 'endEvent' element.
'''
pass
@staticmethod
def import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id, flow_element):
'''
Adds a new edge to graph and a record to sequence_flows dictionary.
Input parameter is object of class xml.dom.Element.
Edges are identified by pair of sourceRef and targetRef attributes of BPMNFlow element. We also
provide a dictionary, that maps sequenceFlow ID attribute with its sourceRef and targetRef.
Method adds basic attributes of sequenceFlow element to edge. Those elements are:
- id - added as edge attribute, we assume that this is a required value,
- name - optional attribute, empty string by default.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: dictionary (associative list) of sequence flows existing in diagram.
Key attribute is sequenceFlow ID, value is a dictionary consisting three key-value pairs: "name" (sequence
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param process_id: string object, representing an ID of process element,
:param flow_element: object representing a BPMN XML 'sequenceFlow' element.
'''
pass
@staticmethod
def import_message_flow_to_graph(diagram_graph, message_flows, flow_element):
'''
Adds a new edge to graph and a record to message flows dictionary.
Input parameter is object of class xml.dom.Element.
Edges are identified by pair of sourceRef and targetRef attributes of BPMNFlow element. We also
provide a dictionary, that maps messageFlow ID attribute with its sourceRef and targetRef.
Method adds basic attributes of messageFlow element to edge. Those elements are:
- id - added as edge attribute, we assume that this is a required value,
- name - optional attribute, empty string by default.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param message_flows: dictionary (associative list) of message flows existing in diagram.
Key attribute is messageFlow ID, value is a dictionary consisting three key-value pairs: "name" (message
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param flow_element: object representing a BPMN XML 'messageFlow' element.
'''
pass
@staticmethod
def import_shape_di(participants_dict, diagram_graph, shape_element):
'''
Adds Diagram Interchange information (information about rendering a diagram) to appropriate
BPMN diagram element in graph node.
We assume that those attributes are required for each BPMNShape:
- width - width of BPMNShape,
- height - height of BPMNShape,
- x - first coordinate of BPMNShape,
- y - second coordinate of BPMNShape.
:param participants_dict: dictionary with 'participant' elements attributes,
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param shape_element: object representing a BPMN XML 'BPMNShape' element.
'''
pass
@staticmethod
def import_flow_di(diagram_graph, sequence_flows, message_flows, flow_element):
'''
Adds Diagram Interchange information (information about rendering a diagram) to appropriate
BPMN sequence flow represented as graph edge.
We assume that each BPMNEdge has a list of 'waypoint' elements. BPMN 2.0 XML Schema states,
that each BPMNEdge must have at least two waypoints.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param sequence_flows: dictionary (associative list) of sequence flows existing in diagram.
Key attribute is sequenceFlow ID, value is a dictionary consisting three key-value pairs: "name" (sequence
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param message_flows: dictionary (associative list) of message flows existing in diagram.
Key attribute is messageFlow ID, value is a dictionary consisting three key-value pairs: "name" (message
flow name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
:param flow_element: object representing a BPMN XML 'BPMNEdge' element.
'''
pass
@staticmethod
def read_xml_file(filepath):
'''
Reads BPMN 2.0 XML file from given filepath and returns xml.dom.xminidom.Document object.
:param filepath: filepath of source XML file.
'''
pass
| 64 | 31 | 26 | 2 | 14 | 10 | 4 | 0.69 | 1 | 3 | 2 | 0 | 1 | 0 | 32 | 32 | 888 | 102 | 464 | 184 | 400 | 322 | 338 | 153 | 305 | 13 | 1 | 4 | 129 |
144,102 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_diagram_rep.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_diagram_rep.BpmnDiagramGraph
|
class BpmnDiagramGraph(object):
"""
Class BPMNDiagramGraph implements simple inner representation of BPMN 2.0 diagram,
based on NetworkX graph implementation
Fields:
* diagram_graph - networkx.Graph object, stores elements of BPMN diagram as nodes. Each edge of graph represents
sequenceFlow element. Edges are identified by IDs of nodes connected by edge. IDs are passed as edge parameters,
* sequence_flows - dictionary (associative list) of sequence flows existing in diagram.
Key attribute is sequenceFlow ID, value is a dictionary consisting three key-value pairs: "name" (sequence flow
name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
* collaboration - a dictionary that contains two dictionaries:
* "messageFlows" - dictionary (associative list) of message flows existing in diagram. Key attribute is
messageFlow ID, value is a dictionary consisting three key-value pairs: "name" (message flow name),
* "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
* "participants" - dictionary (associative list) of participants existing in diagram. Key attribute is
participant ID, value is a dictionary consisting participant attributes,
* process_elements_dictionary - dictionary that holds attribute values for imported 'process' elements.
Key is an ID of process, value is a dictionary of all process attributes,
* diagram_attributes - dictionary that contains BPMN diagram element attributes,
* plane_attributes - dictionary that contains BPMN plane element attributes.
"""
# String "constants" used in multiple places
id_prefix = "id"
bpmndi_namespace = "bpmndi:"
def __init__(self):
"""
Default constructor, initializes object fields with new instances.
"""
self.diagram_graph = nx.Graph()
self.sequence_flows = {}
self.process_elements = {}
self.diagram_attributes = {}
self.plane_attributes = {}
self.collaboration = {}
def load_diagram_from_xml_file(self, filepath):
"""
Reads an XML file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath.
"""
bpmn_import.BpmnDiagramGraphImport.load_diagram_from_xml(filepath, self)
def export_xml_file(self, directory, filename):
"""
Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).
:param directory: strings representing output directory,
:param filename: string representing output file name.
"""
bpmn_export.BpmnDiagramGraphExport.export_xml_file(directory, filename, self)
def export_xml_file_no_di(self, directory, filename):
"""
Exports diagram inner graph to BPMN 2.0 XML file (without Diagram Interchange data).
:param directory: strings representing output directory,
:param filename: string representing output file name.
"""
bpmn_export.BpmnDiagramGraphExport.export_xml_file_no_di(directory, filename, self)
def load_diagram_from_csv_file(self, filepath):
"""
Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath.
"""
bpmn_csv_import.BpmnDiagramGraphCSVImport.load_diagram_from_csv(filepath, self)
def export_csv_file(self, directory, filename):
"""
Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).
:param directory: strings representing output directory,
:param filename: string representing output file name.
"""
bpmn_csv_export.BpmnDiagramGraphCsvExport.export_process_to_csv(self, directory, filename)
# Querying methods
def get_nodes(self, node_type=""):
"""
Gets all nodes of requested type. If no type is provided by user, all nodes in BPMN diagram graph are returned.
Returns a dictionary, where key is an ID of node, value is a dictionary of all node attributes.
:param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
"""
tmp_nodes = self.diagram_graph.nodes(True)
if node_type == "":
return tmp_nodes
else:
nodes = []
for node in tmp_nodes:
if node[1][consts.Consts.type] == node_type:
nodes.append(node)
return nodes
def get_nodes_list_by_process_id(self, process_id):
"""
Gets all nodes of requested type. If no type is provided by user, all nodes in BPMN diagram graph are returned.
Returns a dictionary, where key is an ID of node, value is a dictionary of all node attributes.
:param process_id: string object, representing an ID of parent process element.
"""
tmp_nodes = self.diagram_graph.nodes(True)
nodes = []
for node in tmp_nodes:
if node[1][consts.Consts.process] == process_id:
nodes.append(node)
return nodes
def get_node_by_id(self, node_id):
"""
Gets a node with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param node_id: string with ID of node.
"""
tmp_nodes = self.diagram_graph.nodes(data=True)
for node in tmp_nodes:
if node[0] == node_id:
return node
def get_nodes_id_list_by_type(self, node_type):
"""
Get a list of node's id by requested type.
Returns a list of ids
:param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
"""
tmp_nodes = self.diagram_graph.nodes(data=True)
id_list = []
for node in tmp_nodes:
if node[1][consts.Consts.type] == node_type:
id_list.append(node[0])
return id_list
def get_flows(self):
"""
Gets all graph edges (process flows).
Returns a two-dimensional dictionary, where keys are IDs of nodes connected by edge and
values are a dictionary of all edge attributes.
"""
return self.diagram_graph.edges(data=True)
def get_flow_by_id(self, flow_id):
"""
Gets an edge (flow) with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param flow_id: string with edge ID.
"""
tmp_flows = self.diagram_graph.edges(data=True)
for flow in tmp_flows:
if flow[2][consts.Consts.id] == flow_id:
return flow
def get_flows_list_by_process_id(self, process_id):
"""
Gets an edge (flow) with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param process_id: string object, representing an ID of parent process element.
"""
tmp_flows = self.diagram_graph.edges(data=True)
flows = []
for flow in tmp_flows:
if consts.Consts.process in flow[2] and flow[2][consts.Consts.process] == process_id:
flows.append(flow)
return flows
# Diagram creating methods
def create_new_diagram_graph(self, diagram_name=""):
"""
Initializes a new BPMN diagram and sets up a basic diagram attributes.
Accepts a user-defined values for following attributes:
(Diagram element)
- name - default value empty string.
:param diagram_name: string type. Represents a user-defined value of 'BPMNDiagram' element
attribute 'name'. Default value - empty string.
"""
self.__init__()
diagram_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.diagram_attributes[consts.Consts.id] = diagram_id
self.diagram_attributes[consts.Consts.name] = diagram_name
def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False,
process_type="None"):
"""
Adds a new process to diagram and corresponding participant
process, diagram and plane
Accepts a user-defined values for following attributes:
(Process element)
- isClosed - default value false,
- isExecutable - default value false,
- processType - default value None.
:param process_name: string obejct, process name. Default value - empty string,
:param process_is_closed: boolean type. Represents a user-defined value of 'process' element
attribute 'isClosed'. Default value false,
:param process_is_executable: boolean type. Represents a user-defined value of 'process' element
attribute 'isExecutable'. Default value false,
:param process_type: string type. Represents a user-defined value of 'process' element
attribute 'procesType'. Default value "None",
"""
plane_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
process_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.process_elements[process_id] = {consts.Consts.name: process_name,
consts.Consts.is_closed: "true" if process_is_closed else "false",
consts.Consts.is_executable: "true" if process_is_executable else "false",
consts.Consts.process_type: process_type}
self.plane_attributes[consts.Consts.id] = plane_id
self.plane_attributes[consts.Consts.bpmn_element] = process_id
return process_id
def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None):
"""
Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type.
Adds a basic information inherited from Flow Node type.
:param process_id: string object. ID of parent process,
:param node_type: string object. Represents type of BPMN node passed to method,
:param name: string object. Name of the node,
:param node_id: string object. ID of node. Default value - None.
"""
if node_id is None:
node_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.diagram_graph.add_node(node_id)
self.diagram_graph.node[node_id][consts.Consts.id] = node_id
self.diagram_graph.node[node_id][consts.Consts.type] = node_type
self.diagram_graph.node[node_id][consts.Consts.node_name] = name
self.diagram_graph.node[node_id][consts.Consts.incoming_flow] = []
self.diagram_graph.node[node_id][consts.Consts.outgoing_flow] = []
self.diagram_graph.node[node_id][consts.Consts.process] = process_id
# Adding some dummy constant values
self.diagram_graph.node[node_id][consts.Consts.width] = "100"
self.diagram_graph.node[node_id][consts.Consts.height] = "100"
self.diagram_graph.node[node_id][consts.Consts.x] = "100"
self.diagram_graph.node[node_id][consts.Consts.y] = "100"
return node_id, self.diagram_graph.node[node_id]
def add_task_to_diagram(self, process_id, task_name="", node_id=None):
"""
Adds a Task element to BPMN diagram.
User-defined attributes:
- name
:param process_id: string object. ID of parent process,
:param task_name: string object. Name of task,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is task ID, second a reference to created object.
"""
return self.add_flow_node_to_diagram(process_id, consts.Consts.task, task_name, node_id)
def add_subprocess_to_diagram(self, process_id, subprocess_name, is_expanded=False, triggered_by_event=False,
node_id=None):
"""
Adds a SubProcess element to BPMN diagram.
User-defined attributes:
- name
- triggered_by_event
:param process_id: string object. ID of parent process,
:param subprocess_name: string object. Name of subprocess,
:param is_expanded: boolean value for attribute "isExpanded". Default value false,
:param triggered_by_event: boolean value for attribute "triggeredByEvent". Default value false,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is subProcess ID, second a reference to created object.
"""
subprocess_id, subprocess = self.add_flow_node_to_diagram(process_id, consts.Consts.subprocess, subprocess_name,
node_id)
self.diagram_graph.node[subprocess_id][consts.Consts.is_expanded] = "true" if is_expanded else "false"
self.diagram_graph.node[subprocess_id][consts.Consts.triggered_by_event] = \
"true" if triggered_by_event else "false"
return subprocess_id, subprocess
def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None,
parallel_multiple=False, is_interrupting=True, node_id=None):
"""
Adds a StartEvent element to BPMN diagram.
User-defined attributes:
- name
- parallel_multiple
- is_interrupting
- event definition (creates a special type of start event). Supported event definitions -
* 'message': 'messageEventDefinition',
* 'timer': 'timerEventDefinition',
* 'signal': 'signalEventDefinition',
* 'conditional': 'conditionalEventDefinition',
* 'escalation': 'escalationEventDefinition'.
:param process_id: string object. ID of parent process,
:param start_event_name: string object. Name of start event,
:param start_event_definition: list of event definitions. By default - empty,
:param parallel_multiple: boolean value for attribute "parallelMultiple",
:param is_interrupting: boolean value for attribute "isInterrupting,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is startEvent ID, second a reference to created object.
"""
start_event_id, start_event = self.add_flow_node_to_diagram(process_id, consts.Consts.start_event,
start_event_name, node_id)
self.diagram_graph.node[start_event_id][consts.Consts.parallel_multiple] = \
"true" if parallel_multiple else "false"
self.diagram_graph.node[start_event_id][consts.Consts.is_interrupting] = "true" if is_interrupting else "false"
start_event_definitions = {"message": "messageEventDefinition", "timer": "timerEventDefinition",
"conditional": "conditionalEventDefinition", "signal": "signalEventDefinition",
"escalation": "escalationEventDefinition"}
event_def_list = []
if start_event_definition == "message":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("message", start_event_definitions))
elif start_event_definition == "timer":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("timer", start_event_definitions))
elif start_event_definition == "conditional":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("conditional", start_event_definitions))
elif start_event_definition == "signal":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("signal", start_event_definitions))
elif start_event_definition == "escalation":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("escalation", start_event_definitions))
self.diagram_graph.node[start_event_id][consts.Consts.event_definitions] = event_def_list
return start_event_id, start_event
def add_end_event_to_diagram(self, process_id, end_event_name="", end_event_definition=None, node_id=None):
"""
Adds an EndEvent element to BPMN diagram.
User-defined attributes:
- name
- event definition (creates a special type of end event). Supported event definitions
* `terminate`: 'terminateEventDefinition',
* `signal`: 'signalEventDefinition',
* `error`: 'errorEventDefinition',
* `escalation`: 'escalationEventDefinition',
* `message`: 'messageEventDefinition',
* `compensate`: 'compensateEventDefinition'.
:param process_id: string object. ID of parent process,
:param end_event_name: string object. Name of end event,
:param end_event_definition: list of event definitions. By default - empty.
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is endEvent ID, second a reference to created object,
"""
end_event_id, end_event = self.add_flow_node_to_diagram(process_id, consts.Consts.end_event, end_event_name,
node_id)
end_event_definitions = {"terminate": "terminateEventDefinition", "escalation": "escalationEventDefinition",
"message": "messageEventDefinition", "compensate": "compensateEventDefinition",
"signal": "signalEventDefinition", "error": "errorEventDefinition"}
event_def_list = []
if end_event_definition == "terminate":
event_def_list.append(self.add_event_definition_element("terminate", end_event_definitions))
elif end_event_definition == "escalation":
event_def_list.append(self.add_event_definition_element("escalation", end_event_definitions))
elif end_event_definition == "message":
event_def_list.append(self.add_event_definition_element("message", end_event_definitions))
elif end_event_definition == "compensate":
event_def_list.append(self.add_event_definition_element("compensate", end_event_definitions))
elif end_event_definition == "signal":
event_def_list.append(self.add_event_definition_element("signal", end_event_definitions))
elif end_event_definition == "error":
event_def_list.append(self.add_event_definition_element("error", end_event_definitions))
self.diagram_graph.node[end_event_id][consts.Consts.event_definitions] = event_def_list
return end_event_id, end_event
@staticmethod
def add_event_definition_element(event_type, event_definitions):
"""
Helper function, that creates event definition element (special type of event) from given parameters.
:param event_type: string object. Short name of required event definition,
:param event_definitions: dictionary of event definitions. Key is a short name of event definition,
value is a full name of event definition, as defined in BPMN 2.0 XML Schema.
"""
event_def_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
event_def = {consts.Consts.id: event_def_id, consts.Consts.definition_type: event_definitions[event_type]}
return event_def
def add_gateway_to_diagram(self, process_id, gateway_type, gateway_name="", gateway_direction="Unspecified",
node_id=None):
"""
Adds an exclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_type: string object. Type of gateway to be added.
:param gateway_name: string object. Name of exclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is gateway ID, second a reference to created object.
"""
gateway_id, gateway = self.add_flow_node_to_diagram(process_id, gateway_type, gateway_name, node_id)
if not (gateway_direction in ("Unspecified", "Converging", "Diverging", "Mixed")):
raise bpmn_exception.BpmnPythonError("Invalid value passed as gatewayDirection parameter. Value passed: "
+ gateway_direction)
self.diagram_graph.node[gateway_id][consts.Consts.gateway_direction] = gateway_direction
return gateway_id, gateway
def add_exclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
default=None, node_id=None):
"""
Adds an exclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of exclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified".
:param default: string object. ID of flow node, target of gateway default path. Default value - None,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is exculusiveGateway ID, second a reference to created object.
"""
exclusive_gateway_id, exclusive_gateway = self.add_gateway_to_diagram(process_id,
consts.Consts.exclusive_gateway,
gateway_name=gateway_name,
gateway_direction=gateway_direction,
node_id=node_id)
self.diagram_graph.node[exclusive_gateway_id][consts.Consts.default] = default
return exclusive_gateway_id, exclusive_gateway
def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
default=None, node_id=None):
"""
Adds an inclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param default: string object. ID of flow node, target of gateway default path. Default value - None,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is inclusiveGateway ID, second a reference to created object.
"""
inclusive_gateway_id, inclusive_gateway = self.add_gateway_to_diagram(process_id,
consts.Consts.inclusive_gateway,
gateway_name=gateway_name,
gateway_direction=gateway_direction,
node_id=node_id)
self.diagram_graph.node[inclusive_gateway_id][consts.Consts.default] = default
return inclusive_gateway_id, inclusive_gateway
def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
node_id=None):
"""
Adds an parallelGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is parallelGateway ID, second a reference to created object.
"""
parallel_gateway_id, parallel_gateway = self.add_gateway_to_diagram(process_id,
consts.Consts.parallel_gateway,
gateway_name=gateway_name,
gateway_direction=gateway_direction,
node_id=node_id)
return parallel_gateway_id, parallel_gateway
def add_sequence_flow_to_diagram(self, process_id, source_ref_id, target_ref_id, sequence_flow_name=""):
"""
Adds a SequenceFlow element to BPMN diagram.
Requires that user passes a sourceRef and targetRef as parameters.
User-defined attributes:
- name
:param process_id: string object. ID of parent process,
:param source_ref_id: string object. ID of source node,
:param target_ref_id: string object. ID of target node,
:param sequence_flow_name: string object. Name of sequence flow.
:return: a tuple, where first value is sequenceFlow ID, second a reference to created object.
"""
sequence_flow_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.sequence_flows[sequence_flow_id] = {consts.Consts.name: sequence_flow_name,
consts.Consts.source_ref: source_ref_id,
consts.Consts.target_ref: target_ref_id}
self.diagram_graph.add_edge(source_ref_id, target_ref_id)
flow = self.diagram_graph[source_ref_id][target_ref_id]
flow[consts.Consts.id] = sequence_flow_id
flow[consts.Consts.name] = sequence_flow_name
flow[consts.Consts.process] = process_id
flow[consts.Consts.source_ref] = source_ref_id
flow[consts.Consts.target_ref] = target_ref_id
source_node = self.diagram_graph.node[source_ref_id]
target_node = self.diagram_graph.node[target_ref_id]
flow[consts.Consts.waypoints] = \
[(source_node[consts.Consts.x], source_node[consts.Consts.y]),
(target_node[consts.Consts.x], target_node[consts.Consts.y])]
# add target node (target_ref_id) as outgoing node from source node (source_ref_id)
source_node[consts.Consts.outgoing_flow].append(sequence_flow_id)
# add source node (source_ref_id) as incoming node to target node (target_ref_id)
target_node[consts.Consts.incoming_flow].append(sequence_flow_id)
return sequence_flow_id, flow
def get_nodes_positions(self):
"""
Getter method for nodes positions.
:return: A dictionary with nodes as keys and positions as values
"""
nodes = self.get_nodes()
output = {}
for node in nodes:
output[node[0]] = (float(node[1][consts.Consts.x]), float(node[1][consts.Consts.y]))
return output
|
class BpmnDiagramGraph(object):
'''
Class BPMNDiagramGraph implements simple inner representation of BPMN 2.0 diagram,
based on NetworkX graph implementation
Fields:
* diagram_graph - networkx.Graph object, stores elements of BPMN diagram as nodes. Each edge of graph represents
sequenceFlow element. Edges are identified by IDs of nodes connected by edge. IDs are passed as edge parameters,
* sequence_flows - dictionary (associative list) of sequence flows existing in diagram.
Key attribute is sequenceFlow ID, value is a dictionary consisting three key-value pairs: "name" (sequence flow
name), "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
* collaboration - a dictionary that contains two dictionaries:
* "messageFlows" - dictionary (associative list) of message flows existing in diagram. Key attribute is
messageFlow ID, value is a dictionary consisting three key-value pairs: "name" (message flow name),
* "sourceRef" (ID of node, that is a flow source) and "targetRef" (ID of node, that is a flow target),
* "participants" - dictionary (associative list) of participants existing in diagram. Key attribute is
participant ID, value is a dictionary consisting participant attributes,
* process_elements_dictionary - dictionary that holds attribute values for imported 'process' elements.
Key is an ID of process, value is a dictionary of all process attributes,
* diagram_attributes - dictionary that contains BPMN diagram element attributes,
* plane_attributes - dictionary that contains BPMN plane element attributes.
'''
def __init__(self):
'''
Default constructor, initializes object fields with new instances.
'''
pass
def load_diagram_from_xml_file(self, filepath):
'''
Reads an XML file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath.
'''
pass
def export_xml_file(self, directory, filename):
'''
Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).
:param directory: strings representing output directory,
:param filename: string representing output file name.
'''
pass
def export_xml_file_no_di(self, directory, filename):
'''
Exports diagram inner graph to BPMN 2.0 XML file (without Diagram Interchange data).
:param directory: strings representing output directory,
:param filename: string representing output file name.
'''
pass
def load_diagram_from_csv_file(self, filepath):
'''
Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram.
Returns an instance of BPMNDiagramGraph class.
:param filepath: string with output filepath.
'''
pass
def export_csv_file(self, directory, filename):
'''
Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).
:param directory: strings representing output directory,
:param filename: string representing output file name.
'''
pass
def get_nodes(self, node_type=""):
'''
Gets all nodes of requested type. If no type is provided by user, all nodes in BPMN diagram graph are returned.
Returns a dictionary, where key is an ID of node, value is a dictionary of all node attributes.
:param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
'''
pass
def get_nodes_list_by_process_id(self, process_id):
'''
Gets all nodes of requested type. If no type is provided by user, all nodes in BPMN diagram graph are returned.
Returns a dictionary, where key is an ID of node, value is a dictionary of all node attributes.
:param process_id: string object, representing an ID of parent process element.
'''
pass
def get_node_by_id(self, node_id):
'''
Gets a node with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param node_id: string with ID of node.
'''
pass
def get_nodes_id_list_by_type(self, node_type):
'''
Get a list of node's id by requested type.
Returns a list of ids
:param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
'''
pass
def get_flows(self):
'''
Gets all graph edges (process flows).
Returns a two-dimensional dictionary, where keys are IDs of nodes connected by edge and
values are a dictionary of all edge attributes.
'''
pass
def get_flow_by_id(self, flow_id):
'''
Gets an edge (flow) with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param flow_id: string with edge ID.
'''
pass
def get_flows_list_by_process_id(self, process_id):
'''
Gets an edge (flow) with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param process_id: string object, representing an ID of parent process element.
'''
pass
def create_new_diagram_graph(self, diagram_name=""):
'''
Initializes a new BPMN diagram and sets up a basic diagram attributes.
Accepts a user-defined values for following attributes:
(Diagram element)
- name - default value empty string.
:param diagram_name: string type. Represents a user-defined value of 'BPMNDiagram' element
attribute 'name'. Default value - empty string.
'''
pass
def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False,
process_type="None"):
'''
Adds a new process to diagram and corresponding participant
process, diagram and plane
Accepts a user-defined values for following attributes:
(Process element)
- isClosed - default value false,
- isExecutable - default value false,
- processType - default value None.
:param process_name: string obejct, process name. Default value - empty string,
:param process_is_closed: boolean type. Represents a user-defined value of 'process' element
attribute 'isClosed'. Default value false,
:param process_is_executable: boolean type. Represents a user-defined value of 'process' element
attribute 'isExecutable'. Default value false,
:param process_type: string type. Represents a user-defined value of 'process' element
attribute 'procesType'. Default value "None",
'''
pass
def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None):
'''
Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type.
Adds a basic information inherited from Flow Node type.
:param process_id: string object. ID of parent process,
:param node_type: string object. Represents type of BPMN node passed to method,
:param name: string object. Name of the node,
:param node_id: string object. ID of node. Default value - None.
'''
pass
def add_task_to_diagram(self, process_id, task_name="", node_id=None):
'''
Adds a Task element to BPMN diagram.
User-defined attributes:
- name
:param process_id: string object. ID of parent process,
:param task_name: string object. Name of task,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is task ID, second a reference to created object.
'''
pass
def add_subprocess_to_diagram(self, process_id, subprocess_name, is_expanded=False, triggered_by_event=False,
node_id=None):
'''
Adds a SubProcess element to BPMN diagram.
User-defined attributes:
- name
- triggered_by_event
:param process_id: string object. ID of parent process,
:param subprocess_name: string object. Name of subprocess,
:param is_expanded: boolean value for attribute "isExpanded". Default value false,
:param triggered_by_event: boolean value for attribute "triggeredByEvent". Default value false,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is subProcess ID, second a reference to created object.
'''
pass
def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None,
parallel_multiple=False, is_interrupting=True, node_id=None):
'''
Adds a StartEvent element to BPMN diagram.
User-defined attributes:
- name
- parallel_multiple
- is_interrupting
- event definition (creates a special type of start event). Supported event definitions -
* 'message': 'messageEventDefinition',
* 'timer': 'timerEventDefinition',
* 'signal': 'signalEventDefinition',
* 'conditional': 'conditionalEventDefinition',
* 'escalation': 'escalationEventDefinition'.
:param process_id: string object. ID of parent process,
:param start_event_name: string object. Name of start event,
:param start_event_definition: list of event definitions. By default - empty,
:param parallel_multiple: boolean value for attribute "parallelMultiple",
:param is_interrupting: boolean value for attribute "isInterrupting,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is startEvent ID, second a reference to created object.
'''
pass
def add_end_event_to_diagram(self, process_id, end_event_name="", end_event_definition=None, node_id=None):
'''
Adds an EndEvent element to BPMN diagram.
User-defined attributes:
- name
- event definition (creates a special type of end event). Supported event definitions
* `terminate`: 'terminateEventDefinition',
* `signal`: 'signalEventDefinition',
* `error`: 'errorEventDefinition',
* `escalation`: 'escalationEventDefinition',
* `message`: 'messageEventDefinition',
* `compensate`: 'compensateEventDefinition'.
:param process_id: string object. ID of parent process,
:param end_event_name: string object. Name of end event,
:param end_event_definition: list of event definitions. By default - empty.
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is endEvent ID, second a reference to created object,
'''
pass
@staticmethod
def add_event_definition_element(event_type, event_definitions):
'''
Helper function, that creates event definition element (special type of event) from given parameters.
:param event_type: string object. Short name of required event definition,
:param event_definitions: dictionary of event definitions. Key is a short name of event definition,
value is a full name of event definition, as defined in BPMN 2.0 XML Schema.
'''
pass
def add_gateway_to_diagram(self, process_id, gateway_type, gateway_name="", gateway_direction="Unspecified",
node_id=None):
'''
Adds an exclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_type: string object. Type of gateway to be added.
:param gateway_name: string object. Name of exclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is gateway ID, second a reference to created object.
'''
pass
def add_exclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
default=None, node_id=None):
'''
Adds an exclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of exclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified".
:param default: string object. ID of flow node, target of gateway default path. Default value - None,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is exculusiveGateway ID, second a reference to created object.
'''
pass
def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
default=None, node_id=None):
'''
Adds an inclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param default: string object. ID of flow node, target of gateway default path. Default value - None,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is inclusiveGateway ID, second a reference to created object.
'''
pass
def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
node_id=None):
'''
Adds an parallelGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is parallelGateway ID, second a reference to created object.
'''
pass
def add_sequence_flow_to_diagram(self, process_id, source_ref_id, target_ref_id, sequence_flow_name=""):
'''
Adds a SequenceFlow element to BPMN diagram.
Requires that user passes a sourceRef and targetRef as parameters.
User-defined attributes:
- name
:param process_id: string object. ID of parent process,
:param source_ref_id: string object. ID of source node,
:param target_ref_id: string object. ID of target node,
:param sequence_flow_name: string object. Name of sequence flow.
:return: a tuple, where first value is sequenceFlow ID, second a reference to created object.
'''
pass
def get_nodes_positions(self):
'''
Getter method for nodes positions.
:return: A dictionary with nodes as keys and positions as values
'''
pass
| 29 | 28 | 18 | 2 | 8 | 8 | 2 | 1.12 | 1 | 8 | 6 | 0 | 26 | 6 | 27 | 27 | 533 | 81 | 213 | 83 | 177 | 239 | 166 | 75 | 138 | 8 | 1 | 3 | 60 |
144,103 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_import_utils.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_import_utils.BpmnImportUtils
|
class BpmnImportUtils(object):
"""
Class including utility method used in diagram importing
"""
def __init__(self):
pass
@staticmethod
def remove_namespace_from_tag_name(tag_name):
"""
Helper function, removes namespace annotation from tag name.
:param tag_name: string with tag name.
"""
return tag_name.split(':')[-1]
@staticmethod
def iterate_elements(parent):
"""
Helper function that iterates over child Nodes/Elements of parent Node/Element.
:param parent: object of Element class, representing parent element.
"""
element = parent.firstChild
while element is not None:
yield element
element = element.nextSibling
@staticmethod
def generate_nodes_clasification(bpmn_diagram):
"""
Diagram elements classification. Implementation based on article "A Simple Algorithm for Automatic Layout of
BPMN Processes".
Assigns a classification to the diagram element according to specific element parameters.
- Element - every element of the process which is not an edge,
- Start Event - all types of start events,
- End Event - all types of end events,
- Join - an element with more than one incoming edge,
- Split - an element with more than one outgoing edge.
:param bpmn_diagram: BPMNDiagramGraph class instance representing a BPMN process diagram.
:return: a dictionary of classification labels. Key - node id. Values - a list of labels.
"""
nodes_classification = {}
classification_element = "Element"
classification_start_event = "Start Event"
classification_end_event = "End Event"
task_list = bpmn_diagram.get_nodes(consts.Consts.task)
for element in task_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
subprocess_list = bpmn_diagram.get_nodes(consts.Consts.subprocess)
for element in subprocess_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
complex_gateway_list = bpmn_diagram.get_nodes(consts.Consts.complex_gateway)
for element in complex_gateway_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
event_based_gateway_list = bpmn_diagram.get_nodes(consts.Consts.event_based_gateway)
for element in event_based_gateway_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
inclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.inclusive_gateway)
for element in inclusive_gateway_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
exclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.exclusive_gateway)
for element in exclusive_gateway_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
parallel_gateway_list = bpmn_diagram.get_nodes(consts.Consts.parallel_gateway)
for element in parallel_gateway_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
start_event_list = bpmn_diagram.get_nodes(consts.Consts.start_event)
for element in start_event_list:
classification_labels = [classification_element, classification_start_event]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
intermediate_catch_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_catch_event)
for element in intermediate_catch_event_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
end_event_list = bpmn_diagram.get_nodes(consts.Consts.end_event)
for element in end_event_list:
classification_labels = [classification_element, classification_end_event]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
intermediate_throw_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_throw_event)
for element in intermediate_throw_event_list:
classification_labels = [classification_element]
BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification)
return nodes_classification
@staticmethod
def split_join_classification(element, classification_labels, nodes_classification):
"""
Add the "Split", "Join" classification, if the element qualifies for.
:param element: an element from BPMN diagram,
:param classification_labels: list of labels attached to the element,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels.
"""
classification_join = "Join"
classification_split = "Split"
if len(element[1][consts.Consts.incoming_flow]) >= 2:
classification_labels.append(classification_join)
if len(element[1][consts.Consts.outgoing_flow]) >= 2:
classification_labels.append(classification_split)
nodes_classification[element[0]] = classification_labels
|
class BpmnImportUtils(object):
'''
Class including utility method used in diagram importing
'''
def __init__(self):
pass
@staticmethod
def remove_namespace_from_tag_name(tag_name):
'''
Helper function, removes namespace annotation from tag name.
:param tag_name: string with tag name.
'''
pass
@staticmethod
def iterate_elements(parent):
'''
Helper function that iterates over child Nodes/Elements of parent Node/Element.
:param parent: object of Element class, representing parent element.
'''
pass
@staticmethod
def generate_nodes_clasification(bpmn_diagram):
'''
Diagram elements classification. Implementation based on article "A Simple Algorithm for Automatic Layout of
BPMN Processes".
Assigns a classification to the diagram element according to specific element parameters.
- Element - every element of the process which is not an edge,
- Start Event - all types of start events,
- End Event - all types of end events,
- Join - an element with more than one incoming edge,
- Split - an element with more than one outgoing edge.
:param bpmn_diagram: BPMNDiagramGraph class instance representing a BPMN process diagram.
:return: a dictionary of classification labels. Key - node id. Values - a list of labels.
'''
pass
@staticmethod
def split_join_classification(element, classification_labels, nodes_classification):
'''
Add the "Split", "Join" classification, if the element qualifies for.
:param element: an element from BPMN diagram,
:param classification_labels: list of labels attached to the element,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels.
'''
pass
| 10 | 5 | 22 | 3 | 13 | 5 | 4 | 0.4 | 1 | 1 | 1 | 0 | 1 | 0 | 5 | 5 | 123 | 22 | 72 | 30 | 62 | 29 | 68 | 26 | 62 | 12 | 1 | 1 | 19 |
144,104 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/grid_cell_class.py
|
KrzyHonk_bpmn-python.bpmn_python.grid_cell_class.GridCell
|
class GridCell(object):
"""
Helper class used for Grid cell representation. Contains cell coordinates (row and column) and reference to fow node
"""
def __init__(self, row, col, node_id):
self.row = row
self.col = col
self.node_id = node_id
def __str__(self):
return repr(self.row + " " + self.col + " " + self.node_id)
|
class GridCell(object):
'''
Helper class used for Grid cell representation. Contains cell coordinates (row and column) and reference to fow node
'''
def __init__(self, row, col, node_id):
pass
def __str__(self):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.43 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 2 | 12 | 2 | 7 | 6 | 4 | 3 | 7 | 6 | 4 | 1 | 1 | 0 | 2 |
144,105 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/metrics/test_bpmn_diagram_metrics.py
|
test_bpmn_diagram_metrics.BPMNComplexityMetricsTests
|
class BPMNComplexityMetricsTests(unittest.TestCase):
def setUp(self):
self.models = {name: BpmnDiagramGraph()
for name in ['SIMPLE', 'COMPLEX', 'WITH_CYCLES', 'WITH_CROSSING_POINT']
}
self.models['SIMPLE'].load_diagram_from_xml_file(
os.path.abspath("../examples/xml_import_export/bpmn_editor_simple_example.xml")),
self.models['COMPLEX'].load_diagram_from_xml_file(
os.path.abspath("../examples/xml_import_export/camunda_complex_example.bpmn")),
self.models['WITH_CYCLES'].load_diagram_from_xml_file(
os.path.abspath("../examples/metrics/cycles_test.bpmn")),
self.models['WITH_CROSSING_POINT'].load_diagram_from_xml_file(
os.path.abspath("../examples/metrics/crossing_point_test.bpmn")),
def testTNSEMetricForSimpleModel(self):
self.assertEqual(
metrics.TNSE_metric(self.models['SIMPLE']), 1
)
def testTNSEMetricForComplexModel(self):
self.assertEqual(
metrics.TNSE_metric(self.models['COMPLEX']), 1
)
def testTNSEForModelWithCycles(self):
self.assertEqual(
metrics.TNSE_metric(self.models['WITH_CYCLES']), 1
)
def testTNSEForModelWithCrossingPoint(self):
self.assertEqual(
metrics.TNSE_metric(self.models['WITH_CROSSING_POINT']), 1
)
def testTNIEMetricForSimpleModel(self):
self.assertEqual(
metrics.TNIE_metric(self.models['SIMPLE']), 0
)
def testTNIEMetricForComplexModel(self):
self.assertEqual(
metrics.TNIE_metric(self.models['COMPLEX']), 2
)
def testTNIEForModelWithCycles(self):
self.assertEqual(
metrics.TNIE_metric(self.models['WITH_CYCLES']), 0
)
def testTNIEForModelWithCrossingPoint(self):
self.assertEqual(
metrics.TNIE_metric(self.models['WITH_CROSSING_POINT']), 0
)
def testTNEEMetricForSimpleModel(self):
self.assertEqual(
metrics.TNEE_metric(self.models['SIMPLE']), 1
)
def testTNEEMetricForComplexModel(self):
self.assertEqual(
metrics.TNEE_metric(self.models['COMPLEX']), 1
)
def testTNEEForModelWithCycles(self):
self.assertEqual(
metrics.TNEE_metric(self.models['WITH_CYCLES']), 2
)
def testTNEEForModelWithCrossingPoint(self):
self.assertEqual(
metrics.TNEE_metric(self.models['WITH_CROSSING_POINT']), 1
)
def testTNEMetricForSimpleModel(self):
self.assertEqual(
metrics.TNE_metric(self.models['SIMPLE']), 2
)
def testTNEMetricForComplexModel(self):
self.assertEqual(
metrics.TNE_metric(self.models['COMPLEX']), 4
)
def testTNEForModelWithCycles(self):
self.assertEqual(
metrics.TNE_metric(self.models['WITH_CYCLES']), 3
)
def testTNEForModelWithCrossingPoint(self):
self.assertEqual(
metrics.TNE_metric(self.models['WITH_CROSSING_POINT']), 2
)
def testNOAMetricForSimpleModel(self):
self.assertEqual(
metrics.NOA_metric(self.models['SIMPLE']), 4
)
def testNOAMetricForComplexModel(self):
self.assertEqual(
metrics.NOA_metric(self.models['COMPLEX']), 9
)
def testNOAMetricForModelWithCycles(self):
self.assertEqual(
metrics.NOA_metric(self.models['WITH_CYCLES']), 11
)
def testNOAMetricForModelWithCrossingPoint(self):
self.assertEqual(
metrics.NOA_metric(self.models['WITH_CROSSING_POINT']), 3
)
def testNOACMetricForSimpleModel(self):
self.assertEqual(
metrics.NOAC_metric(self.models['SIMPLE']), 8
)
def testNOACMetricForComplexModel(self):
self.assertEqual(
metrics.NOAC_metric(self.models['COMPLEX']), 21
)
def testNOACMetricForModelWithCycles(self):
self.assertEqual(
metrics.NOAC_metric(self.models['WITH_CYCLES']), 16
)
def testNOACMetricForModelWithCrossingPoint(self):
self.assertEqual(
metrics.NOAC_metric(self.models['WITH_CROSSING_POINT']), 7
)
def testNOAJSMetricForSimpleModel(self):
self.assertEqual(
metrics.NOAJS_metric(self.models['SIMPLE']), 6
)
def testNOAJSMetricForComplexModel(self):
self.assertEqual(
metrics.NOAJS_metric(self.models['COMPLEX']), 17
)
def testNOAJSMetricForModelWithCycles(self):
self.assertEqual(
metrics.NOAJS_metric(self.models['WITH_CYCLES']), 13
)
def testNOAJSMetricForModelWithCrossingPoint(self):
self.assertEqual(
metrics.NOAJS_metric(self.models['WITH_CROSSING_POINT']), 5
)
def testNumberOfNodesForSimpleModel(self):
self.assertEqual(
metrics.NumberOfNodes_metric(self.models['SIMPLE']), 8
)
def testNumberOfNodesForComplexModel(self):
self.assertEqual(
metrics.NumberOfNodes_metric(self.models['COMPLEX']), 21
)
def testNumberOfNodesForModelWithCycles(self):
self.assertEqual(
metrics.NumberOfNodes_metric(self.models['WITH_CYCLES']), 16
)
def testNumberOfNodesForModelWithCrossingPoint(self):
self.assertEqual(
metrics.NumberOfNodes_metric(self.models['WITH_CROSSING_POINT']), 7
)
def testGatewayHeterogenityMetricForSimpleModel(self):
self.assertEqual(
metrics.GatewayHeterogenity_metric(self.models['SIMPLE']), 1
)
def testGatewayHeterogenityMetricForComplexModel(self):
self.assertEqual(
metrics.GatewayHeterogenity_metric(self.models['COMPLEX']), 4
)
def testGatewayHeterogenityMetricForModelWithCycles(self):
self.assertEqual(
metrics.GatewayHeterogenity_metric(self.models['WITH_CYCLES']), 1
)
def testGatewayHeterogenityMetricForModelWithCrossingPoint(self):
self.assertEqual(
metrics.GatewayHeterogenity_metric(self.models['WITH_CROSSING_POINT']), 1
)
def testCoefficientOfNetworkComplexityMetricForSimpleModel(self):
self.assertAlmostEqual(
metrics.CoefficientOfNetworkComplexity_metric(self.models['SIMPLE']), 1.0,
places=3
)
def testCoefficientOfNetworkComplexityMetricForComplexModel(self):
self.assertAlmostEqual(
metrics.CoefficientOfNetworkComplexity_metric(self.models['COMPLEX']), 1.143,
places=3
)
def testCoefficientOfNetworkComplexityMetricForModelWithCycles(self):
self.assertAlmostEqual(
metrics.CoefficientOfNetworkComplexity_metric(self.models['WITH_CYCLES']), 1.0,
places=3
)
def testCoefficientOfNetworkComplexityMetricForModelWithCrossingPoint(self):
self.assertAlmostEqual(
metrics.CoefficientOfNetworkComplexity_metric(self.models['WITH_CROSSING_POINT']), 1.0
)
def testAverageGatewayDegreeMetricForSimpleModel(self):
self.assertAlmostEqual(
metrics.AverageGatewayDegree_metric(self.models['SIMPLE']), 3.0,
places=3
)
def testAverageGatewayDegreeMetricForComplexModel(self):
self.assertAlmostEqual(
metrics.AverageGatewayDegree_metric(self.models['COMPLEX']), 3.0,
places=3
)
def testAverageGatewayDegreeForModelWithCycles(self):
self.assertAlmostEqual(
metrics.AverageGatewayDegree_metric(self.models['WITH_CYCLES']), 3.5,
places=3
)
def testAverageGatewayDegreeForModelWithCrossingPoint(self):
self.assertAlmostEqual(
metrics.AverageGatewayDegree_metric(self.models['WITH_CROSSING_POINT']), 3.0
)
def testDurfeeSquareMetricForSimpleModel(self):
self.assertEqual(
metrics.DurfeeSquare_metric(self.models['SIMPLE']), 2
)
def testDurfeeSquareMetricForComplexModel(self):
self.assertEqual(
metrics.DurfeeSquare_metric(self.models['COMPLEX']), 2
)
def testDurfeeSquareForModelWithCycles(self):
self.assertEqual(
metrics.DurfeeSquare_metric(self.models['WITH_CYCLES']), 2
)
def testDurfeeSquareForModelWithCrossingPoint(self):
self.assertEqual(
metrics.DurfeeSquare_metric(self.models['WITH_CROSSING_POINT']), 2
)
def testPerfectSquareMetricForSimpleModel(self):
self.assertEqual(
metrics.PerfectSquare_metric(self.models['SIMPLE']), 2
)
def testPerfectSquareMetricForComplexModel(self):
self.assertEqual(
metrics.PerfectSquare_metric(self.models['COMPLEX']), 3
)
def testPerfectSquareForModelWithCycles(self):
self.assertEqual(
metrics.PerfectSquare_metric(self.models['WITH_CYCLES']), 4
)
def testPerfectSquareForModelWithCrossingPoint(self):
self.assertEqual(
metrics.PerfectSquare_metric(self.models['WITH_CROSSING_POINT']), 2
)
def tearDown(self):
pass
|
class BPMNComplexityMetricsTests(unittest.TestCase):
def setUp(self):
pass
def testTNSEMetricForSimpleModel(self):
pass
def testTNSEMetricForComplexModel(self):
pass
def testTNSEForModelWithCycles(self):
pass
def testTNSEForModelWithCrossingPoint(self):
pass
def testTNIEMetricForSimpleModel(self):
pass
def testTNIEMetricForComplexModel(self):
pass
def testTNIEForModelWithCycles(self):
pass
def testTNIEForModelWithCrossingPoint(self):
pass
def testTNEEMetricForSimpleModel(self):
pass
def testTNEEMetricForComplexModel(self):
pass
def testTNEEForModelWithCycles(self):
pass
def testTNEEForModelWithCrossingPoint(self):
pass
def testTNEMetricForSimpleModel(self):
pass
def testTNEMetricForComplexModel(self):
pass
def testTNEForModelWithCycles(self):
pass
def testTNEForModelWithCrossingPoint(self):
pass
def testNOAMetricForSimpleModel(self):
pass
def testNOAMetricForComplexModel(self):
pass
def testNOAMetricForModelWithCycles(self):
pass
def testNOAMetricForModelWithCrossingPoint(self):
pass
def testNOACMetricForSimpleModel(self):
pass
def testNOACMetricForComplexModel(self):
pass
def testNOACMetricForModelWithCycles(self):
pass
def testNOACMetricForModelWithCrossingPoint(self):
pass
def testNOAJSMetricForSimpleModel(self):
pass
def testNOAJSMetricForComplexModel(self):
pass
def testNOAJSMetricForModelWithCycles(self):
pass
def testNOAJSMetricForModelWithCrossingPoint(self):
pass
def testNumberOfNodesForSimpleModel(self):
pass
def testNumberOfNodesForComplexModel(self):
pass
def testNumberOfNodesForModelWithCycles(self):
pass
def testNumberOfNodesForModelWithCrossingPoint(self):
pass
def testGatewayHeterogenityMetricForSimpleModel(self):
pass
def testGatewayHeterogenityMetricForComplexModel(self):
pass
def testGatewayHeterogenityMetricForModelWithCycles(self):
pass
def testGatewayHeterogenityMetricForModelWithCrossingPoint(self):
pass
def testCoefficientOfNetworkComplexityMetricForSimpleModel(self):
pass
def testCoefficientOfNetworkComplexityMetricForComplexModel(self):
pass
def testCoefficientOfNetworkComplexityMetricForModelWithCycles(self):
pass
def testCoefficientOfNetworkComplexityMetricForModelWithCrossingPoint(self):
pass
def testAverageGatewayDegreeMetricForSimpleModel(self):
pass
def testAverageGatewayDegreeMetricForComplexModel(self):
pass
def testAverageGatewayDegreeForModelWithCycles(self):
pass
def testAverageGatewayDegreeForModelWithCrossingPoint(self):
pass
def testDurfeeSquareMetricForSimpleModel(self):
pass
def testDurfeeSquareMetricForComplexModel(self):
pass
def testDurfeeSquareForModelWithCycles(self):
pass
def testDurfeeSquareForModelWithCrossingPoint(self):
pass
def testPerfectSquareMetricForSimpleModel(self):
pass
def testPerfectSquareMetricForComplexModel(self):
pass
def testPerfectSquareForModelWithCycles(self):
pass
def testPerfectSquareForModelWithCrossingPoint(self):
pass
def tearDown(self):
pass
| 55 | 0 | 5 | 1 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 54 | 1 | 54 | 126 | 313 | 84 | 229 | 56 | 174 | 0 | 113 | 56 | 58 | 1 | 2 | 0 | 54 |
144,106 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/signavio_simple_test.py
|
signavio_simple_test.SignavioSimpleTests
|
class SignavioSimpleTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using a simple example of BPMN diagram
created in Signavio Editor.
"""
output_directory = "./output/test-signavio/simple/"
example_path = "../examples/xml_import_export/signavio_simple_example.bpmn"
output_file_with_di = "signavio-example-output.xml"
output_file_no_di = "signavio-example-output-no-di.xml"
output_dot_file = "signavio-example"
output_png_file = "signavio-example"
def test_loadSignavioSimpleDiagram(self):
"""
Test for importing a simple Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
def test_loadSignavioSimpleDiagramAndVisualize(self):
"""
Test for importing a simple Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
# Uncomment line below to get a simple view of created diagram
# visualizer.visualize_diagram(bpmn_graph)
visualizer.bpmn_diagram_to_dot_file(bpmn_graph, self.output_directory + self.output_dot_file)
visualizer.bpmn_diagram_to_png(bpmn_graph, self.output_directory + self.output_png_file)
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
|
class SignavioSimpleTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using a simple example of BPMN diagram
created in Signavio Editor.
'''
def test_loadSignavioSimpleDiagram(self):
'''
Test for importing a simple Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
'''
pass
def test_loadSignavioSimpleDiagramAndVisualize(self):
'''
Test for importing a simple Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
'''
pass
| 3 | 3 | 11 | 0 | 6 | 5 | 1 | 0.74 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 74 | 35 | 2 | 19 | 11 | 16 | 14 | 19 | 11 | 16 | 1 | 2 | 0 | 2 |
144,107 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/signavio_complex_test.py
|
signavio_complex_test.SignavioComplexTests
|
class SignavioComplexTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using a complex example of BPMN diagram
created in Signavio Editor.
"""
output_directory = "./output/test-signavio/complex/"
example_path = "../examples/xml_import_export/signavio_complex_example.bpmn"
output_file_with_di = "signavio-complex-example-output.xml"
output_file_no_di = "signavio-complex-example-output-no-di.xml"
output_dot_file = "signavio-complex-example"
output_png_file = "signavio-complex-example"
def test_loadSignavioComplexDiagram(self):
"""
Test for importing a complex Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
def test_loadSignavioComplexDiagramAndVisualize(self):
"""
Test for importing a complex Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
# Uncomment line below to get a simple view of created diagram
# visualizer.visualize_diagram(bpmn_graph)
visualizer.bpmn_diagram_to_dot_file(bpmn_graph, self.output_directory + self.output_dot_file)
visualizer.bpmn_diagram_to_png(bpmn_graph, self.output_directory + self.output_png_file)
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
|
class SignavioComplexTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using a complex example of BPMN diagram
created in Signavio Editor.
'''
def test_loadSignavioComplexDiagram(self):
'''
Test for importing a complex Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
'''
pass
def test_loadSignavioComplexDiagramAndVisualize(self):
'''
Test for importing a complex Signavio diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
'''
pass
| 3 | 3 | 11 | 0 | 6 | 5 | 1 | 0.74 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 74 | 35 | 2 | 19 | 11 | 16 | 14 | 19 | 11 | 16 | 1 | 2 | 0 | 2 |
144,108 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/manually_generated_simple_diagram.py
|
manually_generated_simple_diagram.ManualGenerationSimpleTests
|
class ManualGenerationSimpleTests(unittest.TestCase):
"""
This class contains test for manual diagram generation functionality.
"""
output_directory = "./output/test-manual/simple/"
output_file_with_di = "manually-generated-output.xml"
output_file_no_di = "manually-generated-output-no-di.xml"
output_dot_file = "manually-generated-example"
output_png_file = "manually-generated-example"
def test_create_diagram_manually(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="start_event",
start_event_definition="timer")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id, "start_to_one")
[exclusive_gate_fork_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_fork")
[task1_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1_ex")
[task2_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2_ex")
[exclusive_gate_join_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, exclusive_gate_fork_id, "one_to_ex_fork")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task1_ex_id, "ex_fork_to_ex_one")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task2_ex_id, "ex_fork_to_ex_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_ex_id, exclusive_gate_join_id, "ex_one_to_ex_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_ex_id, exclusive_gate_join_id, "ex_two_to_ex_join")
[task2_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2")
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="end_event",
end_event_definition="message")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_join_id, task2_id, "ex_join_to_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_id, end_id, "two_to_end")
layouter.generate_layout(bpmn_graph)
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
# Uncomment line below to get a simple view of created diagram
# visualizer.visualize_diagram(bpmn_graph)
visualizer.bpmn_diagram_to_dot_file(bpmn_graph, self.output_directory + self.output_dot_file)
visualizer.bpmn_diagram_to_png(bpmn_graph, self.output_directory + self.output_png_file)
|
class ManualGenerationSimpleTests(unittest.TestCase):
'''
This class contains test for manual diagram generation functionality.
'''
def test_create_diagram_manually(self):
pass
| 2 | 1 | 36 | 5 | 29 | 2 | 1 | 0.14 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 46 | 6 | 35 | 9 | 33 | 5 | 31 | 9 | 29 | 1 | 2 | 0 | 1 |
144,109 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/bpmn_python/bpmn_process_csv_export.py
|
KrzyHonk_bpmn-python.bpmn_python.bpmn_process_csv_export.BpmnDiagramGraphCsvExport
|
class BpmnDiagramGraphCsvExport(object):
# TODO read user and add 'who' param
# TODO loops
"""
Class that provides implementation of exporting process to CSV functionality
"""
gateways_list = ["exclusiveGateway", "inclusiveGateway", "parallelGateway"]
tasks_list = ["task", "subProcess"]
classification_element = "Element"
classification_start_event = "Start Event"
classification_end_event = "End Event"
classification_join = "Join"
classification_split = "Split"
'''
Supported start event types: normal, timer, message.
Supported end event types: normal, message.
'''
events_list = ["startEvent", "endEvent"]
lanes_list = ["process", "laneSet", "lane"]
def __init__(self):
pass
@staticmethod
def export_process_to_csv(bpmn_diagram, directory, filename):
"""
Root method of CSV export functionality.
:param bpmn_diagram: an instance of BpmnDiagramGraph class,
:param directory: a string object, which is a path of output directory,
:param filename: a string object, which is a name of output file.
"""
nodes = copy.deepcopy(bpmn_diagram.get_nodes())
start_nodes = []
export_elements = []
for node in nodes:
incoming_list = node[1].get(consts.Consts.incoming_flow)
if len(incoming_list) == 0:
start_nodes.append(node)
if len(start_nodes) != 1:
raise bpmn_exception.BpmnPythonError("Exporting to CSV format accepts only one start event")
nodes_classification = utils.BpmnImportUtils.generate_nodes_clasification(bpmn_diagram)
start_node = start_nodes.pop()
BpmnDiagramGraphCsvExport.export_node(bpmn_diagram, export_elements, start_node, nodes_classification)
try:
os.makedirs(directory)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
file_object = open(directory + filename, "w")
file_object.write("Order,Activity,Condition,Who,Subprocess,Terminated\n")
BpmnDiagramGraphCsvExport.write_export_node_to_file(file_object, export_elements)
file_object.close()
@staticmethod
def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="",
add_join=False):
"""
General method for node exporting
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels,
:param order: the order param of exported node,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:param add_join: boolean flag. Used to indicate if "Join" element should be added to CSV.
:return: None or the next node object if the exported node was a gateway join.
"""
node_type = node[1][consts.Consts.type]
if node_type == consts.Consts.start_event:
return BpmnDiagramGraphCsvExport.export_start_event(bpmn_graph, export_elements, node, nodes_classification,
order=order, prefix=prefix, condition=condition,
who=who)
elif node_type == consts.Consts.end_event:
return BpmnDiagramGraphCsvExport.export_end_event(export_elements, node, order=order, prefix=prefix,
condition=condition, who=who)
else:
return BpmnDiagramGraphCsvExport.export_element(bpmn_graph, export_elements, node, nodes_classification,
order=order, prefix=prefix, condition=condition, who=who,
add_join=add_join)
@staticmethod
def export_element(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="",
who="", add_join=False):
"""
Export a node with "Element" classification (task, subprocess or gateway)
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels,
:param order: the order param of exported node,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:param add_join: boolean flag. Used to indicate if "Join" element should be added to CSV.
:return: None or the next node object if the exported node was a gateway join.
"""
node_type = node[1][consts.Consts.type]
node_classification = nodes_classification[node[0]]
outgoing_flows = node[1].get(consts.Consts.outgoing_flow)
if node_type != consts.Consts.parallel_gateway and consts.Consts.default in node[1] \
and node[1][consts.Consts.default] is not None:
default_flow_id = node[1][consts.Consts.default]
else:
default_flow_id = None
if BpmnDiagramGraphCsvExport.classification_join in node_classification and not add_join:
# If the node is a join, then retract the recursion back to the split.
# In case of activity - return current node. In case of gateway - return outgoing node
# (we are making assumption that join has only one outgoing node)
if node_type == consts.Consts.task or node_type == consts.Consts.subprocess:
return node
else:
outgoing_flow_id = outgoing_flows[0]
outgoing_flow = bpmn_graph.get_flow_by_id(outgoing_flow_id)
outgoing_node = bpmn_graph.get_node_by_id(outgoing_flow[2][consts.Consts.target_ref])
return outgoing_node
else:
if node_type == consts.Consts.task:
export_elements.append({"Order": prefix + str(order), "Activity": node[1][consts.Consts.node_name],
"Condition": condition, "Who": who, "Subprocess": "", "Terminated": ""})
elif node_type == consts.Consts.subprocess:
export_elements.append({"Order": prefix + str(order), "Activity": node[1][consts.Consts.node_name],
"Condition": condition, "Who": who, "Subprocess": "yes", "Terminated": ""})
if BpmnDiagramGraphCsvExport.classification_split in node_classification:
next_node = None
alphabet_suffix_index = 0
for outgoing_flow_id in outgoing_flows:
outgoing_flow = bpmn_graph.get_flow_by_id(outgoing_flow_id)
outgoing_node = bpmn_graph.get_node_by_id(outgoing_flow[2][consts.Consts.target_ref])
# This will work only up to 26 outgoing flows
suffix = string.ascii_lowercase[alphabet_suffix_index]
next_prefix = prefix + str(order) + suffix
alphabet_suffix_index += 1
# parallel gateway does not uses conditions
if node_type != consts.Consts.parallel_gateway and consts.Consts.name in outgoing_flow[2] \
and outgoing_flow[2][consts.Consts.name] is not None:
condition = outgoing_flow[2][consts.Consts.name]
else:
condition = ""
if BpmnDiagramGraphCsvExport.classification_join in nodes_classification[outgoing_node[0]]:
export_elements.append(
{"Order": next_prefix + str(1), "Activity": "goto " + prefix + str(order + 1),
"Condition": condition, "Who": who, "Subprocess": "", "Terminated": ""})
elif outgoing_flow_id == default_flow_id:
tmp_next_node = BpmnDiagramGraphCsvExport.export_node(bpmn_graph, export_elements, outgoing_node,
nodes_classification, 1, next_prefix, "else",
who)
if tmp_next_node is not None:
next_node = tmp_next_node
else:
tmp_next_node = BpmnDiagramGraphCsvExport.export_node(bpmn_graph, export_elements, outgoing_node,
nodes_classification, 1, next_prefix,
condition, who)
if tmp_next_node is not None:
next_node = tmp_next_node
if next_node is not None:
return BpmnDiagramGraphCsvExport.export_node(bpmn_graph, export_elements, next_node,
nodes_classification, order=(order + 1), prefix=prefix,
who=who, add_join=True)
elif len(outgoing_flows) == 1:
outgoing_flow_id = outgoing_flows[0]
outgoing_flow = bpmn_graph.get_flow_by_id(outgoing_flow_id)
outgoing_node = bpmn_graph.get_node_by_id(outgoing_flow[2][consts.Consts.target_ref])
return BpmnDiagramGraphCsvExport.export_node(bpmn_graph, export_elements, outgoing_node,
nodes_classification, order=(order + 1), prefix=prefix,
who=who)
else:
return None
@staticmethod
def export_start_event(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="",
who=""):
"""
Start event export
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param order: the order param of exported node,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:return: None or the next node object if the exported node was a gateway join.
"""
# Assuming that there is only one event definition
event_definitions = node[1].get(consts.Consts.event_definitions)
if event_definitions is not None and len(event_definitions) > 0:
event_definition = node[1][consts.Consts.event_definitions][0]
else:
event_definition = None
if event_definition is None:
activity = node[1][consts.Consts.node_name]
elif event_definition[consts.Consts.definition_type] == "messageEventDefinition":
activity = "message " + node[1][consts.Consts.node_name]
elif event_definition[consts.Consts.definition_type] == "timerEventDefinition":
activity = "timer " + node[1][consts.Consts.node_name]
else:
activity = node[1][consts.Consts.node_name]
export_elements.append({"Order": prefix + str(order), "Activity": activity, "Condition": condition,
"Who": who, "Subprocess": "", "Terminated": ""})
outgoing_flow_id = node[1][consts.Consts.outgoing_flow][0]
outgoing_flow = bpmn_graph.get_flow_by_id(outgoing_flow_id)
outgoing_node = bpmn_graph.get_node_by_id(outgoing_flow[2][consts.Consts.target_ref])
return BpmnDiagramGraphCsvExport.export_node(bpmn_graph, export_elements, outgoing_node, nodes_classification,
order + 1, prefix, who)
@staticmethod
def export_end_event(export_elements, node, order=0, prefix="", condition="", who=""):
"""
End event export
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param order: the order param of exported node,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:return: None or the next node object if the exported node was a gateway join.
"""
# Assuming that there is only one event definition
event_definitions = node[1].get(consts.Consts.event_definitions)
if event_definitions is not None and len(event_definitions) > 0:
event_definition = node[1][consts.Consts.event_definitions][0]
else:
event_definition = None
if event_definition is None:
activity = node[1][consts.Consts.node_name]
elif event_definition[consts.Consts.definition_type] == "messageEventDefinition":
activity = "message " + node[1][consts.Consts.node_name]
else:
activity = node[1][consts.Consts.node_name]
export_elements.append({"Order": prefix + str(order), "Activity": activity, "Condition": condition, "Who": who,
"Subprocess": "", "Terminated": "yes"})
# No outgoing elements for EndEvent
return None
@staticmethod
def write_export_node_to_file(file_object, export_elements):
"""
Exporting process to CSV file
:param file_object: object of File class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document.
"""
for export_element in export_elements:
# Order,Activity,Condition,Who,Subprocess,Terminated
file_object.write(
export_element["Order"] + "," + export_element["Activity"] + "," + export_element["Condition"] + "," +
export_element["Who"] + "," + export_element["Subprocess"] + "," + export_element["Terminated"] + "\n")
|
class BpmnDiagramGraphCsvExport(object):
'''
Class that provides implementation of exporting process to CSV functionality
'''
def __init__(self):
pass
@staticmethod
def export_process_to_csv(bpmn_diagram, directory, filename):
'''
Root method of CSV export functionality.
:param bpmn_diagram: an instance of BpmnDiagramGraph class,
:param directory: a string object, which is a path of output directory,
:param filename: a string object, which is a name of output file.
'''
pass
@staticmethod
def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="",
add_join=False):
'''
General method for node exporting
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels,
:param order: the order param of exported node,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:param add_join: boolean flag. Used to indicate if "Join" element should be added to CSV.
:return: None or the next node object if the exported node was a gateway join.
'''
pass
@staticmethod
def export_element(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="",
who="", add_join=False):
'''
Export a node with "Element" classification (task, subprocess or gateway)
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels,
:param order: the order param of exported node,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:param add_join: boolean flag. Used to indicate if "Join" element should be added to CSV.
:return: None or the next node object if the exported node was a gateway join.
'''
pass
@staticmethod
def export_start_event(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="",
who=""):
'''
Start event export
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param order: the order param of exported node,
:param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:return: None or the next node object if the exported node was a gateway join.
'''
pass
@staticmethod
def export_end_event(export_elements, node, order=0, prefix="", condition="", who=""):
'''
End event export
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
:param order: the order param of exported node,
:param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify
the branch
:param condition: the condition param of exported node,
:param who: the condition param of exported node,
:return: None or the next node object if the exported node was a gateway join.
'''
pass
@staticmethod
def write_export_node_to_file(file_object, export_elements):
'''
Exporting process to CSV file
:param file_object: object of File class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document.
'''
pass
| 14 | 7 | 35 | 3 | 21 | 11 | 5 | 0.52 | 1 | 5 | 3 | 0 | 1 | 0 | 7 | 7 | 282 | 32 | 164 | 58 | 147 | 86 | 113 | 48 | 105 | 15 | 1 | 4 | 36 |
144,110 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/csv_import/csv_import_test.py
|
csv_import_test.CsvExportTests
|
class CsvExportTests(unittest.TestCase):
"""
This class contains test for manual diagram generation functionality.
"""
output_directory = "./output/"
input_directory = "./input/"
def test_csv_import_csv_export(self):
processes = ["pizza-order", "airline-checkin", "order-processing"]
for process in processes:
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_csv_file(os.path.abspath(self.input_directory + process + ".csv"))
bpmn_graph.export_csv_file(self.output_directory, process + ".csv")
cmp_result = filecmp.cmp(self.input_directory + process + ".csv", self.output_directory, process + ".csv")
# unittest.TestCase.assertTrue(self, cmp_result) # unfortunatelly csv export has bugs
bpmn_graph.export_xml_file_no_di(self.output_directory, process + ".bpmn")
|
class CsvExportTests(unittest.TestCase):
'''
This class contains test for manual diagram generation functionality.
'''
def test_csv_import_csv_export(self):
pass
| 2 | 1 | 10 | 1 | 8 | 1 | 2 | 0.36 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 17 | 2 | 11 | 8 | 9 | 4 | 11 | 8 | 9 | 2 | 2 | 1 | 2 |
144,111 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/csv_export/csv_export_test.py
|
csv_export_test.CsvExportTests
|
class CsvExportTests(unittest.TestCase):
"""
This class contains test for manual diagram generation functionality.
"""
output_directory = "./output/test-csv-export/"
example_directory = "../examples/csv_export/"
def test_csv_export_bank_account_example(self):
# TODO not working correctly, problem with nested splits
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_directory + "bank-account-process.bpmn"))
bpmn_graph.export_csv_file(self.output_directory, "bank-account-process.csv")
def test_csv_export_checkin_process_example(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_directory + "checkin-process.bpmn"))
bpmn_graph.export_csv_file(self.output_directory, "checkin-process.csv")
def test_csv_export_credit_process_example(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_directory + "credit-process.bpmn"))
bpmn_graph.export_csv_file(self.output_directory, "credit-process.csv")
def test_csv_export_order_processing_example(self):
# TODO not working correctly, problem with nested splits
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_directory + "order-processing.bpmn"))
bpmn_graph.export_csv_file(self.output_directory, "order-processing.csv")
def test_csv_export_pizza_order_example(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_directory + "pizza-order.bpmn"))
bpmn_graph.export_csv_file(self.output_directory, "pizza-order.csv")
def test_csv_export_tram_process_example(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_directory + "tram-process.bpmn"))
# TODO Problem with the loops
#bpmn_graph.export_csv_file(self.output_directory, "tram-process.csv")
def test_csv_export_manual_simple_diagram(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="Start event",
start_event_definition="timer")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 1")
[subprocess1_id, _] = bpmn_graph.add_subprocess_to_diagram(process_id, subprocess_name="Subprocess 1")
[subprocess2_id, _] = bpmn_graph.add_subprocess_to_diagram(process_id, subprocess_name="Subprocess 2")
[task2_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 2")
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="End event",
end_event_definition="message")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id,
sequence_flow_name="start_to_task_one")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, subprocess1_id,
sequence_flow_name="task_one_to_subprocess_one")
bpmn_graph.add_sequence_flow_to_diagram(process_id, subprocess1_id, subprocess2_id,
sequence_flow_name="subprocess_one_to_subprocess_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, subprocess2_id, task2_id,
sequence_flow_name="subprocess_two_to_task_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_id, end_id,
sequence_flow_name="task_two_to_end")
bpmn_graph.export_csv_file(self.output_directory, "simple_diagram.csv")
bpmn_graph.export_xml_file(self.output_directory, "simple_diagram.bpmn")
def test_csv_export_diagram_with_exclusive_parallel_gateway(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="Start event",
start_event_definition="timer")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 1")
[exclusive_gate_fork_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="Exclusive gate fork")
[task2_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 2")
[task3_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 3")
[task6_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 6")
[exclusive_gate_join_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="Exclusive gate join")
[parallel_gate_fork_id, _] = bpmn_graph.add_parallel_gateway_to_diagram(process_id,
gateway_name="Parallel gateway fork")
[task4_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 4")
[task5_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 5")
[parallel_gate_join_id, _] = bpmn_graph.add_parallel_gateway_to_diagram(process_id,
gateway_name="Parallel gateway join")
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="End event",
end_event_definition="message")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id,
sequence_flow_name="Start to one")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, exclusive_gate_fork_id,
sequence_flow_name="Task one to exclusive fork")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task2_id,
sequence_flow_name="Exclusive fork to task two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_id, task3_id,
sequence_flow_name="Task two to task three")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, parallel_gate_fork_id,
sequence_flow_name="Exclusive fork to parallel fork")
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_fork_id, task4_id,
sequence_flow_name="Parallel fork to task four")
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_fork_id, task5_id,
sequence_flow_name="Parallel fork to task five")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task4_id, parallel_gate_join_id,
sequence_flow_name="Task four to parallel join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task5_id, parallel_gate_join_id,
sequence_flow_name="Task five to parallel join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_join_id, task6_id,
sequence_flow_name="Parallel join to task six")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task3_id, exclusive_gate_join_id,
sequence_flow_name="Task three to exclusive join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task6_id, exclusive_gate_join_id,
sequence_flow_name="Task six to exclusive join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_join_id, end_id,
sequence_flow_name="Exclusive join to end event")
bpmn_graph.export_csv_file(self.output_directory, "exclusive_parallel_gateways_diagram.csv")
bpmn_graph.export_xml_file(self.output_directory, "exclusive_parallel_gateways_diagram.bpmn")
def test_csv_export_diagram_with_inclusive_parallel_gateway(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="Start event",
start_event_definition="timer")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 1")
[exclusive_gate_fork_id, _] = bpmn_graph.add_inclusive_gateway_to_diagram(process_id,
gateway_name="Inclusive gate fork")
[task2_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 2")
[task3_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 3")
[task6_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 6")
[exclusive_gate_join_id, _] = bpmn_graph.add_inclusive_gateway_to_diagram(process_id,
gateway_name="Inclusive gate join")
[parallel_gate_fork_id, _] = bpmn_graph.add_parallel_gateway_to_diagram(process_id,
gateway_name="Parallel gateway fork")
[task4_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 4")
[task5_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="Task 5")
[parallel_gate_join_id, _] = bpmn_graph.add_parallel_gateway_to_diagram(process_id,
gateway_name="Parallel gateway join")
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="End event",
end_event_definition="message")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id,
sequence_flow_name="Start to one")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, exclusive_gate_fork_id,
sequence_flow_name="Task one to exclusive fork")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task2_id,
sequence_flow_name="Condition: approved")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_id, task3_id,
sequence_flow_name="Task two to task three")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, parallel_gate_fork_id,
sequence_flow_name="Condition: rejected")
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_fork_id, task4_id,
sequence_flow_name="Parallel fork to task four")
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_fork_id, task5_id,
sequence_flow_name="Parallel fork to task five")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task4_id, parallel_gate_join_id,
sequence_flow_name="Task four to parallel join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task5_id, parallel_gate_join_id,
sequence_flow_name="Task five to parallel join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_join_id, task6_id,
sequence_flow_name="Parallel join to task six")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task3_id, exclusive_gate_join_id,
sequence_flow_name="Task three to exclusive join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task6_id, exclusive_gate_join_id,
sequence_flow_name="Task six to exclusive join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_join_id, end_id,
sequence_flow_name="Exclusive join to end event")
bpmn_graph.export_csv_file(self.output_directory, "inclusive_parallel_gateways_diagram.csv")
bpmn_graph.export_xml_file(self.output_directory, "inclusive_parallel_gateways_diagram.bpmn")
|
class CsvExportTests(unittest.TestCase):
'''
This class contains test for manual diagram generation functionality.
'''
def test_csv_export_bank_account_example(self):
pass
def test_csv_export_checkin_process_example(self):
pass
def test_csv_export_credit_process_example(self):
pass
def test_csv_export_order_processing_example(self):
pass
def test_csv_export_pizza_order_example(self):
pass
def test_csv_export_tram_process_example(self):
pass
def test_csv_export_manual_simple_diagram(self):
pass
def test_csv_export_diagram_with_exclusive_parallel_gateway(self):
pass
def test_csv_export_diagram_with_inclusive_parallel_gateway(self):
pass
| 10 | 1 | 18 | 1 | 16 | 0 | 1 | 0.05 | 1 | 1 | 1 | 0 | 9 | 0 | 9 | 81 | 178 | 21 | 150 | 24 | 140 | 7 | 105 | 24 | 95 | 1 | 2 | 0 | 9 |
144,112 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/manually_generated_complex_diagram.py
|
manually_generated_complex_diagram.ManualGenerationComplexTests
|
class ManualGenerationComplexTests(unittest.TestCase):
"""
This class contains test for manual diagram generation functionality.
"""
output_directory = "./output/test-manual/complex/"
output_file_with_di = "manually-generated-complex-output.xml"
output_file_no_di = "manually-generated-complex-output-no-di.xml"
output_dot_file = "manually-generated-example"
output_png_file = "manually-generated-example"
def test_create_diagram_manually(self):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="start_event")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="First task")
[subprocess1_id, _] = bpmn_graph.add_subprocess_to_diagram(process_id, subprocess_name="Subprocess")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, subprocess1_id)
[parallel_gate_fork_id, _] = bpmn_graph.add_parallel_gateway_to_diagram(process_id,
gateway_name="parallel_gate_fork")
[task1_par_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1_par")
[task2_par_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2_par")
[parallel_gate_join_id, _] = bpmn_graph.add_parallel_gateway_to_diagram(process_id,
gateway_name="parallel_gate_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, subprocess1_id, parallel_gate_fork_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_fork_id, task1_par_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_fork_id, task2_par_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_par_id, parallel_gate_join_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_par_id, parallel_gate_join_id)
[exclusive_gate_fork_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_fork")
[task1_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1_ex")
[task2_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2_ex")
[exclusive_gate_join_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, parallel_gate_join_id, exclusive_gate_fork_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task1_ex_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task2_ex_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_ex_id, exclusive_gate_join_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_ex_id, exclusive_gate_join_id)
[inclusive_gate_fork_id, _] = bpmn_graph.add_inclusive_gateway_to_diagram(process_id,
gateway_name="inclusive_gate_fork")
[task1_in_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1_in")
[task2_in_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2_in")
[inclusive_gate_join_id, _] = bpmn_graph.add_inclusive_gateway_to_diagram(process_id,
gateway_name="inclusive_gate_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_join_id, inclusive_gate_fork_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, inclusive_gate_fork_id, task1_in_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, inclusive_gate_fork_id, task2_in_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_in_id, inclusive_gate_join_id)
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_in_id, inclusive_gate_join_id)
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="end_event")
bpmn_graph.add_sequence_flow_to_diagram(process_id, inclusive_gate_join_id, end_id)
layouter.generate_layout(bpmn_graph)
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
# Uncomment line below to get a simple view of created diagram
# visualizer.visualize_diagram(bpmn_graph)
visualizer.bpmn_diagram_to_dot_file(bpmn_graph, self.output_directory + self.output_dot_file)
visualizer.bpmn_diagram_to_png(bpmn_graph, self.output_directory + self.output_png_file)
|
class ManualGenerationComplexTests(unittest.TestCase):
'''
This class contains test for manual diagram generation functionality.
'''
def test_create_diagram_manually(self):
pass
| 2 | 1 | 61 | 10 | 49 | 2 | 1 | 0.09 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 71 | 11 | 55 | 9 | 53 | 5 | 49 | 9 | 47 | 1 | 2 | 0 | 1 |
144,113 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/camunda_complex_test.py
|
camunda_complex_test.CamundaComplexTests
|
class CamundaComplexTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using a complex example of BPMN diagram
created in bpmn-io (Camunda library implementation).
"""
output_directory = "./output/test-camunda/complex/"
example_path = "../examples/xml_import_export/camunda_complex_example.bpmn"
output_file_with_di = "camunda-complex-example-output.xml"
output_file_no_di = "camunda-complex-example-output-no-di.xml"
output_dot_file = "camunda-complex-example"
output_png_file = "camunda-complex-example"
def test_loadCamundaComplexDiagram(self):
"""
Test for importing a complex Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
def test_loadCamundaComplexDiagramAndVisualize(self):
"""
Test for importing a complex Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
# Uncomment line below to get a simple view of created diagram
# visualizer.visualize_diagram(bpmn_graph)
visualizer.bpmn_diagram_to_dot_file(bpmn_graph, self.output_directory + self.output_dot_file)
visualizer.bpmn_diagram_to_png(bpmn_graph, self.output_directory + self.output_png_file)
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
|
class CamundaComplexTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using a complex example of BPMN diagram
created in bpmn-io (Camunda library implementation).
'''
def test_loadCamundaComplexDiagram(self):
'''
Test for importing a complex Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
'''
pass
def test_loadCamundaComplexDiagramAndVisualize(self):
'''
Test for importing a complex Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
'''
pass
| 3 | 3 | 11 | 0 | 6 | 5 | 1 | 0.74 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 74 | 35 | 2 | 19 | 11 | 16 | 14 | 19 | 11 | 16 | 1 | 2 | 0 | 2 |
144,114 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/camunda_simple_test.py
|
camunda_simple_test.CamundaSimpleTests
|
class CamundaSimpleTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using a simple example of BPMN diagram
created in bpmn-io (Camunda library implementation).
"""
output_directory = "./output/test-camunda/simple/"
example_path = "../examples/xml_import_export/camunda_simple_example.bpmn"
output_file_with_di = "camunda-example-output.xml"
output_file_no_di = "camunda-example-output-no-di.xml"
output_dot_file = "camunda-example"
output_png_file = "camunda-example"
def test_loadCamundaSimpleDiagram(self):
"""
Test for importing a simple Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
def test_loadCamundaSimpleDiagramAndVisualize(self):
"""
Test for importing a simple Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
# Uncomment line below to get a simple view of created diagram
# visualizer.visualize_diagram(bpmn_graph)
visualizer.bpmn_diagram_to_dot_file(bpmn_graph, self.output_directory + self.output_dot_file)
visualizer.bpmn_diagram_to_png(bpmn_graph, self.output_directory + self.output_png_file)
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
|
class CamundaSimpleTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using a simple example of BPMN diagram
created in bpmn-io (Camunda library implementation).
'''
def test_loadCamundaSimpleDiagram(self):
'''
Test for importing a simple Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
'''
pass
def test_loadCamundaSimpleDiagramAndVisualize(self):
'''
Test for importing a simple Camunda diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
'''
pass
| 3 | 3 | 11 | 0 | 6 | 5 | 1 | 0.74 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 74 | 35 | 2 | 19 | 11 | 16 | 14 | 19 | 11 | 16 | 1 | 2 | 0 | 2 |
144,115 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/lanes_test.py
|
lanes_test.BPMNEditorTests
|
class BPMNEditorTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using an example BPMN diagram, which contains
multiple pool and lane elements.
"""
output_directory = "./output/test-lane/"
example_path = "../examples/xml_import_export/lanes.bpmn"
output_file_with_di = "lanes-example-output.xml"
output_file_no_di = "lanes-example-output-no-di.xml"
def test_load_lanes_example(self):
"""
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
bpmn_graph.export_xml_file(self.output_directory, self.output_file_with_di)
bpmn_graph.export_xml_file_no_di(self.output_directory, self.output_file_no_di)
|
class BPMNEditorTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using an example BPMN diagram, which contains
multiple pool and lane elements.
'''
def test_load_lanes_example(self):
'''
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file
'''
pass
| 2 | 2 | 9 | 0 | 5 | 4 | 1 | 0.8 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 19 | 1 | 10 | 7 | 8 | 8 | 10 | 7 | 8 | 1 | 2 | 0 | 1 |
144,116 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/xml_import_export/default_conditional_flow_test.py
|
default_conditional_flow_test.DefaultConditionalFlowTests
|
class DefaultConditionalFlowTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using an example BPMN diagram created in BPMNEditor.
"""
output_directory = "./output/test-flows/"
example_path = "../examples/xml_import_export/default-conditional-flow-example.bpmn"
output_file = "default-conditional-flow-example.bpmn"
def test_loadBPMNEditorDiagramAndVisualize(self):
"""
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
"""
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(self.example_path))
bpmn_graph.export_xml_file(self.output_directory, self.output_file)
|
class DefaultConditionalFlowTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using an example BPMN diagram created in BPMNEditor.
'''
def test_loadBPMNEditorDiagramAndVisualize(self):
'''
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and later exporting it to XML file. Includes test for visualization functionality.
'''
pass
| 2 | 2 | 8 | 0 | 4 | 4 | 1 | 0.88 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 16 | 1 | 8 | 6 | 6 | 7 | 8 | 6 | 6 | 1 | 2 | 0 | 1 |
144,117 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/metrics/layout_metrics_test.py
|
layout_metrics_test.MetricsTests
|
class MetricsTests(unittest.TestCase):
crossing_points_example_path = "../examples/metrics/crossing_point_test.bpmn"
cycles_example_path = "../examples/metrics/cycles_test.bpmn"
@staticmethod
def load_example_diagram(filepath):
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.load_diagram_from_xml_file(os.path.abspath(filepath))
return bpmn_graph
def test_count_crossing_points(self):
bpmn_graph = MetricsTests.load_example_diagram(self.crossing_points_example_path)
cross_points = metrics.count_crossing_points(bpmn_graph)
self.assertEqual(cross_points, 6, "Crossing points count does not match")
def test_count_segments(self):
bpmn_graph = MetricsTests.load_example_diagram(self.crossing_points_example_path)
segments_count = metrics.count_segments(bpmn_graph)
self.assertEqual(segments_count, 25, "Segments count does not match")
def test_compute_longest_path(self):
bpmn_graph = MetricsTests.load_example_diagram(self.cycles_example_path)
(longest_path, longest_path_len) = metrics.compute_longest_path(bpmn_graph)
self.assertEqual(longest_path_len, 9, "Path length does not match")
def test_compute_longest_path_tasks(self):
bpmn_graph = MetricsTests.load_example_diagram(self.cycles_example_path)
(longest_path, longest_path_len) = metrics.compute_longest_path_tasks(bpmn_graph)
self.assertEqual(longest_path_len, 6, "Path length does not match")
|
class MetricsTests(unittest.TestCase):
@staticmethod
def load_example_diagram(filepath):
pass
def test_count_crossing_points(self):
pass
def test_count_segments(self):
pass
def test_compute_longest_path(self):
pass
def test_compute_longest_path_tasks(self):
pass
| 7 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 4 | 0 | 5 | 77 | 29 | 5 | 24 | 18 | 17 | 0 | 23 | 17 | 17 | 1 | 2 | 0 | 5 |
144,118 |
KrzyHonk/bpmn-python
|
KrzyHonk_bpmn-python/tests/layouter/layouter_test.py
|
layouter_test.BPMNEditorTests
|
class BPMNEditorTests(unittest.TestCase):
"""
This class contains test for bpmn-python package functionality using an example BPMN diagram created in BPMNEditor.
"""
output_directory = "./output/layouter/"
def test_layouter_manually_created_diagram_simple_case(self):
"""
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and generating layout for it
"""
output_file = "layouter_simple_case.xml"
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="start_event")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id, "start_to_one")
[task2_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2")
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="end_event")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, task2_id, "one_to_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_id, end_id, "two_to_end")
layouter.generate_layout(bpmn_graph)
bpmn_graph.export_xml_file(self.output_directory, output_file)
def test_layouter_manually_created_diagram_split_join_case(self):
"""
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and generating layout for it
"""
output_file = "layouter_split_join_case.xml"
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="start_event")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id, "start_to_one")
[exclusive_gate_fork_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_fork")
[task1_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1_ex")
[task2_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2_ex")
[exclusive_gate_join_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, exclusive_gate_fork_id, "one_to_ex_fork")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task1_ex_id, "ex_fork_to_ex_one")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task2_ex_id, "ex_fork_to_ex_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_ex_id, exclusive_gate_join_id, "ex_one_to_ex_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_ex_id, exclusive_gate_join_id, "ex_two_to_ex_join")
[task2_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2")
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="end_event")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_join_id, task2_id, "ex_join_to_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_id, end_id, "two_to_end")
layouter.generate_layout(bpmn_graph)
bpmn_graph.export_xml_file(self.output_directory, output_file)
def test_layouter_manually_created_diagram_cycle_case(self):
"""
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and generating layout for it
"""
output_file = "layouter_cycle_case.xml"
bpmn_graph = diagram.BpmnDiagramGraph()
bpmn_graph.create_new_diagram_graph(diagram_name="diagram1")
process_id = bpmn_graph.add_process_to_diagram()
[start_id, _] = bpmn_graph.add_start_event_to_diagram(process_id, start_event_name="start_event")
[task1_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1")
bpmn_graph.add_sequence_flow_to_diagram(process_id, start_id, task1_id, "start_to_one")
[exclusive_gate_fork_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_fork")
[task1_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task1_ex")
[task2_ex_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2_ex")
[exclusive_gate_join_id, _] = bpmn_graph.add_exclusive_gateway_to_diagram(process_id,
gateway_name="exclusive_gate_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_id, exclusive_gate_fork_id, "one_to_ex_fork")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_fork_id, task1_ex_id, "ex_fork_to_ex_one")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_ex_id, exclusive_gate_fork_id, "ex_two_to_ex_fork")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task1_ex_id, exclusive_gate_join_id, "ex_one_to_ex_join")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_join_id, task2_ex_id, "ex_join_to_ex_two")
[task2_id, _] = bpmn_graph.add_task_to_diagram(process_id, task_name="task2")
[end_id, _] = bpmn_graph.add_end_event_to_diagram(process_id, end_event_name="end_event")
bpmn_graph.add_sequence_flow_to_diagram(process_id, exclusive_gate_join_id, task2_id, "ex_join_to_two")
bpmn_graph.add_sequence_flow_to_diagram(process_id, task2_id, end_id, "two_to_end")
layouter.generate_layout(bpmn_graph)
bpmn_graph.export_xml_file(self.output_directory, output_file)
|
class BPMNEditorTests(unittest.TestCase):
'''
This class contains test for bpmn-python package functionality using an example BPMN diagram created in BPMNEditor.
'''
def test_layouter_manually_created_diagram_simple_case(self):
'''
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and generating layout for it
'''
pass
def test_layouter_manually_created_diagram_split_join_case(self):
'''
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and generating layout for it
'''
pass
def test_layouter_manually_created_diagram_cycle_case(self):
'''
Test for importing a simple BPMNEditor diagram example (as BPMN 2.0 XML) into inner representation
and generating layout for it
'''
pass
| 4 | 4 | 29 | 3 | 21 | 4 | 1 | 0.23 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 75 | 94 | 13 | 66 | 14 | 62 | 15 | 62 | 14 | 58 | 1 | 2 | 0 | 3 |
144,119 |
KujiraProject/Flask-PAM
|
KujiraProject_Flask-PAM/example/flask_pam/token/jwt.py
|
flask_pam.token.jwt.JWT
|
class JWT(Token):
"""JSON Web Token"""
def __init__(self, *args, **kwargs):
super(JWT, self).__init__(*args, **kwargs)
self.algorithm = 'HS256'
log.info("JWT (algorithm: %s) initialized!", self.algorithm)
def generate(self):
data = self.context.copy()
data['username'] = self.username
data['exp'] = int(self.expire.strftime('%s'))
log.info("Generating JWT for user '%s'", self.username)
return jwt.encode(data,
self.secret_key,
algorithm=self.algorithm)
def validate(self, token, **validation_context):
context = jwt.decode(token,
self.secret_key,
algorithms=[self.algorithm])
if 'ip' in validation_context and \
not context['ip'] == validation_context['ip']:
log.warning("Token is invalid!")
return False
return True
|
class JWT(Token):
'''JSON Web Token'''
def __init__(self, *args, **kwargs):
pass
def generate(self):
pass
def validate(self, token, **validation_context):
pass
| 4 | 1 | 8 | 1 | 7 | 0 | 1 | 0.05 | 1 | 2 | 0 | 0 | 3 | 2 | 3 | 7 | 30 | 7 | 22 | 8 | 18 | 1 | 17 | 7 | 13 | 2 | 2 | 1 | 4 |
144,120 |
KujiraProject/Flask-PAM
|
KujiraProject_Flask-PAM/example/flask_pam/token/jwt.py
|
flask_pam.token.jwt.JWT
|
class JWT(Token):
"""JSON Web Token"""
def __init__(self, *args, **kwargs):
super(JWT, self).__init__(*args, **kwargs)
self.algorithm = 'HS256'
log.info("JWT (algorithm: %s) initialized!", self.algorithm)
def generate(self):
data = self.context.copy()
data['username'] = self.username
data['exp'] = int(self.expire.strftime('%s'))
log.info("Generating JWT for user '%s'", self.username)
return jwt.encode(data,
self.secret_key,
algorithm=self.algorithm)
def validate(self, token, **validation_context):
context = jwt.decode(token,
self.secret_key,
algorithms=[self.algorithm])
if 'ip' in validation_context and \
not context['ip'] == validation_context['ip']:
log.warning("Token is invalid!")
return False
return True
|
class JWT(Token):
'''JSON Web Token'''
def __init__(self, *args, **kwargs):
pass
def generate(self):
pass
def validate(self, token, **validation_context):
pass
| 4 | 1 | 8 | 1 | 7 | 0 | 1 | 0.05 | 1 | 2 | 0 | 0 | 3 | 2 | 3 | 7 | 30 | 7 | 22 | 8 | 18 | 1 | 17 | 7 | 13 | 2 | 2 | 1 | 4 |
144,121 |
KujiraProject/Flask-PAM
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KujiraProject_Flask-PAM/example/flask_pam/auth.py
|
flask_pam.auth.Auth
|
class Auth(object):
"""Plugin for Flask which implements PAM authentication with tokens."""
def __init__(self,
token_storage_type, token_type,
token_lifetime, refresh_token_lifetime,
app, development=False):
"""Initialization of Auth object
:param token_storage_type: type which derives from
token_storage.TokenStorage
:param token_type: type which derives from token.Token
:param token_lifetime: time interval in which token will be valid (in seconds)
:param refresh_token_lifetime: time interval in which refresh token will be valid (in seconds)
:param app: Flask class' instance
:param development: flag - turning it on will always result in correct authentication
in decorators: auth_required and group_required
"""
self.token_type = token_type
self.token_storage = token_storage_type()
self.refresh_token_storage = token_storage_type()
self.token_lifetime = token_lifetime
self.refresh_token_lifetime = refresh_token_lifetime
self.init_app(app)
self.development = development
log.info("Auth object initialized. Token: %s, Storage: %s, token lifetime %d, refresh token lifetime %d, development: %r",
self.token_type.__name__,
token_storage_type.__name__,
self.token_lifetime,
self.refresh_token_lifetime,
self.development,)
def init_app(self, app):
"""Saves Flask class' instance in self.app
:param app: Flask class' instance
"""
self.app = app
log.info("Flask application has been initialized in Flask-PAM!")
def authenticate(self, username, password, **token_context):
"""Performs authentication using simplepam
This function calls simplepam's authenticate function and returns
status of authentication using PAM and token object (of type
self.token_type)
:param username: username in Linux
:param password: password for username
:param **token_context: additional args with keys for token generator
"""
log.info("Trying to authenticate user: '%s'", username)
if simplepam.authenticate(username, password):
expire = datetime.now() + timedelta(seconds=self.token_lifetime)
log.info("Token will be valid to %s", expire.strftime('%c'))
refresh_expire = -1
if self.refresh_token_lifetime != -1:
refresh_expire = datetime.now() + timedelta(seconds=self.refresh_token_lifetime)
log.info("Refresh token will be valid to %s",
refresh_expire.strftime('%c'))
token = self.token_type(
self.app.secret_key, username, expire, **token_context)
token.context['salt'] = urandom(120).encode('base-64')
refresh_context = token_context.copy()
refresh_context['refresh_salt'] = urandom(120).encode('base-64')
refresh_token = self.token_type(
self.app.secret_key, username, refresh_expire, **refresh_context)
self.token_storage.set(token)
self.refresh_token_storage.set(refresh_token)
return (True, token, refresh_token)
log.warning("Couldn't authenticate user: %s", username)
return (False, None, None)
def refresh(self, token):
"""Refresh token"""
log.info("Trying to refresh token...")
refresh = self.refresh_token_storage.get(token)
if refresh:
expire = datetime.now() + timedelta(seconds=self.token_lifetime)
refresh.context['refresh_salt'] = urandom(120).encode('base-64')
new_token = self.token_type(
self.app.secret_key, refresh.username, expire, **refresh.context)
self.token_storage.set(new_token)
log.info("Token for user %s has been refreshed!", refresh.username)
return (True, new_token)
log.warning("Could not refresh token!")
return (False, None)
def authenticated(self, user_token, **validation_context):
"""Checks if user is authenticated using token passed in argument
:param user_token: string representing token
:param validation_context: Token.validate optional keyword arguments
"""
token = self.token_storage.get(user_token)
if token and token.validate(user_token, **validation_context):
return True
return False
def group_authenticated(self, user_token, group):
"""Checks if user represented by token is in group.
:param user_token: string representing token
:param group: group's name
"""
if self.authenticated(user_token):
token = self.token_storage.get(user_token)
groups = self.get_groups(token.username)
if group in groups:
return True
return False
def get_groups(self, username):
"""Returns list of groups in which user is.
:param username: name of Linux user
"""
groups = []
for group in grp.getgrall():
if username in group.gr_mem:
groups.append(group.gr_name)
return groups
# decorators
def auth_required(self, view):
"""Decorator which checks if user is authenticated
Decorator for Flask's view which blocks not authenticated requests
:param view: Flask's view function
"""
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info(
"Trying to get access to protected resource: '%s'", view.__name__)
if request.method == 'POST':
token = request.form['token']
if self.development or self.authenticated(token):
return view(*args, **kwargs)
else:
log.warning(
"User has not been authorized to get access to resource: %s", view.__name__)
else:
log.warning(
"Bad request type! Expected 'POST', actual '%s'", request.method)
return abort(403)
return decorated
def group_required(self, group):
"""Decorator which checks if user is in group
Decorator for Flask's view which blocks requests from not
authenticated users or if user is not member of specified group
:param group: group's name
"""
def decorator(view):
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info(
"Trying to get access to resource: %s protected by group: %s", view.__name__, group)
if request.method == 'POST':
token = request.form['token']
if self.development or self.group_authenticated(token, group):
return view(*args, **kwargs)
else:
log.warning(
"User has not been authorized to get access to resource: %s", view.__name__)
else:
log.error(
"Bad request type! Expected 'POST', actual '%s'", request.method)
return abort(403)
return decorated
return decorator
|
class Auth(object):
'''Plugin for Flask which implements PAM authentication with tokens.'''
def __init__(self,
token_storage_type, token_type,
token_lifetime, refresh_token_lifetime,
app, development=False):
'''Initialization of Auth object
:param token_storage_type: type which derives from
token_storage.TokenStorage
:param token_type: type which derives from token.Token
:param token_lifetime: time interval in which token will be valid (in seconds)
:param refresh_token_lifetime: time interval in which refresh token will be valid (in seconds)
:param app: Flask class' instance
:param development: flag - turning it on will always result in correct authentication
in decorators: auth_required and group_required
'''
pass
def init_app(self, app):
'''Saves Flask class' instance in self.app
:param app: Flask class' instance
'''
pass
def authenticate(self, username, password, **token_context):
'''Performs authentication using simplepam
This function calls simplepam's authenticate function and returns
status of authentication using PAM and token object (of type
self.token_type)
:param username: username in Linux
:param password: password for username
:param **token_context: additional args with keys for token generator
'''
pass
def refresh(self, token):
'''Refresh token'''
pass
def authenticated(self, user_token, **validation_context):
'''Checks if user is authenticated using token passed in argument
:param user_token: string representing token
:param validation_context: Token.validate optional keyword arguments
'''
pass
def group_authenticated(self, user_token, group):
'''Checks if user represented by token is in group.
:param user_token: string representing token
:param group: group's name
'''
pass
def get_groups(self, username):
'''Returns list of groups in which user is.
:param username: name of Linux user
'''
pass
def auth_required(self, view):
'''Decorator which checks if user is authenticated
Decorator for Flask's view which blocks not authenticated requests
:param view: Flask's view function
'''
pass
@functools.wraps(view)
def decorated(*args, **kwargs):
pass
def group_required(self, group):
'''Decorator which checks if user is in group
Decorator for Flask's view which blocks requests from not
authenticated users or if user is not member of specified group
:param group: group's name
'''
pass
def decorator(view):
pass
@functools.wraps(view)
def decorated(*args, **kwargs):
pass
| 15 | 10 | 18 | 4 | 11 | 4 | 2 | 0.44 | 1 | 2 | 0 | 0 | 9 | 7 | 9 | 9 | 192 | 48 | 100 | 40 | 82 | 44 | 86 | 35 | 73 | 3 | 1 | 2 | 24 |
144,122 |
KujiraProject/Flask-PAM
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KujiraProject_Flask-PAM/example/flask_pam/auth.py
|
flask_pam.auth.Auth
|
class Auth(object):
"""Plugin for Flask which implements PAM authentication with tokens."""
def __init__(self,
token_storage_type, token_type,
token_lifetime, refresh_token_lifetime,
app, development=False):
"""Initialization of Auth object
:param token_storage_type: type which derives from
token_storage.TokenStorage
:param token_type: type which derives from token.Token
:param token_lifetime: time interval in which token will be valid (in seconds)
:param refresh_token_lifetime: time interval in which refresh token will be valid (in seconds)
:param app: Flask class' instance
:param development: flag - turning it on will always result in correct authentication
in decorators: auth_required and group_required
"""
self.token_type = token_type
self.token_storage = token_storage_type()
self.refresh_token_storage = token_storage_type()
self.token_lifetime = token_lifetime
self.refresh_token_lifetime = refresh_token_lifetime
self.init_app(app)
self.development = development
log.info("Auth object initialized. Token: %s, Storage: %s, token lifetime %d, refresh token lifetime %d, development: %r",
self.token_type.__name__,
token_storage_type.__name__,
self.token_lifetime,
self.refresh_token_lifetime,
self.development,)
def init_app(self, app):
"""Saves Flask class' instance in self.app
:param app: Flask class' instance
"""
self.app = app
log.info("Flask application has been initialized in Flask-PAM!")
def authenticate(self, username, password, **token_context):
"""Performs authentication using simplepam
This function calls simplepam's authenticate function and returns
status of authentication using PAM and token object (of type
self.token_type)
:param username: username in Linux
:param password: password for username
:param **token_context: additional args with keys for token generator
"""
log.info("Trying to authenticate user: '%s'", username)
if simplepam.authenticate(username, password):
expire = datetime.now() + timedelta(seconds=self.token_lifetime)
log.info("Token will be valid to %s", expire.strftime('%c'))
refresh_expire = -1
if self.refresh_token_lifetime != -1:
refresh_expire = datetime.now() + timedelta(seconds=self.refresh_token_lifetime)
log.info("Refresh token will be valid to %s",
refresh_expire.strftime('%c'))
token = self.token_type(
self.app.secret_key, username, expire, **token_context)
token.context['salt'] = urandom(120).encode('base-64')
refresh_context = token_context.copy()
refresh_context['refresh_salt'] = urandom(120).encode('base-64')
refresh_token = self.token_type(
self.app.secret_key, username, refresh_expire, **refresh_context)
self.token_storage.set(token)
self.refresh_token_storage.set(refresh_token)
return (True, token, refresh_token)
log.warning("Couldn't authenticate user: %s", username)
return (False, None, None)
def refresh(self, token):
"""Refresh token"""
log.info("Trying to refresh token...")
refresh = self.refresh_token_storage.get(token)
if refresh:
expire = datetime.now() + timedelta(seconds=self.token_lifetime)
refresh.context['refresh_salt'] = urandom(120).encode('base-64')
new_token = self.token_type(
self.app.secret_key, refresh.username, expire, **refresh.context)
self.token_storage.set(new_token)
log.info("Token for user %s has been refreshed!", refresh.username)
return (True, new_token)
log.warning("Could not refresh token!")
return (False, None)
def authenticated(self, user_token, **validation_context):
"""Checks if user is authenticated using token passed in argument
:param user_token: string representing token
:param validation_context: Token.validate optional keyword arguments
"""
token = self.token_storage.get(user_token)
if token and token.validate(user_token, **validation_context):
return True
return False
def group_authenticated(self, user_token, group):
"""Checks if user represented by token is in group.
:param user_token: string representing token
:param group: group's name
"""
if self.authenticated(user_token):
token = self.token_storage.get(user_token)
groups = self.get_groups(token.username)
if group in groups:
return True
return False
def get_groups(self, username):
"""Returns list of groups in which user is.
:param username: name of Linux user
"""
groups = []
for group in grp.getgrall():
if username in group.gr_mem:
groups.append(group.gr_name)
return groups
# decorators
def auth_required(self, view):
"""Decorator which checks if user is authenticated
Decorator for Flask's view which blocks not authenticated requests
:param view: Flask's view function
"""
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info(
"Trying to get access to protected resource: '%s'", view.__name__)
if request.method == 'POST':
token = request.form['token']
if self.development or self.authenticated(token):
return view(*args, **kwargs)
else:
log.warning(
"User has not been authorized to get access to resource: %s", view.__name__)
else:
log.warning(
"Bad request type! Expected 'POST', actual '%s'", request.method)
return abort(403)
return decorated
def group_required(self, group):
"""Decorator which checks if user is in group
Decorator for Flask's view which blocks requests from not
authenticated users or if user is not member of specified group
:param group: group's name
"""
def decorator(view):
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info(
"Trying to get access to resource: %s protected by group: %s", view.__name__, group)
if request.method == 'POST':
token = request.form['token']
if self.development or self.group_authenticated(token, group):
return view(*args, **kwargs)
else:
log.warning(
"User has not been authorized to get access to resource: %s", view.__name__)
else:
log.error(
"Bad request type! Expected 'POST', actual '%s'", request.method)
return abort(403)
return decorated
return decorator
|
class Auth(object):
'''Plugin for Flask which implements PAM authentication with tokens.'''
def __init__(self,
token_storage_type, token_type,
token_lifetime, refresh_token_lifetime,
app, development=False):
'''Initialization of Auth object
:param token_storage_type: type which derives from
token_storage.TokenStorage
:param token_type: type which derives from token.Token
:param token_lifetime: time interval in which token will be valid (in seconds)
:param refresh_token_lifetime: time interval in which refresh token will be valid (in seconds)
:param app: Flask class' instance
:param development: flag - turning it on will always result in correct authentication
in decorators: auth_required and group_required
'''
pass
def init_app(self, app):
'''Saves Flask class' instance in self.app
:param app: Flask class' instance
'''
pass
def authenticate(self, username, password, **token_context):
'''Performs authentication using simplepam
This function calls simplepam's authenticate function and returns
status of authentication using PAM and token object (of type
self.token_type)
:param username: username in Linux
:param password: password for username
:param **token_context: additional args with keys for token generator
'''
pass
def refresh(self, token):
'''Refresh token'''
pass
def authenticated(self, user_token, **validation_context):
'''Checks if user is authenticated using token passed in argument
:param user_token: string representing token
:param validation_context: Token.validate optional keyword arguments
'''
pass
def group_authenticated(self, user_token, group):
'''Checks if user represented by token is in group.
:param user_token: string representing token
:param group: group's name
'''
pass
def get_groups(self, username):
'''Returns list of groups in which user is.
:param username: name of Linux user
'''
pass
def auth_required(self, view):
'''Decorator which checks if user is authenticated
Decorator for Flask's view which blocks not authenticated requests
:param view: Flask's view function
'''
pass
@functools.wraps(view)
def decorated(*args, **kwargs):
pass
def group_required(self, group):
'''Decorator which checks if user is in group
Decorator for Flask's view which blocks requests from not
authenticated users or if user is not member of specified group
:param group: group's name
'''
pass
def decorator(view):
pass
@functools.wraps(view)
def decorated(*args, **kwargs):
pass
| 15 | 10 | 18 | 4 | 11 | 4 | 2 | 0.44 | 1 | 2 | 0 | 0 | 9 | 7 | 9 | 9 | 192 | 48 | 100 | 40 | 82 | 44 | 86 | 35 | 73 | 3 | 1 | 2 | 24 |
144,123 |
KujiraProject/Flask-PAM
|
KujiraProject_Flask-PAM/flask_pam/token_storage/dict_storage.py
|
flask_pam.token_storage.dict_storage.DictStorage
|
class DictStorage(TokenStorage):
"""Tokens' storage which uses Python's dictionaries"""
def __init__(self):
self.tokens = {}
self.users = {}
def get(self, token):
if token in self.tokens:
t = self.tokens[token]
if t.expire >= datetime.now():
return t
else:
log.info("Token has expired on %s", t.expire.strftime('%s'))
return None
def set(self, token):
self.tokens[token.generate()] = token
self.users[token.username] = token
log.info("Setting token for user '%s'", token.username)
def getByUser(self, username):
if username in self.users:
t = self.users[username]
if t.expire >= datetime.now():
return t
else:
log.info("Token for user '%s' has expired on %s",
username, t.expire.strftime('%s'))
return None
|
class DictStorage(TokenStorage):
'''Tokens' storage which uses Python's dictionaries'''
def __init__(self):
pass
def get(self, token):
pass
def set(self, token):
pass
def getByUser(self, username):
pass
| 5 | 1 | 7 | 1 | 6 | 0 | 2 | 0.04 | 1 | 1 | 0 | 0 | 4 | 2 | 4 | 7 | 33 | 7 | 25 | 9 | 20 | 1 | 22 | 9 | 17 | 3 | 2 | 2 | 8 |
144,124 |
KujiraProject/Flask-PAM
|
KujiraProject_Flask-PAM/flask_pam/token_storage/dict_storage.py
|
flask_pam.token_storage.dict_storage.DictStorage
|
class DictStorage(TokenStorage):
"""Tokens' storage which uses Python's dictionaries"""
def __init__(self):
self.tokens = {}
self.users = {}
def get(self, token):
if token in self.tokens:
t = self.tokens[token]
if t.expire >= datetime.now():
return t
else:
log.info("Token has expired on %s", t.expire.strftime('%s'))
return None
def set(self, token):
self.tokens[token.generate()] = token
self.users[token.username] = token
log.info("Setting token for user '%s'", token.username)
def getByUser(self, username):
if username in self.users:
t = self.users[username]
if t.expire >= datetime.now():
return t
else:
log.info("Token for user '%s' has expired on %s",
username, t.expire.strftime('%s'))
return None
|
class DictStorage(TokenStorage):
'''Tokens' storage which uses Python's dictionaries'''
def __init__(self):
pass
def get(self, token):
pass
def set(self, token):
pass
def getByUser(self, username):
pass
| 5 | 1 | 7 | 1 | 6 | 0 | 2 | 0.04 | 1 | 1 | 0 | 0 | 4 | 2 | 4 | 7 | 33 | 7 | 25 | 9 | 20 | 1 | 22 | 9 | 17 | 3 | 2 | 2 | 8 |
144,125 |
KujiraProject/Flask-PAM
|
KujiraProject_Flask-PAM/example/flask_pam/token/simple.py
|
flask_pam.token.simple.Simple
|
class Simple(Token):
"""Simple token implementation. Only for testing purposes."""
def generate(self):
log.info("Generating Simple token for user '%s'", self.username)
return sha256(self.username + str(self.context)).hexdigest()
|
class Simple(Token):
'''Simple token implementation. Only for testing purposes.'''
def generate(self):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.25 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 5 | 7 | 2 | 4 | 2 | 2 | 1 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
144,126 |
KujiraProject/Flask-PAM
|
KujiraProject_Flask-PAM/example/flask_pam/token/simple.py
|
flask_pam.token.simple.Simple
|
class Simple(Token):
"""Simple token implementation. Only for testing purposes."""
def generate(self):
log.info("Generating Simple token for user '%s'", self.username)
return sha256(self.username + str(self.context)).hexdigest()
|
class Simple(Token):
'''Simple token implementation. Only for testing purposes.'''
def generate(self):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.25 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 5 | 7 | 2 | 4 | 2 | 2 | 1 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
144,127 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/level.py
|
vint.linting.level.Level
|
class Level(enum.Enum):
ERROR = 0
WARNING = 1
STYLE_PROBLEM = 2
|
class Level(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
144,128 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/lint_target.py
|
vint.linting.lint_target.CachedLintTarget
|
class CachedLintTarget(AbstractLintTarget):
def __init__(self, lint_target):
# type: (AbstractLintTarget) -> None
super(CachedLintTarget, self).__init__(lint_target.path)
self._target = lint_target
self._cached_bytes = None # type: Optional[bytes]
def read(self): # type: () -> bytes
if self._cached_bytes is not None:
return self._cached_bytes
result = self._target.read()
self._cached_bytes = result
return result
|
class CachedLintTarget(AbstractLintTarget):
def __init__(self, lint_target):
pass
def read(self):
pass
| 3 | 0 | 6 | 1 | 5 | 2 | 2 | 0.27 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 4 | 15 | 3 | 11 | 6 | 8 | 3 | 11 | 6 | 8 | 2 | 2 | 1 | 3 |
144,129 |
Kuniwak/vint
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/test/integration/vint/linting/test_linter.py
|
test.integration.vint.linting.test_linter.TestLinterIntegral.StubPolicy2
|
class StubPolicy2(AbstractPolicy):
reference = 'ref2'
description = 'desc2'
level = Level.WARNING
def listen_node_types(self):
return [NodeType.COMMENT]
def is_valid(self, node, lint_context):
return 'STUB_POLICY_2_INVALID' not in node['str']
|
class StubPolicy2(AbstractPolicy):
def listen_node_types(self):
pass
def is_valid(self, node, lint_context):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 9 | 12 | 4 | 8 | 6 | 5 | 0 | 8 | 6 | 5 | 1 | 2 | 0 | 2 |
144,130 |
Kuniwak/vint
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/test/integration/vint/linting/test_linter.py
|
test.integration.vint.linting.test_linter.TestLinterIntegral.StubPolicySet
|
class StubPolicySet(object):
def __init__(self):
self._enabled_policies = []
def get_enabled_policies(self):
return self._enabled_policies
def update_by_config(self, config_dict):
self._enabled_policies = []
policy_enabling_map = config_dict['policies']
if policy_enabling_map['StubPolicy1']['enabled']:
self._enabled_policies.append(TestLinterIntegral.StubPolicy1())
if policy_enabling_map['StubPolicy2']['enabled']:
self._enabled_policies.append(TestLinterIntegral.StubPolicy2())
|
class StubPolicySet(object):
def __init__(self):
pass
def get_enabled_policies(self):
pass
def update_by_config(self, config_dict):
pass
| 4 | 0 | 5 | 1 | 4 | 0 | 2 | 0 | 1 | 3 | 3 | 0 | 3 | 1 | 3 | 3 | 19 | 7 | 12 | 6 | 8 | 0 | 12 | 6 | 8 | 3 | 1 | 1 | 5 |
144,131 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/policy/abstract_policy.py
|
vint.linting.policy.abstract_policy.AbstractPolicy
|
class AbstractPolicy(object):
description = None
reference = None
level = None
def __init__(self):
self.name = self.__class__.__name__
def listen_node_types(self):
""" Listening node type.
is_valid will be called when a linter visit the listening node type.
"""
return []
def is_valid(self, node, lint_context):
""" Whether the specified node is valid for the policy. """
return True
def create_violation_report(self, node, lint_context):
""" Returns a violation report for the node. """
return {
'name': self.name,
'level': self.level,
'description': self.description,
'reference': self.reference,
'position': {
'line': node['pos']['lnum'],
'column': node['pos']['col'],
'path': lint_context['lint_target'].path,
},
}
def get_policy_config(self, lint_context):
"""
Returns a config of the concrete policy. For example, a config of ProhibitSomethingEvil is located on
config.policies.ProhibitSomethingEvil.
"""
policy_config = lint_context['config']\
.get('policies', {})\
.get(self.__class__.__name__, {})
return policy_config
def get_violation_if_found(self, node, lint_context):
""" Returns a violation if the node is invalid. """
if self.is_valid(node, lint_context):
return None
return self.create_violation_report(node, lint_context)
def get_policy_options(self, lint_context):
policy_section = lint_context['config'].get('policies', {})
return policy_section.get(self.name, {})
|
class AbstractPolicy(object):
def __init__(self):
pass
def listen_node_types(self):
''' Listening node type.
is_valid will be called when a linter visit the listening node type.
'''
pass
def is_valid(self, node, lint_context):
''' Whether the specified node is valid for the policy. '''
pass
def create_violation_report(self, node, lint_context):
''' Returns a violation report for the node. '''
pass
def get_policy_config(self, lint_context):
'''
Returns a config of the concrete policy. For example, a config of ProhibitSomethingEvil is located on
config.policies.ProhibitSomethingEvil.
'''
pass
def get_violation_if_found(self, node, lint_context):
''' Returns a violation if the node is invalid. '''
pass
def get_policy_options(self, lint_context):
pass
| 8 | 5 | 6 | 0 | 4 | 1 | 1 | 0.29 | 1 | 0 | 0 | 19 | 7 | 1 | 7 | 7 | 59 | 15 | 34 | 14 | 26 | 10 | 22 | 14 | 14 | 2 | 1 | 1 | 8 |
144,132 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/policy/prohibit_command_rely_on_user.py
|
vint.linting.policy.prohibit_command_rely_on_user.ProhibitCommandRelyOnUser
|
class ProhibitCommandRelyOnUser(AbstractPolicy):
description = 'Avoid commands that rely on user settings'
reference = get_reference_source('FRAGILE')
level = Level.WARNING
def listen_node_types(self):
return [NodeType.EXCMD]
def is_valid(self, node, lint_context):
""" Whether the specified node is valid.
This policy prohibit following commands:
- normal without !
- substitute
"""
ea = node['ea']
command = ea['cmd'].get('name', None)
# It seems line jump command
if command is None:
return True
is_prohibited_command = command in ProhibitedCommands
if is_prohibited_command:
return False
should_be_with_bang = command in CommandsShouldBeWithBang
if not should_be_with_bang:
return True
is_bang = ea.get('forceit', 0) == 1
return is_bang
|
class ProhibitCommandRelyOnUser(AbstractPolicy):
def listen_node_types(self):
pass
def is_valid(self, node, lint_context):
''' Whether the specified node is valid.
This policy prohibit following commands:
- normal without !
- substitute
'''
pass
| 3 | 1 | 14 | 3 | 8 | 3 | 3 | 0.32 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 9 | 35 | 10 | 19 | 11 | 16 | 6 | 19 | 11 | 16 | 4 | 2 | 1 | 5 |
144,133 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/policy/prohibit_autocmd_with_no_group.py
|
vint.linting.policy.prohibit_autocmd_with_no_group.ProhibitAutocmdWithNoGroup
|
class ProhibitAutocmdWithNoGroup(AbstractPolicy):
description = 'autocmd should execute in an augroup or execute with a group'
reference = ':help :autocmd'
level = Level.WARNING
is_inside_of_augroup = False
def listen_node_types(self):
return [NodeType.EXCMD]
def is_valid(self, node, lint_context):
""" Whether the specified node is valid.
autocmd family should be called with any groups.
"""
# noed.ea.cmd is empty when line jump command such as 1
cmd_name = node['ea']['cmd'].get('name', None)
is_autocmd = cmd_name == 'autocmd'
if is_autocmd and not self.is_inside_of_augroup:
matched = re.match(r'au(?:tocmd)?!?\s+(\S+)', node['str'])
if not matched:
# Looks like autocmd with a bang
return True
has_group = any(x and x.upper() not in AutoCmdEvents for x in matched.group(1).split(','))
return has_group
is_augroup = cmd_name == 'augroup'
if is_augroup:
matched = re.match(r'aug(?:roup)?\s+[eE][nN][dD]$', node['str'])
is_augroup_end = bool(matched)
self.is_inside_of_augroup = not is_augroup_end
return True
|
class ProhibitAutocmdWithNoGroup(AbstractPolicy):
def listen_node_types(self):
pass
def is_valid(self, node, lint_context):
''' Whether the specified node is valid.
autocmd family should be called with any groups.
'''
pass
| 3 | 1 | 15 | 4 | 9 | 3 | 3 | 0.23 | 1 | 2 | 1 | 0 | 2 | 0 | 2 | 9 | 39 | 12 | 22 | 13 | 19 | 5 | 22 | 13 | 19 | 4 | 2 | 2 | 5 |
144,134 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/policy/prohibit_abbreviation_option.py
|
vint.linting.policy.prohibit_abbreviation_option.ProhibitAbbreviationOption
|
class ProhibitAbbreviationOption(AbstractPolicy):
description = 'Use the full option name instead of the abbreviation'
reference = ':help option-summary'
level = Level.STYLE_PROBLEM
was_scriptencoding_found = False
has_encoding_opt_after_scriptencoding = False
def listen_node_types(self):
return [NodeType.EXCMD, NodeType.OPTION]
def is_valid(self, node, lint_context):
""" Whether the specified node is valid.
Abbreviation options are invalid.
"""
node_type = NodeType(node['type'])
if node_type is NodeType.OPTION:
# Remove & at head
option_name = node['value'][1:]
is_valid = option_name not in Abbreviations
if not is_valid:
self._make_description_by_option_name(option_name)
return is_valid
excmd_node = node
is_set_cmd = excmd_node['ea']['cmd'].get('name') in SetCommandFamily
if not is_set_cmd:
return True
option_expr = excmd_node['str'].split()[1]
# Care `:set ft=vim` and `:set cpo&vim`, ...
option_name = re.match(r'[a-z]+', option_expr).group(0)
# After a "set" command, we can add an invert prefix "no" and "inv"
# to options. For example, "nowrap" is an inverted option "wrap".
is_valid = option_name not in AbbreviationsIncludingInvertPrefix
if not is_valid:
self._make_description_by_option_name(option_name)
return is_valid
def _make_description_by_option_name(self, option_name):
param = {
'good_pattern': AbbreviationsIncludingInvertPrefix[option_name],
'bad_pattern': option_name,
}
self.description = ('Use the full option name `{good_pattern}` '
'instead of `{bad_pattern}`'.format(**param))
|
class ProhibitAbbreviationOption(AbstractPolicy):
def listen_node_types(self):
pass
def is_valid(self, node, lint_context):
''' Whether the specified node is valid.
Abbreviation options are invalid.
'''
pass
def _make_description_by_option_name(self, option_name):
pass
| 4 | 1 | 15 | 4 | 9 | 2 | 2 | 0.21 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 10 | 59 | 19 | 33 | 16 | 29 | 7 | 29 | 16 | 25 | 5 | 2 | 2 | 7 |
144,135 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/lint_target.py
|
vint.linting.lint_target.LintTargetFile
|
class LintTargetFile(AbstractLintTarget):
def __init__(self, path):
# type: (Path) -> None
super(LintTargetFile, self).__init__(path)
def read(self): # type: () -> bytes
with self.path.open('rb') as f:
return f.read()
|
class LintTargetFile(AbstractLintTarget):
def __init__(self, path):
pass
def read(self):
pass
| 3 | 0 | 3 | 0 | 3 | 1 | 1 | 0.33 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 4 | 9 | 2 | 6 | 4 | 3 | 2 | 6 | 3 | 3 | 1 | 2 | 1 | 2 |
144,136 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/linter.py
|
vint.linting.linter.Linter
|
class Linter(object):
""" A class for Linters.
This class provides a linting algorithm that know how to lint by Policy
class, and how to manage enabled policies by using Config classes.
The class manage what policies are enabled by using the Config class.
The config should be refreshed when a config comment is found.
Then the Linter class notify refresh request to the Config class in
traversing.
The Linter class lint by event-driven traversing.
Enabled policies request to call their when the nodes necesary to validate
are found in traversing. The Linter class collect violations that are
returned by policies.
"""
def __init__(self, policy_set, config_dict_global):
# type: (PolicySet, Dict[str, Any]) -> None
self._is_debug = get_config_value(config_dict_global, ['cmdargs', 'verbose'], False)
self._plugins = {
'scope': ScopePlugin(),
}
self._policy_set = policy_set
self._config_dict_global = config_dict_global
self._parser = self.build_parser()
self._listeners_map = {}
def build_parser(self):
enable_neovim = get_config_value(self._config_dict_global, ['cmdargs', 'env', 'neovim'], False)
parser = Parser([self._plugins['scope']], enable_neovim=enable_neovim)
return parser
def _parse_vimlparser_error(self, err_message):
match = re.match(r'vimlparser: (?P<description>.*): line (?P<line_number>\d+) col (?P<column_number>\d+)$', err_message)
return match.groupdict()
def _create_parse_error(self, path, err_message):
parser_error = self._parse_vimlparser_error(err_message)
return {
'name': 'SyntaxError',
'level': Level.ERROR,
'description': parser_error['description'],
'reference': 'vim-jp/vim-vimlparser',
'position': {
'line': int(parser_error['line_number']),
'column': int(parser_error['column_number']),
'path': Path(path),
},
}
def _create_decoding_error(self, path, err_message):
return {
'name': 'DecodingError',
'level': Level.ERROR,
'description': err_message,
'reference': 'no reference',
'position': {
'line': 0,
'column': 0,
'path': Path(path),
},
}
def lint(self, lint_target): # type: (AbstractLintTarget) -> List[Dict[str, Any]]
logging.debug('checking: `{file_path}`'.format(file_path=lint_target.path))
try:
root_ast = self._parser.parse(lint_target)
except vimlparser.VimLParserException as exception:
parse_error = self._create_parse_error(lint_target.path, str(exception))
return [parse_error]
except EncodingDetectionError as exception:
decoding_error = self._create_decoding_error(lint_target, str(exception))
return [decoding_error]
self._traverse(root_ast, lint_target)
return self._violations
def _traverse(self, root_ast, lint_target):
if self._is_debug:
logging.debug('{cls}: checking `{file_path}`'.format(
cls=self.__class__.__name__,
file_path=lint_target.path)
)
logging.debug('{cls}: using config as {config_dict}'.format(
cls=self.__class__.__name__,
config_dict=self._config_dict_global
))
self._prepare_for_traversal()
lint_context = {
'lint_target': lint_target,
'root_node': root_ast,
'stack_trace': [],
'plugins': self._plugins,
'config': self._config.get_config_dict(),
}
traverse(root_ast,
on_enter=lambda node: self._handle_enter(node, lint_context),
on_leave=lambda node: self._handle_leave(node, lint_context))
def _prepare_for_traversal(self):
self._dynamic_configs = [
ConfigToggleCommentSource(),
ConfigNextLineCommentSource(is_debug=self._is_debug),
] # type: List[ConfigAbstractDynamicSource]
config_dict_source = ConfigDictSource(self._config_dict_global.copy())
self._config = ConfigContainer(config_dict_source, *self._dynamic_configs)
self._violations = [] # type: List[Dict[str, Any]]
self._update_listeners_map()
def _handle_enter(self, node, lint_context):
self._refresh_policies_if_necessary(node)
if self._is_debug:
logging.debug("{cls}: checking {pos}".format(
cls=self.__class__.__name__,
pos=node['pos']
))
self._fire_listeners(node, lint_context)
lint_context['stack_trace'].append(node)
def _handle_leave(self, node, lint_context):
lint_context['stack_trace'].pop()
def _fire_listeners(self, node, lint_context):
node_type = NodeType(node['type'])
if node_type not in self._listeners_map:
return
listening_policies = self._listeners_map[node_type]
for listening_policy in listening_policies:
violation = listening_policy.get_violation_if_found(node, lint_context)
if violation is not None:
self._violations.append(violation)
def _refresh_policies_if_necessary(self, node):
for dynamic_config in self._dynamic_configs:
dynamic_config.update_by_node(node)
self._update_listeners_map()
def _update_enabled_policies(self):
policy_set = self._policy_set
config = self._config
config_dict = config.get_config_dict()
policy_set.update_by_config(config_dict)
def _update_listeners_map(self):
self._update_enabled_policies()
self._listeners_map = {}
policy_set = self._policy_set
for policy in policy_set.get_enabled_policies():
listened_node_types = policy.listen_node_types()
for listened_node_type in listened_node_types:
if listened_node_type not in self._listeners_map:
self._listeners_map[listened_node_type] = [policy]
else:
self._listeners_map[listened_node_type].append(policy)
|
class Linter(object):
''' A class for Linters.
This class provides a linting algorithm that know how to lint by Policy
class, and how to manage enabled policies by using Config classes.
The class manage what policies are enabled by using the Config class.
The config should be refreshed when a config comment is found.
Then the Linter class notify refresh request to the Config class in
traversing.
The Linter class lint by event-driven traversing.
Enabled policies request to call their when the nodes necesary to validate
are found in traversing. The Linter class collect violations that are
returned by policies.
'''
def __init__(self, policy_set, config_dict_global):
pass
def build_parser(self):
pass
def _parse_vimlparser_error(self, err_message):
pass
def _create_parse_error(self, path, err_message):
pass
def _create_decoding_error(self, path, err_message):
pass
def lint(self, lint_target):
pass
def _traverse(self, root_ast, lint_target):
pass
def _prepare_for_traversal(self):
pass
def _handle_enter(self, node, lint_context):
pass
def _handle_leave(self, node, lint_context):
pass
def _fire_listeners(self, node, lint_context):
pass
def _refresh_policies_if_necessary(self, node):
pass
def _update_enabled_policies(self):
pass
def _update_listeners_map(self):
pass
| 15 | 1 | 11 | 2 | 9 | 0 | 2 | 0.13 | 1 | 12 | 9 | 0 | 14 | 9 | 14 | 14 | 189 | 52 | 124 | 46 | 109 | 16 | 81 | 45 | 66 | 4 | 1 | 3 | 25 |
144,137 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/policy/prohibit_command_with_unintended_side_effect.py
|
vint.linting.policy.prohibit_command_with_unintended_side_effect.ProhibitCommandWithUnintendedSideEffect
|
class ProhibitCommandWithUnintendedSideEffect(AbstractPolicy):
level = Level.WARNING
description = 'Do not use a command that has unintended side effects'
reference = get_reference_source('DANGEROUS')
def listen_node_types(self):
return [
NodeType.EXCMD,
]
def is_valid(self, node, lint_context):
""" Whether the specified node is valid to the policy.
This policy prohibit using `:s[ubstitute]` family.
"""
command = node['ea']['cmd'].get('name', None)
is_prohibited_command = any(pattern == command
for pattern in PROHIBITED_COMMAND_PATTERNS)
return not is_prohibited_command
|
class ProhibitCommandWithUnintendedSideEffect(AbstractPolicy):
def listen_node_types(self):
pass
def is_valid(self, node, lint_context):
''' Whether the specified node is valid to the policy.
This policy prohibit using `:s[ubstitute]` family.
'''
pass
| 3 | 1 | 7 | 1 | 5 | 2 | 1 | 0.23 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 9 | 22 | 6 | 13 | 8 | 10 | 3 | 10 | 8 | 7 | 1 | 2 | 0 | 2 |
144,138 |
Kuniwak/vint
|
Kuniwak_vint/vint/linting/lint_target.py
|
vint.linting.lint_target.LintTargetBufferedStream
|
class LintTargetBufferedStream(AbstractLintTarget):
def __init__(self, alternate_path, buffered_io):
# type: (Path, BufferedIOBase) -> None
super(LintTargetBufferedStream, self).__init__(alternate_path)
self._buffered_io = buffered_io
def read(self): # type: () -> bytes
return self._buffered_io.read()
|
class LintTargetBufferedStream(AbstractLintTarget):
def __init__(self, alternate_path, buffered_io):
pass
def read(self):
pass
| 3 | 0 | 3 | 0 | 3 | 1 | 1 | 0.33 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 4 | 9 | 2 | 6 | 4 | 3 | 2 | 6 | 4 | 3 | 1 | 2 | 0 | 2 |
144,139 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_scope_detector.py
|
test.unit.vint.ast.plugin.scope_plugin.test_scope_detector.TestScopeDetector
|
class TestScopeDetector(unittest.TestCase):
def test_parameterized(self):
test_cases = [
# Declarative variable test
(Vis.SCRIPT_LOCAL, create_id('g:explicit_global'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('implicit_global'), Vis.GLOBAL_LIKE, Explicity.IMPLICIT),
(Vis.FUNCTION_LOCAL, create_id('g:explicit_global'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('b:buffer_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('b:buffer_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('w:window_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('w:window_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('s:script_local'), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('s:script_local'), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('l:explicit_function_local'), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('implicit_function_local'), Vis.FUNCTION_LOCAL, Explicity.IMPLICIT),
(Vis.FUNCTION_LOCAL, create_id('param', is_declarative=True, is_declarative_parameter=True), Vis.FUNCTION_LOCAL, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.SCRIPT_LOCAL, create_id('v:count'), Vis.BUILTIN, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('v:count'), Vis.BUILTIN, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('count'), Vis.BUILTIN, Explicity.IMPLICIT),
(Vis.SCRIPT_LOCAL, create_curlyname(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.FUNCTION_LOCAL, create_curlyname(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.SCRIPT_LOCAL, create_subscript_member(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.FUNCTION_LOCAL, create_subscript_member(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.SCRIPT_LOCAL, create_id('g:ExplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('ImplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.SCRIPT_LOCAL, create_id('g:file#explicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('file#implicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.FUNCTION_LOCAL, create_id('g:ExplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('ImplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.FUNCTION_LOCAL, create_id('g:file#explicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('file#implicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.SCRIPT_LOCAL, create_id('s:ScriptLocalFunc', is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('s:ScriptLocalFunc', is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('t:InvalidScopeFunc', is_function=True), Vis.INVALID, Explicity.EXPLICIT),
# Referencing variable test
(Vis.SCRIPT_LOCAL, create_id('g:explicit_global', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('implicit_global', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.IMPLICIT),
(Vis.FUNCTION_LOCAL, create_id('g:explicit_global', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('b:buffer_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('b:buffer_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('w:window_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('w:window_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('s:script_local', is_declarative=False), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('s:script_local', is_declarative=False), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('l:explicit_function_local', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('implicit_function_local', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.IMPLICIT),
(Vis.FUNCTION_LOCAL, create_id('a:param', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('a:000', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('a:1', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('v:count', is_declarative=False), Vis.BUILTIN, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('v:count', is_declarative=False), Vis.BUILTIN, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('count', is_declarative=False), Vis.BUILTIN, Explicity.IMPLICIT),
(Vis.SCRIPT_LOCAL, create_id('localtime', is_declarative=False, is_function=True), Vis.BUILTIN, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.SCRIPT_LOCAL, create_curlyname(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.FUNCTION_LOCAL, create_curlyname(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.SCRIPT_LOCAL, create_subscript_member(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.FUNCTION_LOCAL, create_subscript_member(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
(Vis.SCRIPT_LOCAL, create_id('g:ExplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('ImplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.SCRIPT_LOCAL, create_id('g:file#explicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('file#implicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.FUNCTION_LOCAL, create_id('g:ExplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('ImplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.FUNCTION_LOCAL, create_id('g:file#explicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('file#implicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),
(Vis.SCRIPT_LOCAL, create_id('s:ScriptLocalFunc', is_declarative=False, is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.FUNCTION_LOCAL, create_id('s:ScriptLocalFunc', is_declarative=False, is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
(Vis.SCRIPT_LOCAL, create_id('t:TabLocalFuncRef', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
]
for context_scope_visibility, id_node, expected_scope_visibility, expected_explicity in test_cases:
scope = create_scope(context_scope_visibility)
scope_visibility_hint = detect_possible_scope_visibility(id_node, scope)
self.assertEqual(expected_scope_visibility, scope_visibility_hint.scope_visibility, id_node)
self.assertEqual(expected_explicity, scope_visibility_hint.explicity, id_node)
|
class TestScopeDetector(unittest.TestCase):
def test_parameterized(self):
pass
| 2 | 0 | 104 | 31 | 71 | 10 | 2 | 0.14 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 105 | 31 | 72 | 6 | 70 | 10 | 8 | 6 | 6 | 2 | 2 | 1 | 2 |
144,140 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_redir_assignment_parser.py
|
test.unit.vint.ast.plugin.scope_plugin.test_redir_assignment_parser.TestRedirAssignmentParser
|
class TestRedirAssignmentParser(unittest.TestCase):
def create_ast(self, file_path):
parser = Parser()
ast = parser.parse(LintTargetFile(file_path.value))
return ast
def test_process(self):
ast = self.create_ast(Fixtures.REDIR_VARIABLE)
parser = RedirAssignmentParser()
got_ast = parser.process(ast)
got_identifier = get_redir_content(got_ast['body'][0])
self.assertEqual('g:var', got_identifier.get('value'))
def test_traverse(self):
ast = self.create_ast(Fixtures.REDIR_VARIABLE)
parser = RedirAssignmentParser()
got_ast = parser.process(ast)
is_redir_content_visited = {
'g:var': False,
}
def enter_handler(node):
if NodeType(node['type']) is not NodeType.IDENTIFIER:
return
is_redir_content_visited[node['value']] = True
traverse(got_ast, on_enter=enter_handler)
self.assertTrue(all(is_redir_content_visited.values()))
|
class TestRedirAssignmentParser(unittest.TestCase):
def create_ast(self, file_path):
pass
def test_process(self):
pass
def test_traverse(self):
pass
def enter_handler(node):
pass
| 5 | 0 | 9 | 2 | 7 | 0 | 1 | 0 | 1 | 5 | 5 | 0 | 3 | 0 | 3 | 75 | 34 | 10 | 24 | 15 | 19 | 0 | 22 | 15 | 17 | 2 | 2 | 1 | 5 |
144,141 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/linting/config/test_config_next_line_comment_source.py
|
test.unit.vint.linting.config.test_config_next_line_comment_source.Fixtures
|
class Fixtures(enum.Enum):
SIMPLE = get_fixture_path("fixture_for_line_comment_simple.vim")
LAMBDA_STRING_EXPR = get_fixture_path("fixture_for_line_comment_lambda_string_expr.vim")
|
class Fixtures(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
144,142 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/linting/config/test_config_global_source.py
|
test.unit.vint.linting.config.test_config_global_source.TestConfigGlobalSource
|
class TestConfigGlobalSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
env = {
'home_path': get_fixture_path('dummy_home'),
'xdg_config_home': get_fixture_path('unexistent_xdg_config_home'),
}
expected_config_dict = {
'cmdargs': {
'verbose': bool,
'error-limit': int,
'severity': Level,
},
'source_name': str,
}
config_source = self.initialize_config_source_with_env(ConfigGlobalSource, env)
self.assertConfigValueType(config_source, expected_config_dict)
def test_get_config_dict_with_no_global_config(self):
env = {
'home_path': get_fixture_path('unexistent_home'),
'xdg_config_home': get_fixture_path('unexistent_xdg_config_home'),
}
expected_config_dict = {'source_name': 'ConfigGlobalSource'}
config_source = self.initialize_config_source_with_env(ConfigGlobalSource, env)
self.assertConfigDict(config_source, expected_config_dict)
def test_get_config_dict_with_default_xdg_config_home(self):
env = {
'home_path': get_fixture_path('unexistent_home'),
'xdg_config_home': get_fixture_path('xdg_config_home'),
}
expected_config_dict = {
'cmdargs': {
'verbose': bool,
'error-limit': int,
'severity': Level,
},
'source_name': str,
}
config_source = self.initialize_config_source_with_env(ConfigGlobalSource, env)
self.assertConfigValueType(config_source, expected_config_dict)
|
class TestConfigGlobalSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
pass
def test_get_config_dict_with_no_global_config(self):
pass
def test_get_config_dict_with_default_xdg_config_home(self):
pass
| 4 | 0 | 13 | 0 | 13 | 0 | 1 | 0 | 2 | 5 | 2 | 0 | 3 | 0 | 3 | 79 | 43 | 4 | 39 | 13 | 35 | 0 | 16 | 13 | 12 | 1 | 3 | 0 | 3 |
144,143 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/linting/config/test_config_file_source.py
|
test.unit.vint.linting.config.test_config_file_source.TestConfigFileSource
|
class TestConfigFileSource(ConfigSourceAssertion, unittest.TestCase):
class ConcreteConfigFileSource(ConfigFileSource):
def get_file_path(self, env):
return FIXTURE_CONFIG_FILE
def test_get_config_dict(self):
expected_config_dict = {
'cmdargs': {
'verbose': True,
'severity': Level.WARNING,
'error-limit': 10,
},
'policies': {
'ProhibitSomethingEvil': {
'enabled': False,
},
'ProhibitSomethingDengerous': {
'enabled': True,
},
},
'source_name': 'ConcreteConfigFileSource',
}
config_source = self.initialize_config_source_with_env(
TestConfigFileSource.ConcreteConfigFileSource)
self.assertConfigDict(config_source, expected_config_dict)
|
class TestConfigFileSource(ConfigSourceAssertion, unittest.TestCase):
class ConcreteConfigFileSource(ConfigFileSource):
def get_file_path(self, env):
pass
def test_get_config_dict(self):
pass
| 4 | 0 | 12 | 1 | 11 | 0 | 1 | 0 | 2 | 2 | 2 | 0 | 1 | 0 | 1 | 77 | 27 | 3 | 24 | 6 | 20 | 0 | 8 | 6 | 4 | 1 | 3 | 0 | 2 |
144,144 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/linting/config/test_config_dict_source.py
|
test.unit.vint.linting.config.test_config_dict_source.TestConfigDictSource
|
class TestConfigDictSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
config_dict = {
'cmdargs': {
'verbose': True,
'severity': Level.WARNING,
'error-limit': 10,
},
'policies': {
'ProhibitSomethingEvil': {
'enabled': False,
},
'ProhibitSomethingDengerous': {
'enabled': True,
},
},
'source_name': 'ConfigDictSource',
}
config_source = ConfigDictSource(config_dict)
expected_config_dict = config_dict
self.assertConfigDict(config_source, expected_config_dict)
|
class TestConfigDictSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
pass
| 2 | 0 | 22 | 2 | 20 | 0 | 1 | 0 | 2 | 2 | 2 | 0 | 1 | 0 | 1 | 77 | 23 | 2 | 21 | 5 | 19 | 0 | 6 | 5 | 4 | 1 | 3 | 0 | 1 |
144,145 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/linting/config/test_config_default_source.py
|
test.unit.vint.linting.config.test_config_default_source.TestConfigDefaultSource
|
class TestConfigDefaultSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
expected_type = {
'cmdargs': {
'verbose': bool,
'error-limit': int,
'severity': Enum,
}
}
config_source = self.initialize_config_source_with_env(ConfigDefaultSource)
self.assertConfigValueType(config_source, expected_type)
|
class TestConfigDefaultSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
pass
| 2 | 0 | 11 | 1 | 10 | 0 | 1 | 0 | 2 | 4 | 1 | 0 | 1 | 0 | 1 | 77 | 12 | 1 | 11 | 4 | 9 | 0 | 5 | 4 | 3 | 1 | 3 | 0 | 1 |
144,146 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/linting/config/test_config_container.py
|
test.unit.vint.linting.config.test_config_container.TestConfigContainer
|
class TestConfigContainer(ConfigSourceAssertion, unittest.TestCase):
class StubConfigSource(ConfigSource):
def __init__(self, config_dict):
self.return_value = config_dict
def get_config_dict(self):
return self.return_value
def test_get_config_dict(self):
config_dicts = (
{ # Default source
'cmdargs': {
'verbose': True,
'severity': Level.WARNING,
'error-limit': 10,
},
'policies': {
'ProhibitSomethingEvil': {
'enabled': False,
},
'ProhibitSomethingDangerous': {
'enabled': True,
},
},
'source_name': 'FirstSource',
},
{ # Something to overwrite
'cmdargs': {
'error-limit': 20,
},
'policies': {
'ProhibitSomethingEvil': {
'enabled': True,
},
},
'source_name': 'SecondSource',
},
{
'source_name': 'ThirdSource',
}, # Something to overwrite but no affect
)
config_sources = [TestConfigContainer.StubConfigSource(config_dict)
for config_dict in config_dicts]
config_container = ConfigContainer(*config_sources)
expected_config_dict = {
'cmdargs': {
'verbose': True,
'severity': Level.WARNING,
'error-limit': 20,
},
'policies': {
'ProhibitSomethingEvil': {
'enabled': True,
},
'ProhibitSomethingDangerous': {
'enabled': True,
},
},
'source_name': 'ConfigContainer',
}
self.assertConfigDict(config_container, expected_config_dict)
|
class TestConfigContainer(ConfigSourceAssertion, unittest.TestCase):
class StubConfigSource(ConfigSource):
def __init__(self, config_dict):
pass
def get_config_dict(self):
pass
def test_get_config_dict(self):
pass
| 5 | 0 | 20 | 1 | 19 | 1 | 1 | 0.05 | 2 | 3 | 3 | 0 | 1 | 0 | 1 | 77 | 67 | 8 | 59 | 10 | 54 | 3 | 12 | 10 | 7 | 1 | 3 | 0 | 3 |
144,147 |
Kuniwak/vint
|
Kuniwak_vint/test/unit/vint/linting/config/test_config_comment_parser.py
|
test.unit.vint.linting.config.test_config_comment_parser.TestConfigCommentParser
|
class TestConfigCommentParser(ConfigCommentAssertion, unittest.TestCase):
def test_parse_config_comment_empty(self):
expected_config_comment = ConfigComment(
config_dict={'policies': {}},
is_only_next_line=False
)
config_comment = parse_config_comment(' vint:')
self.assertConfigCommentEqual(config_comment, expected_config_comment)
def test_parse_config_comment(self):
expected_config_comment = ConfigComment(
config_dict={
'policies': {
'Policy1': {
'enabled': False,
},
'Policy2': {
'enabled': True,
},
},
},
is_only_next_line=False
)
config_comment = parse_config_comment(' vint: -Policy1 +Policy2')
self.assertConfigCommentEqual(config_comment, expected_config_comment)
def test_parse_config_comment_next_line(self):
expected_config_comment = ConfigComment(
config_dict={
'policies': {
'Policy1': {
'enabled': False,
},
'Policy2': {
'enabled': True,
},
},
},
is_only_next_line=True
)
config_dict = parse_config_comment(' vint: next-line -Policy1 +Policy2')
self.assertConfigCommentEqual(config_dict, expected_config_comment)
def test_parse_config_comment_next_line_with_no_white_spaces(self):
expected_config_comment = ConfigComment(
config_dict={'policies': {}},
is_only_next_line=True
)
config_dict = parse_config_comment('vint:next-line')
self.assertConfigCommentEqual(config_dict, expected_config_comment)
def test_parse_not_config_comment(self):
config_comment = parse_config_comment(' not config comment')
self.assertIsNone(config_comment)
|
class TestConfigCommentParser(ConfigCommentAssertion, unittest.TestCase):
def test_parse_config_comment_empty(self):
pass
def test_parse_config_comment_empty(self):
pass
def test_parse_config_comment_next_line(self):
pass
def test_parse_config_comment_next_line_with_no_white_spaces(self):
pass
def test_parse_not_config_comment(self):
pass
| 6 | 0 | 12 | 2 | 10 | 0 | 1 | 0 | 2 | 1 | 1 | 0 | 5 | 0 | 5 | 78 | 67 | 17 | 50 | 15 | 44 | 0 | 20 | 15 | 14 | 1 | 3 | 0 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.