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
3,000
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/assertpy/dynamic.py
assertpy.dynamic.DynamicMixin
class DynamicMixin(object): """Dynamic assertions mixin.""" def __getattr__(self, attr): """Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>().""" if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] err_msg = False is_dict = isinstance(self.val, Iterable) and hasattr(self.val, '__getitem__') if not hasattr(self.val, attr_name): if is_dict: if attr_name not in self.val: err_msg = 'Expected key <%s>, but val has no key <%s>.' % (attr_name, attr_name) else: err_msg = 'Expected attribute <%s>, but val has no attribute <%s>.' % (attr_name, attr_name) def _wrapper(*args, **kwargs): if err_msg: self._err(err_msg) # ok to raise AssertionError now that we are inside wrapper else: if len(args) != 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) try: val_attr = getattr(self.val, attr_name) except AttributeError: val_attr = self.val[attr_name] if callable(val_attr): try: actual = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: actual = val_attr expected = args[0] if actual != expected: self._err('Expected <%s> to be equal to <%s> on %s <%s>, but was not.' % (actual, expected, 'key' if is_dict else 'attribute', attr_name)) return self return _wrapper
class DynamicMixin(object): '''Dynamic assertions mixin.''' def __getattr__(self, attr): '''Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>().''' pass def _wrapper(*args, **kwargs): pass
3
2
33
5
28
2
7
0.09
1
2
0
1
1
0
1
1
45
8
35
9
32
3
32
9
29
8
1
3
13
3,001
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/assertpy/exception.py
assertpy.exception.ExceptionMixin
class ExceptionMixin(object): """Expected exception mixin.""" def raises(self, ex): """Asserts that val is callable and that when called raises the given error.""" if not callable(self.val): raise TypeError('val must be callable') if not issubclass(ex, BaseException): raise TypeError('given arg must be exception') return self._builder(self.val, self.description, self.kind, ex) # don't chain! def when_called_with(self, *some_args, **some_kwargs): """Asserts the val callable when invoked with the given args and kwargs raises the expected exception.""" if not self.expected: raise TypeError('expected exception not set, raises() must be called first') try: self.val(*some_args, **some_kwargs) except BaseException as e: if issubclass(type(e), self.expected): # chain on with _message_ (don't chain to self!) return self._builder(str(e), self.description, self.kind) else: # got exception, but wrong type, so raise self._err('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs), type(e).__name__)) # didn't fail as expected, so raise self._err('Expected <%s> to raise <%s> when called with (%s).' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs)))
class ExceptionMixin(object): '''Expected exception mixin.''' def raises(self, ex): '''Asserts that val is callable and that when called raises the given error.''' pass def when_called_with(self, *some_args, **some_kwargs): '''Asserts the val callable when invoked with the given args and kwargs raises the expected exception.''' pass
3
3
15
1
12
3
4
0.28
1
4
0
1
2
0
2
2
34
3
25
4
22
7
17
3
14
4
1
2
7
3,002
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_custom_dict.py
test_custom_dict.CustomDict
class CustomDict(object): def __init__(self, d): self._dict = d self._idx = 0 def __iter__(self): return self def __next__(self): try: result = self.keys()[self._idx] except IndexError: raise StopIteration self._idx += 1 return result def __contains__(self, key): return key in self.keys() def keys(self): return list(self._dict.keys()) def values(self): return list(self._dict.values()) def __getitem__(self, key): return self._dict.get(key)
class CustomDict(object): def __init__(self, d): pass def __iter__(self): pass def __next__(self): pass def __contains__(self, key): pass def keys(self): pass def values(self): pass def __getitem__(self, key): pass
8
0
3
0
3
0
1
0
1
3
0
0
7
2
7
7
28
7
21
11
13
0
21
11
13
2
1
1
8
3,003
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_class.py
test_class.Truck
class Truck(AbstractAutomobile): @property def classification(self): return 'truck'
class Truck(AbstractAutomobile): @property def classification(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
4
0
4
3
1
0
3
2
1
1
2
0
1
3,004
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_class.py
test_class.Person
class Person(object): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def name(self): return '%s %s' % (self.first_name, self.last_name) def say_hello(self): return 'Hello, %s!' % self.first_name
class Person(object): def __init__(self, first_name, last_name): pass @property def name(self): pass def say_hello(self): pass
5
0
2
0
2
0
1
0
1
0
0
1
3
2
3
3
11
2
9
7
4
0
8
6
4
1
1
0
3
3,005
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/assertpy/string.py
assertpy.string.StringMixin
class StringMixin(object): """String assertions mixin.""" def is_equal_to_ignoring_case(self, other): """Asserts that val is case-insensitive equal to other.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(other, str_types): raise TypeError('given arg must be a string') if self.val.lower() != other.lower(): self._err('Expected <%s> to be case-insensitive equal to <%s>, but was not.' % (self.val, other)) return self def contains_ignoring_case(self, *items): """Asserts that val is string and contains the given item or items.""" if len(items) == 0: raise ValueError('one or more args must be given') if isinstance(self.val, str_types): if len(items) == 1: if not isinstance(items[0], str_types): raise TypeError('given arg must be a string') if items[0].lower() not in self.val.lower(): self._err('Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0])) else: missing = [] for i in items: if not isinstance(i, str_types): raise TypeError('given args must all be strings') if i.lower() not in self.val.lower(): missing.append(i) if missing: self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing))) elif isinstance(self.val, Iterable): missing = [] for i in items: if not isinstance(i, str_types): raise TypeError('given args must all be strings') found = False for v in self.val: if not isinstance(v, str_types): raise TypeError('val items must all be strings') if i.lower() == v.lower(): found = True break if not found: missing.append(i) if missing: self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing))) else: raise TypeError('val is not a string or iterable') return self def starts_with(self, prefix): """Asserts that val is string or iterable and starts with prefix.""" if prefix is None: raise TypeError('given prefix arg must not be none') if isinstance(self.val, str_types): if not isinstance(prefix, str_types): raise TypeError('given prefix arg must be a string') if len(prefix) == 0: raise ValueError('given prefix arg must not be empty') if not self.val.startswith(prefix): self._err('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix)) elif isinstance(self.val, Iterable): if len(self.val) == 0: raise ValueError('val must not be empty') first = next(iter(self.val)) if first != prefix: self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix)) else: raise TypeError('val is not a string or iterable') return self def ends_with(self, suffix): """Asserts that val is string or iterable and ends with suffix.""" if suffix is None: raise TypeError('given suffix arg must not be none') if isinstance(self.val, str_types): if not isinstance(suffix, str_types): raise TypeError('given suffix arg must be a string') if len(suffix) == 0: raise ValueError('given suffix arg must not be empty') if not self.val.endswith(suffix): self._err('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix)) elif isinstance(self.val, Iterable): if len(self.val) == 0: raise ValueError('val must not be empty') last = None for last in self.val: pass if last != suffix: self._err('Expected %s to end with <%s>, but did not.' % (self.val, suffix)) else: raise TypeError('val is not a string or iterable') return self def matches(self, pattern): """Asserts that val is string and matches regex pattern.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if len(pattern) == 0: raise ValueError('given pattern arg must not be empty') if re.search(pattern, self.val) is None: self._err('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern)) return self def does_not_match(self, pattern): """Asserts that val is string and does not match regex pattern.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if len(pattern) == 0: raise ValueError('given pattern arg must not be empty') if re.search(pattern, self.val) is not None: self._err('Expected <%s> to not match pattern <%s>, but did.' % (self.val, pattern)) return self def is_alpha(self): """Asserts that val is non-empty string and all characters are alphabetic.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if not self.val.isalpha(): self._err('Expected <%s> to contain only alphabetic chars, but did not.' % self.val) return self def is_digit(self): """Asserts that val is non-empty string and all characters are digits.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if not self.val.isdigit(): self._err('Expected <%s> to contain only digits, but did not.' % self.val) return self def is_lower(self): """Asserts that val is non-empty string and all characters are lowercase.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if self.val != self.val.lower(): self._err('Expected <%s> to contain only lowercase chars, but did not.' % self.val) return self def is_upper(self): """Asserts that val is non-empty string and all characters are uppercase.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if self.val != self.val.upper(): self._err('Expected <%s> to contain only uppercase chars, but did not.' % self.val) return self def is_unicode(self): """Asserts that val is a unicode string.""" if type(self.val) is not unicode: self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__)) return self
class StringMixin(object): '''String assertions mixin.''' def is_equal_to_ignoring_case(self, other): '''Asserts that val is case-insensitive equal to other.''' pass def contains_ignoring_case(self, *items): '''Asserts that val is string and contains the given item or items.''' pass def starts_with(self, prefix): '''Asserts that val is string or iterable and starts with prefix.''' pass def ends_with(self, suffix): '''Asserts that val is string or iterable and ends with suffix.''' pass def matches(self, pattern): '''Asserts that val is string and matches regex pattern.''' pass def does_not_match(self, pattern): '''Asserts that val is string and does not match regex pattern.''' pass def is_alpha(self): '''Asserts that val is non-empty string and all characters are alphabetic.''' pass def is_digit(self): '''Asserts that val is non-empty string and all characters are digits.''' pass def is_lower(self): '''Asserts that val is non-empty string and all characters are lowercase.''' pass def is_upper(self): '''Asserts that val is non-empty string and all characters are uppercase.''' pass def is_unicode(self): '''Asserts that val is a unicode string.''' pass
12
12
14
0
13
1
6
0.08
1
3
0
1
11
0
11
11
165
11
142
18
130
12
135
18
123
18
1
4
69
3,006
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/assertpy/numeric.py
assertpy.numeric.NumericMixin
class NumericMixin(object): """Numeric assertions mixin.""" NUMERIC_COMPAREABLE = set([datetime.datetime, datetime.timedelta, datetime.date, datetime.time]) NUMERIC_NON_COMPAREABLE = set([complex]) def _validate_compareable(self, other): self_type = type(self.val) other_type = type(other) if self_type in self.NUMERIC_NON_COMPAREABLE: raise TypeError('ordering is not defined for type <%s>' % self_type.__name__) if self_type in self.NUMERIC_COMPAREABLE: if other_type is not self_type: raise TypeError('given arg must be <%s>, but was <%s>' % (self_type.__name__, other_type.__name__)) return if isinstance(self.val, numbers.Number): if not isinstance(other, numbers.Number): raise TypeError('given arg must be a number, but was <%s>' % other_type.__name__) return raise TypeError('ordering is not defined for type <%s>' % self_type.__name__) def _validate_number(self): """Raise TypeError if val is not numeric.""" if isinstance(self.val, numbers.Number) is False: raise TypeError('val is not numeric') def _validate_real(self): """Raise TypeError if val is not real number.""" if isinstance(self.val, numbers.Real) is False: raise TypeError('val is not real number') def is_zero(self): """Asserts that val is numeric and equal to zero.""" self._validate_number() return self.is_equal_to(0) def is_not_zero(self): """Asserts that val is numeric and not equal to zero.""" self._validate_number() return self.is_not_equal_to(0) def is_nan(self): """Asserts that val is real number and NaN (not a number).""" self._validate_number() self._validate_real() if not math.isnan(self.val): self._err('Expected <%s> to be <NaN>, but was not.' % self.val) return self def is_not_nan(self): """Asserts that val is real number and not NaN (not a number).""" self._validate_number() self._validate_real() if math.isnan(self.val): self._err('Expected not <NaN>, but was.') return self def is_inf(self): """Asserts that val is real number and Inf (infinity).""" self._validate_number() self._validate_real() if not math.isinf(self.val): self._err('Expected <%s> to be <Inf>, but was not.' % self.val) return self def is_not_inf(self): """Asserts that val is real number and not Inf (infinity).""" self._validate_number() self._validate_real() if math.isinf(self.val): self._err('Expected not <Inf>, but was.') return self def is_greater_than(self, other): """Asserts that val is numeric and is greater than other.""" self._validate_compareable(other) if self.val <= other: if type(self.val) is datetime.datetime: self._err('Expected <%s> to be greater than <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: self._err('Expected <%s> to be greater than <%s>, but was not.' % (self.val, other)) return self def is_greater_than_or_equal_to(self, other): """Asserts that val is numeric and is greater than or equal to other.""" self._validate_compareable(other) if self.val < other: if type(self.val) is datetime.datetime: self._err('Expected <%s> to be greater than or equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: self._err('Expected <%s> to be greater than or equal to <%s>, but was not.' % (self.val, other)) return self def is_less_than(self, other): """Asserts that val is numeric and is less than other.""" self._validate_compareable(other) if self.val >= other: if type(self.val) is datetime.datetime: self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val, other)) return self def is_less_than_or_equal_to(self, other): """Asserts that val is numeric and is less than or equal to other.""" self._validate_compareable(other) if self.val > other: if type(self.val) is datetime.datetime: self._err('Expected <%s> to be less than or equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: self._err('Expected <%s> to be less than or equal to <%s>, but was not.' % (self.val, other)) return self def is_positive(self): """Asserts that val is numeric and greater than zero.""" return self.is_greater_than(0) def is_negative(self): """Asserts that val is numeric and less than zero.""" return self.is_less_than(0) def is_between(self, low, high): """Asserts that val is numeric and is between low and high.""" val_type = type(self.val) self._validate_between_args(val_type, low, high) if self.val < low or self.val > high: if val_type is datetime.datetime: self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S'))) else: self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val, low, high)) return self def is_not_between(self, low, high): """Asserts that val is numeric and is between low and high.""" val_type = type(self.val) self._validate_between_args(val_type, low, high) if self.val >= low and self.val <= high: if val_type is datetime.datetime: self._err('Expected <%s> to not be between <%s> and <%s>, but was.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S'))) else: self._err('Expected <%s> to not be between <%s> and <%s>, but was.' % (self.val, low, high)) return self def is_close_to(self, other, tolerance): """Asserts that val is numeric and is close to other within tolerance.""" self._validate_close_to_args(self.val, other, tolerance) if self.val < (other-tolerance) or self.val > (other+tolerance): if type(self.val) is datetime.datetime: tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000 h, rem = divmod(tolerance_seconds, 3600) m, s = divmod(rem, 60) self._err('Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s)) else: self._err('Expected <%s> to be close to <%s> within tolerance <%s>, but was not.' % (self.val, other, tolerance)) return self def is_not_close_to(self, other, tolerance): """Asserts that val is numeric and is not close to other within tolerance.""" self._validate_close_to_args(self.val, other, tolerance) if self.val >= (other-tolerance) and self.val <= (other+tolerance): if type(self.val) is datetime.datetime: tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000 h, rem = divmod(tolerance_seconds, 3600) m, s = divmod(rem, 60) self._err('Expected <%s> to not be close to <%s> within tolerance <%d:%02d:%02d>, but was.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s)) else: self._err('Expected <%s> to not be close to <%s> within tolerance <%s>, but was.' % (self.val, other, tolerance)) return self
class NumericMixin(object): '''Numeric assertions mixin.''' def _validate_compareable(self, other): pass def _validate_number(self): '''Raise TypeError if val is not numeric.''' pass def _validate_real(self): '''Raise TypeError if val is not real number.''' pass def is_zero(self): '''Asserts that val is numeric and equal to zero.''' pass def is_not_zero(self): '''Asserts that val is numeric and not equal to zero.''' pass def is_nan(self): '''Asserts that val is real number and NaN (not a number).''' pass def is_not_nan(self): '''Asserts that val is real number and not NaN (not a number).''' pass def is_inf(self): '''Asserts that val is real number and Inf (infinity).''' pass def is_not_inf(self): '''Asserts that val is real number and not Inf (infinity).''' pass def is_greater_than(self, other): '''Asserts that val is numeric and is greater than other.''' pass def is_greater_than_or_equal_to(self, other): '''Asserts that val is numeric and is greater than or equal to other.''' pass def is_less_than(self, other): '''Asserts that val is numeric and is less than other.''' pass def is_less_than_or_equal_to(self, other): '''Asserts that val is numeric and is less than or equal to other.''' pass def is_positive(self): '''Asserts that val is numeric and greater than zero.''' pass def is_negative(self): '''Asserts that val is numeric and less than zero.''' pass def is_between(self, low, high): '''Asserts that val is numeric and is between low and high.''' pass def is_not_between(self, low, high): '''Asserts that val is numeric and is between low and high.''' pass def is_close_to(self, other, tolerance): '''Asserts that val is numeric and is close to other within tolerance.''' pass def is_not_close_to(self, other, tolerance): '''Asserts that val is numeric and is not close to other within tolerance.''' pass
20
19
8
0
7
1
2
0.15
1
5
0
1
19
0
19
19
173
25
129
32
109
19
121
32
101
6
1
2
46
3,007
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/assertpy/helpers.py
assertpy.helpers.HelpersMixin
class HelpersMixin(object): """Helpers mixin.""" def _fmt_items(self, i): if len(i) == 0: return '<>' elif len(i) == 1 and hasattr(i, '__getitem__'): return '<%s>' % i[0] else: return '<%s>' % str(i).lstrip('([').rstrip(',])') def _fmt_args_kwargs(self, *some_args, **some_kwargs): """Helper to convert the given args and kwargs into a string.""" if some_args: out_args = str(some_args).lstrip('(').rstrip(',)') if some_kwargs: out_kwargs = ', '.join([str(i).lstrip('(').rstrip(')').replace(', ',': ') for i in [ (k,some_kwargs[k]) for k in sorted(some_kwargs.keys())]]) if some_args and some_kwargs: return out_args + ', ' + out_kwargs elif some_args: return out_args elif some_kwargs: return out_kwargs else: return '' def _validate_between_args(self, val_type, low, high): low_type = type(low) high_type = type(high) if val_type in self.NUMERIC_NON_COMPAREABLE: raise TypeError('ordering is not defined for type <%s>' % val_type.__name__) if val_type in self.NUMERIC_COMPAREABLE: if low_type is not val_type: raise TypeError('given low arg must be <%s>, but was <%s>' % (val_type.__name__, low_type.__name__)) if high_type is not val_type: raise TypeError('given high arg must be <%s>, but was <%s>' % (val_type.__name__, low_type.__name__)) elif isinstance(self.val, numbers.Number): if isinstance(low, numbers.Number) is False: raise TypeError('given low arg must be numeric, but was <%s>' % low_type.__name__) if isinstance(high, numbers.Number) is False: raise TypeError('given high arg must be numeric, but was <%s>' % high_type.__name__) else: raise TypeError('ordering is not defined for type <%s>' % val_type.__name__) if low > high: raise ValueError('given low arg must be less than given high arg') def _validate_close_to_args(self, val, other, tolerance): if type(val) is complex or type(other) is complex or type(tolerance) is complex: raise TypeError('ordering is not defined for complex numbers') if isinstance(val, numbers.Number) is False and type(val) is not datetime.datetime: raise TypeError('val is not numeric or datetime') if type(val) is datetime.datetime: if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was <%s>' % type(other).__name__) if type(tolerance) is not datetime.timedelta: raise TypeError('given tolerance arg must be timedelta, but was <%s>' % type(tolerance).__name__) else: if isinstance(other, numbers.Number) is False: raise TypeError('given arg must be numeric') if isinstance(tolerance, numbers.Number) is False: raise TypeError('given tolerance arg must be numeric') if tolerance < 0: raise ValueError('given tolerance arg must be positive') def _check_dict_like(self, d, check_keys=True, check_values=True, check_getitem=True, name='val', return_as_bool=False): if not isinstance(d, Iterable): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: not iterable' % (name, type(d).__name__)) if check_keys: if not hasattr(d, 'keys') or not callable(getattr(d, 'keys')): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: missing keys()' % (name, type(d).__name__)) if check_values: if not hasattr(d, 'values') or not callable(getattr(d, 'values')): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: missing values()' % (name, type(d).__name__)) if check_getitem: if not hasattr(d, '__getitem__'): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: missing [] accessor' % (name, type(d).__name__)) if return_as_bool: return True def _check_iterable(self, l, check_getitem=True, name='val'): if not isinstance(l, Iterable): raise TypeError('%s <%s> is not iterable' % (name, type(l).__name__)) if check_getitem: if not hasattr(l, '__getitem__'): raise TypeError('%s <%s> does not have [] accessor' % (name, type(l).__name__)) def _dict_not_equal(self, val, other, ignore=None, include=None): if ignore or include: ignores = self._dict_ignore(ignore) includes = self._dict_include(include) # guarantee include keys are in val if include: missing = [] for i in includes: if i not in val: missing.append(i) if missing: self._err('Expected <%s> to include key%s %s, but did not include key%s %s.' % ( val, '' if len(includes) == 1 else 's', self._fmt_items(['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in includes]), '' if len(missing) == 1 else 's', self._fmt_items(missing))) if ignore and include: k1 = set([k for k in val if k not in ignores and k in includes]) elif ignore: k1 = set([k for k in val if k not in ignores]) else: # include k1 = set([k for k in val if k in includes]) if ignore and include: k2 = set([k for k in other if k not in ignores and k in includes]) elif ignore: k2 = set([k for k in other if k not in ignores]) else: # include k2 = set([k for k in other if k in includes]) if k1 != k2: return True else: for k in k1: if self._check_dict_like(val[k], check_values=False, return_as_bool=True) and self._check_dict_like(other[k], check_values=False, return_as_bool=True): return self._dict_not_equal(val[k], other[k], ignore=[i[1:] for i in ignores if type(i) is tuple and i[0] == k] if ignore else None, include=[i[1:] for i in self._dict_ignore(include) if type(i) is tuple and i[0] == k] if include else None) elif val[k] != other[k]: return True return False else: return val != other def _dict_ignore(self, ignore): return [i[0] if type(i) is tuple and len(i) == 1 else i \ for i in (ignore if type(ignore) is list else [ignore])] def _dict_include(self, include): return [i[0] if type(i) is tuple else i \ for i in (include if type(include) is list else [include])] def _dict_err(self, val, other, ignore=None, include=None): def _dict_repr(d, other): out = '' ellip = False for k,v in d.items(): if k not in other: out += '%s%s: %s' % (', ' if len(out) > 0 else '', repr(k), repr(v)) elif v != other[k]: out += '%s%s: %s' % (', ' if len(out) > 0 else '', repr(k), _dict_repr(v, other[k]) if self._check_dict_like(v, check_values=False, return_as_bool=True) and self._check_dict_like(other[k], check_values=False, return_as_bool=True) else repr(v) ) else: ellip = True return '{%s%s}' % ('..' if ellip and len(out) == 0 else '.., ' if ellip else '', out) if ignore: ignores = self._dict_ignore(ignore) ignore_err = ' ignoring keys %s' % self._fmt_items(['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in ignores]) if include: includes = self._dict_ignore(include) include_err = ' including keys %s' % self._fmt_items(['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in includes]) self._err('Expected <%s> to be equal to <%s>%s%s, but was not.' % ( _dict_repr(val, other), _dict_repr(other, val), ignore_err if ignore else '', include_err if include else '' ))
class HelpersMixin(object): '''Helpers mixin.''' def _fmt_items(self, i): pass def _fmt_args_kwargs(self, *some_args, **some_kwargs): '''Helper to convert the given args and kwargs into a string.''' pass def _validate_between_args(self, val_type, low, high): pass def _validate_close_to_args(self, val, other, tolerance): pass def _check_dict_like(self, d, check_keys=True, check_values=True, check_getitem=True, name='val', return_as_bool=False): pass def _check_iterable(self, l, check_getitem=True, name='val'): pass def _dict_not_equal(self, val, other, ignore=None, include=None): pass def _dict_ignore(self, ignore): pass def _dict_include(self, include): pass def _dict_err(self, val, other, ignore=None, include=None): pass def _dict_repr(d, other): pass
12
2
17
1
16
0
8
0.03
1
11
0
1
10
0
10
10
188
22
163
29
151
5
125
29
113
19
1
4
85
3,008
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/assertpy/file.py
assertpy.file.FileMixin
class FileMixin(object): """File assertions mixin.""" def exists(self): """Asserts that val is a path and that it exists.""" if not isinstance(self.val, str_types): raise TypeError('val is not a path') if not os.path.exists(self.val): self._err('Expected <%s> to exist, but was not found.' % self.val) return self def does_not_exist(self): """Asserts that val is a path and that it does not exist.""" if not isinstance(self.val, str_types): raise TypeError('val is not a path') if os.path.exists(self.val): self._err('Expected <%s> to not exist, but was found.' % self.val) return self def is_file(self): """Asserts that val is an existing path to a file.""" self.exists() if not os.path.isfile(self.val): self._err('Expected <%s> to be a file, but was not.' % self.val) return self def is_directory(self): """Asserts that val is an existing path to a directory.""" self.exists() if not os.path.isdir(self.val): self._err('Expected <%s> to be a directory, but was not.' % self.val) return self def is_named(self, filename): """Asserts that val is an existing path to a file and that file is named filename.""" self.is_file() if not isinstance(filename, str_types): raise TypeError('given filename arg must be a path') val_filename = os.path.basename(os.path.abspath(self.val)) if val_filename != filename: self._err('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename)) return self def is_child_of(self, parent): """Asserts that val is an existing path to a file and that file is a child of parent.""" self.is_file() if not isinstance(parent, str_types): raise TypeError('given parent directory arg must be a path') val_abspath = os.path.abspath(self.val) parent_abspath = os.path.abspath(parent) if not val_abspath.startswith(parent_abspath): self._err('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath)) return self
class FileMixin(object): '''File assertions mixin.''' def exists(self): '''Asserts that val is a path and that it exists.''' pass def does_not_exist(self): '''Asserts that val is a path and that it does not exist.''' pass def is_file(self): '''Asserts that val is an existing path to a file.''' pass def is_directory(self): '''Asserts that val is an existing path to a directory.''' pass def is_named(self, filename): '''Asserts that val is an existing path to a file and that file is named filename.''' pass def is_child_of(self, parent): '''Asserts that val is an existing path to a file and that file is a child of parent.''' pass
7
7
8
0
7
1
3
0.17
1
1
0
1
6
0
6
6
53
6
40
10
33
7
40
10
33
3
1
1
16
3,009
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_custom_dict.py
test_custom_dict.CustomDictNoGetitem
class CustomDictNoGetitem(object): def __iter__(self): return self def __next__(self): return 1 def keys(self): return 'foo' def values(self): return 'bar'
class CustomDictNoGetitem(object): def __iter__(self): pass def __next__(self): pass def keys(self): pass def values(self): pass
5
0
2
0
2
0
1
0
1
0
0
0
4
0
4
4
12
3
9
5
4
0
9
5
4
1
1
0
4
3,010
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_custom_dict.py
test_custom_dict.CustomDictNoKeys
class CustomDictNoKeys(object): def __iter__(self): return self def __next__(self): return 1
class CustomDictNoKeys(object): def __iter__(self): pass def __next__(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
2
6
1
5
3
2
0
5
3
2
1
1
0
2
3,011
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_custom_dict.py
test_custom_dict.CustomDictNoKeysCallable
class CustomDictNoKeysCallable(object): def __init__(self): self.keys = 'foo' def __iter__(self): return self def __next__(self): return 1
class CustomDictNoKeysCallable(object): def __init__(self): pass def __iter__(self): pass def __next__(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
1
3
3
9
2
7
5
3
0
7
5
3
1
1
0
3
3,012
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_class.py
test_class.Car
class Car(AbstractAutomobile): @property def classification(self): return 'car'
class Car(AbstractAutomobile): @property def classification(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
4
0
4
3
1
0
3
2
1
1
2
0
1
3,013
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_custom_dict.py
test_custom_dict.CustomDictNoValuesCallable
class CustomDictNoValuesCallable(object): def __init__(self): self.values = 'foo' def __iter__(self): return self def __next__(self): return 1 def keys(self): return 'foo'
class CustomDictNoValuesCallable(object): def __init__(self): pass def __iter__(self): pass def __next__(self): pass def keys(self): pass
5
0
2
0
2
0
1
0
1
0
0
0
4
1
4
4
12
3
9
6
4
0
9
6
4
1
1
0
4
3,014
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_custom_list.py
test_custom_list.CustomList
class CustomList(object): def __init__(self, s): self._s = s self._idx = 0 def __iter__(self): return self def __next__(self): try: result = self._s[self._idx] except IndexError: raise StopIteration self._idx += 1 return result def __getitem__(self, idx): return self._s[idx]
class CustomList(object): def __init__(self, s): pass def __iter__(self): pass def __next__(self): pass def __getitem__(self, idx): pass
5
0
4
0
4
0
1
0
1
2
0
0
4
2
4
4
19
4
15
8
10
0
15
8
10
2
1
1
5
3,015
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_dyn.py
test_dyn.Person
class Person(object): def __init__(self, first_name, last_name, shoe_size): self.first_name = first_name self.last_name = last_name self.shoe_size = shoe_size @property def name(self): return '%s %s' % (self.first_name, self.last_name) def say_hello(self): return 'Hello, %s!' % self.first_name def say_goodbye(self, target): return 'Bye, %s!' % target
class Person(object): def __init__(self, first_name, last_name, shoe_size): pass @property def name(self): pass def say_hello(self): pass def say_goodbye(self, target): pass
6
0
3
0
3
0
1
0
1
0
0
0
4
3
4
4
15
3
12
9
6
0
11
8
6
1
1
0
4
3,016
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_expected_exception.py
test_expected_exception.Foo
class Foo(object): def bar(self): raise RuntimeError('method err')
class Foo(object): def bar(self): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
3,017
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_extracting.py
test_extracting.Person
class Person(object): def __init__(self, first_name, last_name, shoe_size): self.first_name = first_name self.last_name = last_name self.shoe_size = shoe_size def full_name(self): return '%s %s' % (self.first_name, self.last_name) def say_hello(self, name): return 'Hello, %s!' % name
class Person(object): def __init__(self, first_name, last_name, shoe_size): pass def full_name(self): pass def say_hello(self, name): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
3
3
3
11
2
9
7
5
0
9
7
5
1
1
0
3
3,018
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_file.py
test_file.TestFile
class TestFile(object): def setup(self): self.tmp = tempfile.NamedTemporaryFile() self.tmp.write('foobar'.encode('utf-8')) self.tmp.seek(0) def teardown(self): self.tmp.close() def test_contents_of_path(self): contents = contents_of(self.tmp.name) assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contents_of_path_ascii(self): contents = contents_of(self.tmp.name, 'ascii') assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contents_of_return_type(self): if sys.version_info[0] == 3: contents = contents_of(self.tmp.name) assert_that(contents).is_type_of(str) else: contents = contents_of(self.tmp.name) assert_that(contents).is_type_of(unicode) def test_contents_of_return_type_ascii(self): if sys.version_info[0] == 3: contents = contents_of(self.tmp.name, 'ascii') assert_that(contents).is_type_of(str) else: contents = contents_of(self.tmp.name, 'ascii') assert_that(contents).is_type_of(str) def test_contents_of_file(self): contents = contents_of(self.tmp.file) assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contents_of_file_ascii(self): contents = contents_of(self.tmp.file, 'ascii') assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contains_of_bad_type_failure(self): try: contents_of(123) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val must be file or path, but was type <int>') def test_contains_of_missing_file_failure(self): try: contents_of('missing.txt') fail('should have raised error') except IOError as ex: assert_that(str(ex)).contains_ignoring_case('no such file') def test_exists(self): assert_that(self.tmp.name).exists() def test_exists_failure(self): try: assert_that('missing.txt').exists() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <missing.txt> to exist, but was not found.') def test_exists_bad_val_failure(self): try: assert_that(123).exists() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a path') def test_does_not_exist(self): assert_that('missing.txt').does_not_exist() def test_does_not_exist_failure(self): try: assert_that(self.tmp.name).does_not_exist() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <{}> to not exist, but was found.'.format(self.tmp.name)) def test_does_not_exist_bad_val_failure(self): try: assert_that(123).does_not_exist() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a path') def test_is_file(self): assert_that(self.tmp.name).is_file() def test_is_file_exists_failure(self): try: assert_that('missing.txt').is_file() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <missing.txt> to exist, but was not found.') def test_is_file_directory_failure(self): try: dirname = os.path.dirname(self.tmp.name) assert_that(dirname).is_file() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected <.*> to be a file, but was not.') def test_is_directory(self): dirname = os.path.dirname(self.tmp.name) assert_that(dirname).is_directory() def test_is_directory_exists_failure(self): try: assert_that('missing_dir').is_directory() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <missing_dir> to exist, but was not found.') def test_is_directory_file_failure(self): try: assert_that(self.tmp.name).is_directory() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected <.*> to be a directory, but was not.') def test_is_named(self): basename = os.path.basename(self.tmp.name) assert_that(self.tmp.name).is_named(basename) def test_is_named_failure(self): try: assert_that(self.tmp.name).is_named('foo.txt') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected filename <.*> to be equal to <foo.txt>, but was not.') def test_is_named_bad_arg_type_failure(self): try: assert_that(self.tmp.name).is_named(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).matches('given filename arg must be a path') def test_is_child_of(self): dirname = os.path.dirname(self.tmp.name) assert_that(self.tmp.name).is_child_of(dirname) def test_is_child_of_failure(self): try: assert_that(self.tmp.name).is_child_of('foo_dir') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected file <.*> to be a child of <.*/foo_dir>, but was not.') def test_is_child_of_bad_arg_type_failure(self): try: assert_that(self.tmp.name).is_child_of(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).matches('given parent directory arg must be a path')
class TestFile(object): def setup(self): pass def teardown(self): pass def test_contents_of_path(self): pass def test_contents_of_path_ascii(self): pass def test_contents_of_return_type(self): pass def test_contents_of_return_type_ascii(self): pass def test_contents_of_file(self): pass def test_contents_of_file_ascii(self): pass def test_contains_of_bad_type_failure(self): pass def test_contains_of_missing_file_failure(self): pass def test_exists(self): pass def test_exists_failure(self): pass def test_exists_bad_val_failure(self): pass def test_does_not_exist(self): pass def test_does_not_exist_failure(self): pass def test_does_not_exist_bad_val_failure(self): pass def test_is_file(self): pass def test_is_file_exists_failure(self): pass def test_is_file_directory_failure(self): pass def test_is_directory(self): pass def test_is_directory_exists_failure(self): pass def test_is_directory_file_failure(self): pass def test_is_named(self): pass def test_is_named_failure(self): pass def test_is_named_bad_arg_type_failure(self): pass def test_is_child_of(self): pass def test_is_child_of_failure(self): pass def test_is_child_of_bad_arg_type_failure(self): pass
29
0
5
0
5
0
2
0
1
4
0
0
28
1
28
28
161
28
133
54
104
0
131
40
102
2
1
1
44
3,019
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_list.py
test_list.Person
class Person(object): def __init__(self, name): self.name = name
class Person(object): def __init__(self, name): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
1
3
0
3
3
1
0
3
3
1
1
1
0
1
3,020
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_custom_dict.py
test_custom_dict.CustomDictNoValues
class CustomDictNoValues(object): def __iter__(self): return self def __next__(self): return 1 def keys(self): return 'foo'
class CustomDictNoValues(object): def __iter__(self): pass def __next__(self): pass def keys(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
0
3
3
9
2
7
4
3
0
7
4
3
1
1
0
3
3,021
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/tests/test_readme.py
test_readme.Developer
class Developer(Person): def say_hello(self): return '%s writes code.' % self.first_name
class Developer(Person): def say_hello(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
4
3
0
3
2
1
0
3
2
1
1
2
0
1
3,022
ActivisionGameScience/assertpy
ActivisionGameScience_assertpy/assertpy/extracting.py
assertpy.extracting.ExtractingMixin
class ExtractingMixin(object): """Collection flattening mixin.""" ### collection of objects assertions ### def extracting(self, *names, **kwargs): """Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given).""" if not isinstance(self.val, Iterable): raise TypeError('val is not iterable') if isinstance(self.val, str_types): raise TypeError('val must not be string') if len(names) == 0: raise ValueError('one or more name args must be given') def _extract(x, name): if self._check_dict_like(x, check_values=False, return_as_bool=True): if name in x: return x[name] else: raise ValueError('item keys %s did not contain key <%s>' % (list(x.keys()), name)) elif isinstance(x, Iterable): self._check_iterable(x, name='item') return x[name] elif hasattr(x, name): attr = getattr(x, name) if callable(attr): try: return attr() except TypeError: raise ValueError('val method <%s()> exists, but is not zero-arg method' % name) else: return attr else: raise ValueError('val does not have property or zero-arg method <%s>' % name) def _filter(x): if 'filter' in kwargs: if isinstance(kwargs['filter'], str_types): return bool(_extract(x, kwargs['filter'])) elif self._check_dict_like(kwargs['filter'], check_values=False, return_as_bool=True): for k in kwargs['filter']: if isinstance(k, str_types): if _extract(x, k) != kwargs['filter'][k]: return False return True elif callable(kwargs['filter']): return kwargs['filter'](x) return False return True def _sort(x): if 'sort' in kwargs: if isinstance(kwargs['sort'], str_types): return _extract(x, kwargs['sort']) elif isinstance(kwargs['sort'], Iterable): items = [] for k in kwargs['sort']: if isinstance(k, str_types): items.append(_extract(x, k)) return tuple(items) elif callable(kwargs['sort']): return kwargs['sort'](x) return 0 extracted = [] for i in sorted(self.val, key=lambda x: _sort(x)): if _filter(i): items = [_extract(i, name) for name in names] extracted.append(tuple(items) if len(items) > 1 else items[0]) # chain on with _extracted_ list (don't chain to self!) return self._builder(extracted, self.description, self.kind)
class ExtractingMixin(object): '''Collection flattening mixin.''' def extracting(self, *names, **kwargs): '''Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given).''' pass def _extract(x, name): pass def _filter(x): pass def _sort(x): pass
5
2
29
1
27
1
7
0.07
1
5
0
1
1
1
1
1
71
6
61
12
56
4
52
12
47
8
1
5
29
3,023
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/migrations/0002_scopes_20161208.py
esi.migrations.0002_scopes_20161208.Migration
class Migration(migrations.Migration): dependencies = [ ('esi', '0001_initial'), ] operations = [ migrations.RunPython(generate_scopes, delete_scopes) ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
8
1
7
3
6
0
3
3
2
0
1
0
0
3,024
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/migrations/0001_initial.py
esi.migrations.0001_initial.Migration
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='CallbackRedirect', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('url', models.CharField(default='/', help_text='The internal URL to redirect this callback towards.', max_length=254)), ('session_key', models.CharField(help_text='Session key identifying the session this redirect was created for.', max_length=254, unique=True)), ('state', models.CharField(help_text='OAuth2 state string representing this session.', max_length=128)), ('created', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='Scope', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='The official EVE name for the scope.', max_length=100, unique=True)), ('help_text', models.TextField(help_text='The official EVE description of the scope.')), ], ), migrations.CreateModel( name='Token', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('access_token', models.CharField(help_text='The access token granted by SSO.', max_length=254, unique=True)), ('refresh_token', models.CharField(blank=True, help_text='A re-usable token to generate new access tokens upon expiry.', max_length=254, null=True)), ('character_id', models.IntegerField(help_text='The ID of the EVE character who authenticated by SSO.')), ('character_name', models.CharField(help_text='The name of the EVE character who authenticated by SSO.', max_length=100)), ('token_type', models.CharField(choices=[('Character', 'Character'), ('Corporation', 'Corporation')], default='Character', help_text='The applicable range of the token.', max_length=100)), ('character_owner_hash', models.CharField(help_text='The unique string identifying this character and its owning EVE account. Changes if the owning account changes.', max_length=254)), ('scopes', models.ManyToManyField(blank=True, help_text='The access scopes granted by this token.', to='esi.Scope')), ('user', models.ForeignKey(blank=True, help_text='The user to whom this token belongs.', null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='callbackredirect', name='token', field=models.ForeignKey(blank=True, help_text='Token generated by a completed code exchange from callback processing.', null=True, on_delete=django.db.models.deletion.CASCADE, to='esi.Token'), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
48
3
45
4
44
0
4
4
3
0
1
0
0
3,025
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/errors.py
esi.errors.TokenInvalidError
class TokenInvalidError(TokenError): pass
class TokenInvalidError(TokenError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
4
0
0
3,026
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/managers.py
esi.managers.TokenManager
class TokenManager(models.Manager): def get_queryset(self): """ Replace base queryset model with custom TokenQueryset :rtype: :class:`esi.managers.TokenQueryset` """ return TokenQueryset(self.model, using=self._db) def create_from_code(self, code, user=None): """ Perform OAuth code exchange to retrieve a token. :param code: OAuth grant code. :param user: User who will own token. :return: :class:`esi.models.Token` """ # perform code exchange logger.debug("Creating new token from code {0}".format(code[:-5])) oauth = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, redirect_uri=app_settings.ESI_SSO_CALLBACK_URL) token = oauth.fetch_token(app_settings.ESI_TOKEN_URL, client_secret=app_settings.ESI_SSO_CLIENT_SECRET, code=code) r = oauth.request('get', app_settings.ESI_TOKEN_VERIFY_URL) r.raise_for_status() token_data = r.json() logger.debug(token_data) # translate returned data to a model model = self.create( character_id=token_data['CharacterID'], character_name=token_data['CharacterName'], character_owner_hash=token_data['CharacterOwnerHash'], access_token=token['access_token'], refresh_token=token['refresh_token'], token_type=token_data['TokenType'], user=user, ) # parse scopes if 'Scopes' in token_data: from esi.models import Scope for s in token_data['Scopes'].split(): try: scope = Scope.objects.get(name=s) model.scopes.add(scope) except Scope.DoesNotExist: # This scope isn't included in a data migration. Create a placeholder until it updates. try: help_text = s.split('.')[1].replace('_', ' ').capitalize() except IndexError: # Unusual scope name, missing periods. help_text = s.replace('_', ' ').capitalize() scope = Scope.objects.create(name=s, help_text=help_text) model.scopes.add(scope) logger.debug("Added {0} scopes to new token.".format(model.scopes.all().count())) if not app_settings.ESI_ALWAYS_CREATE_TOKEN: # see if we already have a token for this character and scope combination # if so, we don't need a new one queryset = self.get_queryset().equivalent_to(model) if queryset.exists(): logger.debug( "Identified {0} tokens equivalent to new token. Updating access and refresh tokens.".format( queryset.count())) queryset.update( access_token=model.access_token, refresh_token=model.refresh_token, created=model.created, ) if queryset.filter(user=model.user).exists(): logger.debug("Equivalent token with same user exists. Deleting new token.") model.delete() model = queryset.filter(user=model.user)[0] # pick one at random logger.debug("Successfully created {0} for user {1}".format(repr(model), user)) return model def create_from_request(self, request): """ Generate a token from the OAuth callback request. Must contain 'code' in GET. :param request: OAuth callback request. :return: :class:`esi.models.Token` """ logger.debug("Creating new token for {0} session {1}".format(request.user, request.session.session_key[:5])) code = request.GET.get('code') # attach a user during creation for some functionality in a post_save created receiver I'm working on elsewhere model = self.create_from_code(code, user=request.user if request.user.is_authenticated else None) return model
class TokenManager(models.Manager): def get_queryset(self): ''' Replace base queryset model with custom TokenQueryset :rtype: :class:`esi.managers.TokenQueryset` ''' pass def create_from_code(self, code, user=None): ''' Perform OAuth code exchange to retrieve a token. :param code: OAuth grant code. :param user: User who will own token. :return: :class:`esi.models.Token` ''' pass def create_from_request(self, request): ''' Generate a token from the OAuth callback request. Must contain 'code' in GET. :param request: OAuth callback request. :return: :class:`esi.models.Token` ''' pass
4
3
28
2
19
8
4
0.42
1
3
2
0
3
1
3
3
87
7
57
17
52
24
42
16
37
8
1
4
11
3,027
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/migrations/0003_hide_tokens_from_admin_site.py
esi.migrations.0003_hide_tokens_from_admin_site.Migration
class Migration(migrations.Migration): dependencies = [ ('esi', '0002_scopes_20161208'), ] operations = [ migrations.AlterField( model_name='token', name='access_token', field=models.CharField(editable=False, help_text='The access token granted by SSO.', max_length=254, unique=True), ), migrations.AlterField( model_name='token', name='refresh_token', field=models.CharField(blank=True, editable=False, help_text='A re-usable token to generate new access tokens upon expiry.', max_length=254, null=True), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
18
2
16
3
15
0
3
3
2
0
1
0
0
3,028
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/errors.py
esi.errors.NotRefreshableTokenError
class NotRefreshableTokenError(TokenError): pass
class NotRefreshableTokenError(TokenError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
4
0
0
3,029
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/managers.py
esi.managers.TokenQueryset
class TokenQueryset(models.QuerySet): def get_expired(self): """ Get all tokens which have expired. :return: All expired tokens. :rtype: :class:`esi.managers.TokenQueryset` """ max_age = timezone.now() - timedelta(seconds=app_settings.ESI_TOKEN_VALID_DURATION) return self.filter(created__lte=max_age) def bulk_refresh(self): """ Refreshes all refreshable tokens in the queryset. Deletes any tokens which fail to refresh. Deletes any tokens which are expired and cannot refresh. Excludes tokens for which the refresh was incomplete for other reasons. """ session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID) auth = requests.auth.HTTPBasicAuth(app_settings.ESI_SSO_CLIENT_ID, app_settings.ESI_SSO_CLIENT_SECRET) incomplete = [] for model in self.filter(refresh_token__isnull=False): try: model.refresh(session=session, auth=auth) logging.debug("Successfully refreshed {0}".format(repr(model))) except TokenError: logger.info("Refresh failed for {0}. Deleting.".format(repr(model))) model.delete() except IncompleteResponseError: incomplete.append(model.pk) self.filter(refresh_token__isnull=True).get_expired().delete() return self.exclude(pk__in=incomplete) def require_valid(self): """ Ensures all tokens are still valid. If expired, attempts to refresh. Deletes those which fail to refresh or cannot be refreshed. :return: All tokens which are still valid. :rtype: :class:`esi.managers.TokenQueryset` """ expired = self.get_expired() valid = self.exclude(pk__in=expired) valid_expired = expired.bulk_refresh() return valid_expired | valid def require_scopes(self, scope_string): """ :param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with all requested scopes. :rtype: :class:`esi.managers.TokenQueryset` """ scopes = _process_scopes(scope_string) if not scopes: # asking for tokens with no scopes return self.filter(scopes__isnull=True) from .models import Scope scope_pks = Scope.objects.filter(name__in=scopes).values_list('pk', flat=True) if not len(scopes) == len(scope_pks): # there's a scope we don't recognize, so we can't have any tokens for it return self.none() tokens = self.all() for pk in scope_pks: tokens = tokens.filter(scopes__pk=pk) return tokens def require_scopes_exact(self, scope_string): """ :param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with only the requested scopes. :rtype: :class:`esi.managers.TokenQueryset` """ num_scopes = len(_process_scopes(scope_string)) pks = [v['pk'] for v in self.annotate(models.Count('scopes')).require_scopes(scope_string).filter( scopes__count=num_scopes).values('pk', 'scopes__id')] return self.filter(pk__in=pks) def equivalent_to(self, token): """ Gets all tokens which match the character and scopes of a reference token :param token: :class:`esi.models.Token` :return: :class:`esi.managers.TokenQueryset` """ return self.filter(character_id=token.character_id).require_scopes_exact(token.scopes.all()).filter( models.Q(user=token.user) | models.Q(user__isnull=True)).exclude(pk=token.pk)
class TokenQueryset(models.QuerySet): def get_expired(self): ''' Get all tokens which have expired. :return: All expired tokens. :rtype: :class:`esi.managers.TokenQueryset` ''' pass def bulk_refresh(self): ''' Refreshes all refreshable tokens in the queryset. Deletes any tokens which fail to refresh. Deletes any tokens which are expired and cannot refresh. Excludes tokens for which the refresh was incomplete for other reasons. ''' pass def require_valid(self): ''' Ensures all tokens are still valid. If expired, attempts to refresh. Deletes those which fail to refresh or cannot be refreshed. :return: All tokens which are still valid. :rtype: :class:`esi.managers.TokenQueryset` ''' pass def require_scopes(self, scope_string): ''' :param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with all requested scopes. :rtype: :class:`esi.managers.TokenQueryset` ''' pass def require_scopes_exact(self, scope_string): ''' :param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with only the requested scopes. :rtype: :class:`esi.managers.TokenQueryset` ''' pass def equivalent_to(self, token): ''' Gets all tokens which match the character and scopes of a reference token :param token: :class:`esi.models.Token` :return: :class:`esi.managers.TokenQueryset` ''' pass
7
6
13
0
7
6
2
0.82
1
4
3
0
6
0
6
6
85
5
44
22
36
36
42
22
34
4
1
2
12
3,030
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/migrations/0004_remove_unique_access_token.py
esi.migrations.0004_remove_unique_access_token.Migration
class Migration(migrations.Migration): dependencies = [ ('esi', '0003_hide_tokens_from_admin_site'), ] operations = [ migrations.AlterField( model_name='token', name='access_token', field=models.CharField(editable=False, help_text='The access token granted by SSO.', max_length=254), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
13
2
11
3
10
0
3
3
2
0
1
0
0
3,031
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/clients.py
esi.clients.CachingHttpFuture
class CachingHttpFuture(HttpFuture): """ Used to add caching to certain HTTP requests according to "Expires" header """ def __init__(self, *args, **kwargs): super(CachingHttpFuture, self).__init__(*args, **kwargs) self.cache_key = self._build_cache_key(self.future.request) @staticmethod def _build_cache_key(request): """ Generated the key name used to cache responses :param request: request used to retrieve API response :return: formatted cache name """ str_hash = md5( (request.method + request.url + str(request.params) + str(request.data) + str(request.json)).encode( 'utf-8')).hexdigest() return 'esi_%s' % str_hash @staticmethod def _time_to_expiry(expires): """ Determines the seconds until a HTTP header "Expires" timestamp :param expires: HTTP response "Expires" header :return: seconds until "Expires" time """ try: expires_dt = datetime.strptime(str(expires), '%a, %d %b %Y %H:%M:%S %Z') delta = expires_dt - datetime.utcnow() return delta.seconds except ValueError: return 0 def result(self, **kwargs): if app_settings.ESI_CACHE_RESPONSE and self.future.request.method == 'GET' and self.operation is not None: """ Only cache if all are true: - settings dictate caching - it's a http get request - it's to a swagger api endpoint """ cached = cache.get(self.cache_key) if cached: result, response = cached else: _also_return_response = self.also_return_response # preserve original value self.also_return_response = True # override to always get the raw response for expiry header result, response = super(CachingHttpFuture, self).result(**kwargs) self.also_return_response = _also_return_response # restore original value if 'Expires' in response.headers: expires = self._time_to_expiry(response.headers['Expires']) if expires > 0: cache.set(self.cache_key, (result, response), expires) if self.also_return_response: return result, response else: return result else: return super(CachingHttpFuture, self).result(**kwargs)
class CachingHttpFuture(HttpFuture): ''' Used to add caching to certain HTTP requests according to "Expires" header ''' def __init__(self, *args, **kwargs): pass @staticmethod def _build_cache_key(request): ''' Generated the key name used to cache responses :param request: request used to retrieve API response :return: formatted cache name ''' pass @staticmethod def _time_to_expiry(expires): ''' Determines the seconds until a HTTP header "Expires" timestamp :param expires: HTTP response "Expires" header :return: seconds until "Expires" time ''' pass def result(self, **kwargs): pass
7
3
13
1
9
5
3
0.58
1
5
0
0
2
2
4
4
62
5
38
16
31
22
31
14
26
6
1
4
10
3,032
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/models.py
esi.models.CallbackRedirect
class CallbackRedirect(models.Model): """ Records the intended destination for the SSO callback. Used to internally redirect SSO callbacks. """ url = models.CharField(max_length=254, default='/', help_text="The internal URL to redirect this callback towards.") session_key = models.CharField(max_length=254, unique=True, help_text="Session key identifying the session this redirect was created for.") state = models.CharField(max_length=128, help_text="OAuth2 state string representing this session.") created = models.DateTimeField(auto_now_add=True) token = models.ForeignKey(Token, on_delete=models.CASCADE, blank=True, null=True, help_text="Token generated by a completed code exchange from callback processing.") def __str__(self): return "%s: %s" % (self.session_key, self.url) def __repr__(self): return "<{}(id={}): {} to {}>".format(self.__class__.__name__, self.pk, self.session_key, self.url)
class CallbackRedirect(models.Model): ''' Records the intended destination for the SSO callback. Used to internally redirect SSO callbacks. ''' def __str__(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.33
1
0
0
0
2
0
2
2
18
2
12
8
9
4
10
8
7
1
1
0
2
3,033
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/models.py
esi.models.Scope
class Scope(models.Model): """ Represents an access scope granted by SSO. """ name = models.CharField(max_length=100, unique=True, help_text="The official EVE name for the scope.") help_text = models.TextField(help_text="The official EVE description of the scope.") @property def friendly_name(self): try: return re.sub('_', ' ', self.name.split('.')[1]).strip() except IndexError: return self.name def __str__(self): return self.name
class Scope(models.Model): ''' Represents an access scope granted by SSO. ''' @property def friendly_name(self): pass def __str__(self): pass
4
1
4
0
4
0
2
0.27
1
1
0
0
2
0
2
2
16
2
11
6
7
3
10
5
7
2
1
1
3
3,034
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/models.py
esi.models.Token
class Token(models.Model): """ EVE Swagger Interface Access Token Contains information about the authenticating character and scopes granted to this token. Contains the access token required for ESI authentication as well as refreshing. """ created = models.DateTimeField(auto_now_add=True) access_token = models.TextField(help_text="The access token granted by SSO.", editable=False) refresh_token = models.TextField(blank=True, default='', help_text="A re-usable token to generate new access tokens upon expiry.", editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, help_text="The user to whom this token belongs.") character_id = models.IntegerField(help_text="The ID of the EVE character who authenticated by SSO.") character_name = models.CharField(max_length=100, help_text="The name of the EVE character who authenticated by SSO.") token_type = models.CharField(max_length=100, choices=(('Character', 'Character'), ('Corporation', 'Corporation'),), default='Character', help_text="The applicable range of the token.") character_owner_hash = models.CharField(max_length=254, help_text="The unique string identifying this character and its owning EVE " "account. Changes if the owning account changes.") scopes = models.ManyToManyField(Scope, blank=True, help_text="The access scopes granted by this token.") objects = TokenManager() def __str__(self): return "%s - %s" % (self.character_name, ", ".join(sorted(s.name for s in self.scopes.all()))) def __repr__(self): return "<{}(id={}): {}, {}>".format( self.__class__.__name__, self.pk, self.character_id, self.character_name, ) @property def can_refresh(self): """ Determines if this token can be refreshed upon expiry """ return bool(self.refresh_token) @property def expires(self): """ Determines when the token expires. """ return self.created + datetime.timedelta(seconds=app_settings.ESI_TOKEN_VALID_DURATION) @property def expired(self): """ Determines if the access token has expired. """ return self.expires < timezone.now() def refresh(self, session=None, auth=None): """ Refreshes the token. :param session: :class:`requests_oauthlib.OAuth2Session` for refreshing token with. :param auth: :class:`requests.auth.HTTPBasicAuth` """ logger.debug("Attempting refresh of {0}".format(repr(self))) if self.can_refresh: if not session: session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID) if not auth: auth = HTTPBasicAuth(app_settings.ESI_SSO_CLIENT_ID, app_settings.ESI_SSO_CLIENT_SECRET) try: token = session.refresh_token(app_settings.ESI_TOKEN_URL, refresh_token=self.refresh_token, auth=auth) logger.debug("Retrieved new token from SSO servers.") self.access_token = token['access_token'] self.refresh_token = token['refresh_token'] self.created = timezone.now() self.save() logger.debug("Successfully refreshed {0}".format(repr(self))) except (InvalidGrantError, InvalidTokenError, InvalidClientIdError) as e: logger.info("Refresh failed for {0}: {1}".format(repr(self), e)) raise TokenInvalidError() except MissingTokenError as e: logger.info("Refresh failed for {0}: {1}".format(repr(self), e)) raise IncompleteResponseError() except InvalidClientError: logger.debug("ESI client ID and secret rejected by remote. Cannot refresh.") raise ImproperlyConfigured('Verify ESI_SSO_CLIENT_ID and ESI_SSO_CLIENT_SECRET settings.') else: logger.debug("Not a refreshable token.") raise NotRefreshableTokenError() def get_esi_client(self, **kwargs): """ Creates an authenticated ESI client with this token. :param kwargs: Extra spec versioning as per `esi.clients.esi_client_factory` :return: :class:`bravado.client.SwaggerClient` """ return esi_client_factory(token=self, **kwargs) @classmethod def get_token_data(cls, access_token): session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, token={'access_token': access_token}) return session.request('get', app_settings.ESI_TOKEN_VERIFY_URL).json() def update_token_data(self, commit=True): logger.debug("Updating token data for {0}".format(repr(self))) if self.expired: if self.can_refresh: self.refresh() else: raise TokenExpiredError() token_data = self.get_token_data(self.access_token) logger.debug(token_data) self.character_id = token_data['CharacterID'] self.character_name = token_data['CharacterName'] self.character_owner_hash = token_data['CharacterOwnerHash'] self.token_type = token_data['TokenType'] logger.debug("Successfully updated token data.") if commit: self.save()
class Token(models.Model): ''' EVE Swagger Interface Access Token Contains information about the authenticating character and scopes granted to this token. Contains the access token required for ESI authentication as well as refreshing. ''' def __str__(self): pass def __repr__(self): pass @property def can_refresh(self): ''' Determines if this token can be refreshed upon expiry ''' pass @property def expires(self): ''' Determines when the token expires. ''' pass @property def expired(self): ''' Determines if the access token has expired. ''' pass def refresh(self, session=None, auth=None): ''' Refreshes the token. :param session: :class:`requests_oauthlib.OAuth2Session` for refreshing token with. :param auth: :class:`requests.auth.HTTPBasicAuth` ''' pass def get_esi_client(self, **kwargs): ''' Creates an authenticated ESI client with this token. :param kwargs: Extra spec versioning as per `esi.clients.esi_client_factory` :return: :class:`bravado.client.SwaggerClient` ''' pass @classmethod def get_token_data(cls, access_token): pass def update_token_data(self, commit=True): pass
14
6
9
0
7
2
2
0.28
1
7
4
0
8
0
9
9
121
11
86
28
72
24
67
23
57
7
1
2
18
3,035
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/apps.py
esi.apps.EsiConfig
class EsiConfig(AppConfig): name = 'esi' verbose_name = 'EVE Swagger Interface' def ready(self): super(EsiConfig, self).ready() from esi import checks
class EsiConfig(AppConfig): def ready(self): pass
2
0
3
0
3
0
1
0
1
1
0
0
1
0
1
1
7
1
6
5
3
0
6
5
3
1
1
0
1
3,036
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/admin.py
esi.admin.TokenAdmin
class TokenAdmin(admin.ModelAdmin): def get_scopes(self, obj): return ", ".join([x.name for x in obj.scopes.all()]) get_scopes.short_description = 'Scopes' User = get_user_model() list_display = ('user', 'character_name', 'get_scopes') search_fields = ['user__%s' % User.USERNAME_FIELD, 'character_name', 'scopes__name']
class TokenAdmin(admin.ModelAdmin): def get_scopes(self, obj): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
9
2
7
5
5
0
7
5
5
1
1
0
1
3,037
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/clients.py
esi.clients.TokenAuthenticator
class TokenAuthenticator(requests_client.Authenticator): """ Adds the authorization header containing access token, if specified. Sets ESI datasource to tranquility or singularity. """ def __init__(self, token=None, datasource=None): host = urlparse.urlsplit(app_settings.ESI_API_URL).hostname super(TokenAuthenticator, self).__init__(host) self.token = token self.datasource = datasource def apply(self, request): if self.token and self.token.expired: if self.token.can_refresh: self.token.refresh() else: raise TokenExpiredError() request.headers['Authorization'] = 'Bearer ' + self.token.access_token if self.token else None request.params['datasource'] = self.datasource or app_settings.ESI_API_DATASOURCE return request
class TokenAuthenticator(requests_client.Authenticator): ''' Adds the authorization header containing access token, if specified. Sets ESI datasource to tranquility or singularity. ''' def __init__(self, token=None, datasource=None): pass def apply(self, request): pass
3
1
7
0
7
0
3
0.27
1
2
1
0
2
2
2
2
21
2
15
6
12
4
14
6
11
4
1
2
5
3,038
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/admin.py
esi.admin.ScopeAdmin
class ScopeAdmin(admin.ModelAdmin): list_display = ('name', 'help_text')
class ScopeAdmin(admin.ModelAdmin): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
3,039
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/migrations/0005_remove_token_length_limit.py
esi.migrations.0005_remove_token_length_limit.Migration
class Migration(migrations.Migration): dependencies = [ ('esi', '0004_remove_unique_access_token'), ] operations = [ migrations.AlterField( model_name='token', name='access_token', field=models.TextField(editable=False, help_text='The access token granted by SSO.'), ), migrations.AlterField( model_name='token', name='refresh_token', field=models.TextField(blank=True, default='', editable=False, help_text='A re-usable token to generate new access tokens upon expiry.'), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
18
2
16
3
15
0
3
3
2
0
1
0
0
3,040
Adarnof/adarnauth-esi
Adarnof_adarnauth-esi/esi/errors.py
esi.errors.IncompleteResponseError
class IncompleteResponseError(Exception): pass
class IncompleteResponseError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
3,041
Addvilz/hemp
Addvilz_hemp/hemp/internal/utils.py
hemp.internal.utils.SimpleProgressPrinter
class SimpleProgressPrinter(RemoteProgress): def _parse_progress_line(self, line): if '\r' in line: line = line.replace('\r', '\r[GIT] ') sys.stdout.write('[GIT] ' + line + '\n') sys.stdout.flush()
class SimpleProgressPrinter(RemoteProgress): def _parse_progress_line(self, line): pass
2
0
5
0
5
0
2
0
1
0
0
0
1
0
1
1
6
0
6
2
4
0
6
2
4
2
1
1
2
3,042
Adman/pynameday
Adman_pynameday/pynameday/czechrepublic.py
pynameday.czechrepublic.CzechRepublic
class CzechRepublic(NamedayMixin): """Czech namedays""" NAMEDAYS = ( # january (None, 'Karina', 'Radmila', 'Diana', 'Dalimil', None, 'Vilma', 'Čestmir', 'Vladan', 'Břetislav', 'Bohdana', 'Pravoslav', 'Edita', 'Radovan', 'Alice', 'Ctirad', 'Drahoslav', 'Vladislav', 'Doubravka', 'Ilona', 'Běla', 'Slavomir', 'Zdeněk', 'Milena', 'Miloš', 'Zora', 'Ingrid', 'Otýlie', 'Zdislava', 'Robin', 'Marika'), # february ('Hynek', 'Nela', 'Blažej', 'Jarmila', 'Dobromila', 'Vanda', 'Veronika', 'Milada', 'Apolena', 'Mojmir', 'Božena', 'Slavěna', 'Věnceslav', 'Valentýn', 'Jiřina', 'Ljuba', 'Miloslava', 'Gizela', 'Patrik', 'Oldřich', 'Lenka', 'Petr', 'Svatopluk', 'Matěj', 'Liliana', 'Dorota', 'Alexandr', 'Lumir', None), # march ('Bedřich', 'Anežka', 'Kamil', 'Stela', 'Kazimír', 'Miroslav', 'Tomáš', 'Gabriela', 'Františka', 'Viktorie', 'Anděla', 'Řehoř', 'Růžena', 'Matylda, Růt', 'Ida', 'Elena, Herbert', 'Vlastimil', 'Eduard', 'Josef', 'Světlana', 'Radek', 'Leona', 'Ivona', 'Gabriel', 'Marián', 'Emanuel', 'Dita', 'Soňa', 'Taťána', 'Arnošt', 'Kvido'), # april ('Hugo', 'Erika', 'Richard', 'Ivana', 'Miroslava', 'Vendula', 'Heřman, Hermína', 'Ema', 'Dušan', 'Darja', 'Izabela', 'Julius', 'Aleš', 'Vincenc', 'Anastázie', 'Irena', 'Rudolf', 'Valérie', 'Rostislav', 'Marcela', 'Alexandra', 'Evžénie', 'Vojtěch', 'Jiří', 'Marek', 'Oto', 'Jaroslav', 'Vlastislav', 'Robert', 'Blahoslav'), # may (None, 'Zigmund', 'Alexej', 'Květoslav', 'Klaudie', 'Radoslav', 'Stanislav', None, 'Ctibor', 'Blažena', 'Svatava', 'Pankrác', 'Servác', 'Bonifác', 'Žofie', 'Přemysl', 'Aneta', 'Nataša', 'Ivo', 'Zbyšek', 'Monika', 'Emil', 'Vladimír', 'Jana, Vanesa', 'Viola', 'Filip', 'Valdemar', 'Vilém', 'Maxmilián', 'Ferdinand', 'Kamila'), # june ('Laura', 'Jarmil', 'Tamara', 'Dalibor', 'Dobroslav', 'Norbert', 'Iveta, Slavoj', 'Medard', 'Stanislava', 'Gita', 'Bruno', 'Antonie', 'Antonin', 'Roland', 'Vít', 'Zbyněk', 'Adolf', 'Milan', 'Leoš', 'Květa', 'Alois', 'Pavla', 'Zdeňka', 'Jan', 'Ivan', 'Adriana', 'Ladislav', 'Lubomir', 'Petr, Pavel', 'Šárka'), # july ('Jaroslava', 'Patricie', 'Radomir', 'Prokop', 'Cyril, Metoděj', None, 'Bohuslava', 'Nora', 'Drahoslava', 'Libuše, Amálie', 'Olga', 'Bořek', 'Markéta', 'Karolína', 'Jindřich', 'Luboš', 'Martina', 'Drahomira', 'Čeněk', 'Ilja', 'Vítězslav', 'Magdaléna', 'Libor', 'Kristýna', 'Jakub', 'Anna', 'Věroslav', 'Viktor', 'Marta', 'Bořivoj', 'Ignác'), # august ('Oskar', 'Gustav', 'Miluše', 'Dominik', 'Kristián', 'Oldriška', 'Lada', 'Soběslav', 'Roman', 'Vavřinec', 'Zuzana', 'Klára', 'Alena', 'Alan', 'Hana', 'Jáchym', 'Petra', 'Helena', 'Ludvík', 'Bernard', 'Johana', 'Bohuslav', 'Sandra', 'Bartoloměj', 'Radim', 'Luděk', 'Otakar', 'Augustýn', 'Evelína', 'Vladěna', 'Pavlína'), # september ('Linda, Samuel', 'Adéla', 'Bronislav', 'Jindřiška', 'Boris', 'Boleslav', 'Regína', 'Mariana', 'Daniela', 'Irma', 'Denisa, Denis', 'Marie', 'Lubor', 'Radka', 'Jolana', 'Ludmila', 'Naděžda', 'Kryštof', 'Zita', 'Oleg', 'Matouš', 'Darina', 'Berta', 'Jaromír', 'Zlata', 'Andrea', 'Jonáš', 'Václav', 'Michal', 'Jeroným'), # october ('Igor', 'Olívie, Oliver', 'Bohumil', 'František', 'Eliška', 'Hanuš', 'Justýna', 'Věra', 'Štefan, Sára', 'Marina', 'Andrej', 'Marcel', 'Renáta', 'Agáta', 'Tereza', 'Havel', 'Hedvika', 'Lukáš', 'Michaela', 'Vendelin', 'Brigita', 'Sabina', 'Teodora', 'Nina', 'Beáta', 'Erik', 'Šarlota', None, 'Silvie', 'Tadeáš', 'Štěpánka'), # november ('Felix', None, 'Hubert', 'Karel', 'Miriam', 'Liběna', 'Saskia', 'Bohumir', 'Bohdan', 'Evžen', 'Martin', 'Benedikt', 'Tibor', 'Sáva', 'Leopold', 'Otmar, Maulena', 'Mahulena', 'Romana', 'Alžběta', 'Nikol, Nikola', 'Albert', 'Cecílie', 'Klement', 'Emílie', 'Kateřina', 'Artur', 'Xenie', 'René', 'Zina', 'Ondřej'), # december ('Iva', 'Blanka', 'Svatoslav', 'Barbora', 'Jitka', 'Mikuláš', 'Benjamín', 'Květoslava', 'Vratislav', 'Julie', 'Dana', 'Simona', 'Lucie', 'Lýdie', 'Radana', 'Albína', 'Daniel', 'Miloslav', 'Ester', 'Dagmar', 'Natálie', 'Šimon', 'Vlasta', 'Adam, Eva', None, 'Štěpán', 'Žaneta', 'Bohumila', 'Judita', 'David', 'Silvestr'), )
class CzechRepublic(NamedayMixin): '''Czech namedays''' pass
1
1
0
0
0
0
0
0.21
1
0
0
0
0
0
0
2
87
11
63
2
62
13
2
2
1
0
2
0
0
3,043
Adman/pynameday
Adman_pynameday/pynameday/slovakia.py
pynameday.slovakia.Slovakia
class Slovakia(NamedayMixin): """Slovakian namedays""" NAMEDAYS = ( # january (None, 'Alexandra, Karina', 'Daniela', 'Drahoslav', 'Andrea', 'Antónia', 'Bohuslava', 'Severín', 'Alexej', 'Dáša', 'Malvína', 'Ernest', 'Rastislav', 'Radovan', 'Dobroslav', 'Kristína', 'Nataša', 'Bohdana', 'Drahomíra, Mário', 'Dalibor', 'Vincent', 'Zora', 'Miloš', 'Timotej', 'Gejza', 'Tamara', 'Bohuš', 'Alfonz', 'Gašpar', 'Ema', 'Emil'), # february ('Tatiana', 'Erika, Erik', 'Blažej', 'Veronika', 'Agáta', 'Dorota', 'Vanda', 'Zoja', 'Zdenko', 'Gabriela', 'Dezider', 'Perla', 'Arpád', 'Valentín', 'Pravoslav', 'Ida, Liana', 'Miloslava', 'Jaromír', 'Vlasta', 'Lívia', 'Eleonóra', 'Etela', 'Roman, Romana', 'Matej', 'Frederik, Frederika', 'Viktor', 'Alexander', 'Zlatica', 'Radomír'), # march ('Albín', 'Anežka', 'Bohumil, Bohumila', 'Kazimír', 'Fridrich', 'Radoslav, Radoslava', 'Tomáš', 'Alan, Alana', 'Františka', 'Bruno, Branislav', 'Angela, Angelika', 'Gregor', 'Vlastimil', 'Matilda', 'Svetlana', 'Boleslav', 'Ľubica', 'Eduard', 'Jozef', 'Víťazoslav, Klaudius', 'Blahoslav', 'Beňadik', 'Adrián', 'Gabriel', 'Marián', 'Emanuel', 'Alena', 'Soňa', 'Miroslav', 'Vieroslava', 'Benjamín'), # april ('Hugo', 'Zita', 'Richard', 'Izidor', 'Miroslava', 'Irena', 'Zoltán', 'Albert', 'Milena', 'Igor', 'Július', 'Estera', 'Aleš', 'Justina', 'Fedor', 'Dana, Danica', 'Rudolf, Rudolfa', 'Valér', 'Jela', 'Marcel', 'Ervín', 'Slavomír', 'Vojtech', 'Juraj', 'Marek', 'Jaroslava', 'Jaroslav', 'Jarmila', 'Lea', 'Anastázia'), # may (None, 'Žigmund', 'Galina', 'Florián', 'Lesia, Lesana', 'Hermína', 'Monika', 'Ingrida', 'Roland', 'Viktória', 'Blažena', 'Pankrác', 'Servác', 'Bonifác', 'Žofia, Sofia', 'Svetozár', 'Gizela', 'Viola', 'Gertrúda', 'Bernard', 'Zina', 'Júlia, Juliana', 'Želmíra', 'Ela', 'Urban', 'Dušan', 'Iveta', 'Viliam', 'Vilma', 'Ferdinand', 'Petrana, Petronela'), # june ('Žaneta', 'Xénia, Oxana', 'Karolína', 'Lenka', 'Laura', 'Norbert', 'Róbert', 'Medard', 'Stanislava', 'Margaréta', 'Dobroslava', 'Zlatko', 'Anton', 'Vasil', 'Vít', 'Blanka, Bianka', 'Adolf', 'Vratislav', 'Alfréd', 'Valéria', 'Alojz', 'Paulína', 'Sidónia', 'Ján', 'Olívia, Tadeáš', 'Adriána', 'Ladislav, Ladislava', 'Beáta', 'Peter, Pavol, Petra', 'Melánia'), # july ('Diana', 'Berta', 'Miloslav', 'Prokop', 'Cyril, Metod', 'Patrik, Patrícia', 'Oliver', 'Ivan', 'Lujza', 'Amália', 'Milota', 'Nina', 'Margita', 'Kamil', 'Henrich', 'Drahomír, Rút', 'Bohuslav', 'Kamila', 'Dušana', 'Iľja, Eliáš', 'Daniel', 'Magdaléna', 'Oľga', 'Vladimír', 'Jakub, Timur', 'Anna, Hana, Anita', 'Božena', 'Krištof', 'Marta', 'Libuša', 'Ignác'), # august ('Božidara', 'Gustáv', 'Jerguš', 'Dominika, Dominik', 'Hortenzia', 'Jozefína', 'Štefánia', 'Oskar', 'Ľubomíra', 'Vavrinec', 'Zuzana', 'Darina', 'Ľubomír', 'Mojmír', 'Marcela', 'Leonard', 'Milica', 'Elena, Helena', 'Lýdia', 'Anabela, Liliana', 'Jana', 'Tichomír', 'Filip', 'Bartolomej', 'Ľudovít', 'Samuel', 'Silvia', 'Augustín', 'Nikola, Nikolaj', 'Ružena', 'Nora'), # september ('Drahoslava', 'Linda, Rebeka', 'Belo', 'Rozália', 'Regina', 'Alica', 'Marianna', 'Miriama', 'Martina', 'Oleg', 'Bystrík', 'Mária, Marlena', 'Ctibor', 'Ľudomil', 'Jolana', 'Ľudmila', 'Olympia', 'Eugénia', 'Konštantín', 'Ľuboslav, Ľuboslava', 'Matúš', 'Móric', 'Zdenka', 'Ľuboš, Ľubor', 'Vladislav, Vladislava', 'Edita', 'Cyprián', 'Václav', 'Michal, Michaela', 'Jarolím'), # october ('Arnold', 'Levoslav', 'Stela', 'František', 'Viera', 'Natália', 'Eliška', 'Brigita', 'Dionýz', 'Slavomíra', 'Valentína', 'Maximilián', 'Koloman', 'Boris', 'Terézia', 'Vladimíra', 'Hedviga', 'Lukáš', 'Kristián', 'Vendelín', 'Uršuľa', 'Sergej', 'Alojzia', 'Kvetoslava', 'Aurel', 'Demeter', 'Sabína', 'Dobromila', 'Klára', 'Šimon, Simona', 'Aurélia'), # november ('Denis, Denisa', None, 'Hubert', 'Karol', 'Imrich', 'Renáta', 'René', 'Bohumír', 'Teodor', 'Tibor', 'Martin, Maroš', 'Svätopluk', 'Stanislav', 'Irma', 'Leopold', 'Agnesa', 'Klaudia', 'Eugen', 'Alžbeta', 'Félix', 'Elvíra', 'Cecília', 'Klement', 'Emília', 'Katarína', 'Kornel', 'Milan', 'Henrieta', 'Vratko', 'Ondrej, Andrej'), # december ('Edmund', 'Bibiána', 'Oldrich', 'Barbora, Barbara', 'Oto', 'Mikuláš', 'Ambróz', 'Marína', 'Izabela', 'Radúz', 'Hilda', 'Otília', 'Lucia', 'Branislava, Bronislava', 'Ivica', 'Albína', 'Kornélia', 'Sláva', 'Judita', 'Dagmara', 'Bohdan', 'Adela', 'Nadežda', 'Adam, Eva', None, 'Štefan', 'Filoména', 'Ivana, Ivona', 'Milada', 'Dávid', 'Silvester'), )
class Slovakia(NamedayMixin): '''Slovakian namedays''' pass
1
1
0
0
0
0
0
0.18
1
0
0
0
0
0
0
2
97
11
73
2
72
13
2
2
1
0
2
0
0
3,044
Adman/pynameday
Adman_pynameday/pynameday/tests/tests.py
tests.AustriaTest
class AustriaTest(TestCase, NamedayMixinTest): """Austrian nameday test""" def setUp(self): self.cal = Austria.NAMEDAYS
class AustriaTest(TestCase, NamedayMixinTest): '''Austrian nameday test''' def setUp(self): pass
2
1
2
0
2
0
1
0.33
2
1
1
0
1
1
1
75
4
0
3
3
1
1
3
3
1
1
2
0
1
3,045
Adman/pynameday
Adman_pynameday/pynameday/tests/tests.py
tests.CzechRepublicTest
class CzechRepublicTest(TestCase, NamedayMixinTest): """Czech nameday test""" def setUp(self): self.cal = CzechRepublic.NAMEDAYS
class CzechRepublicTest(TestCase, NamedayMixinTest): '''Czech nameday test''' def setUp(self): pass
2
1
2
0
2
0
1
0.33
2
1
1
0
1
1
1
75
4
0
3
3
1
1
3
3
1
1
2
0
1
3,046
Adman/pynameday
Adman_pynameday/pynameday/austria.py
pynameday.austria.Austria
class Austria(NamedayMixin): """Austrian namedays""" NAMEDAYS = ( # january ('Neujahr', 'Basilius', 'Genoveva', 'Angela', 'Emilie', 'Heilige 3 Könige', 'Raimund v. P.', 'Severin, Erhard', 'Julian, Eberhard', 'Gregor X.', 'Taufe Jesu', 'Ernst', 'Jutta, Gottfried', 'Felix v. N.', 'Gabriel v. F.', 'Theobald', 'Antonius', 'Regina', 'Marius, Mario', 'Fabian, Sebastian', 'Agnes', 'Vinzenz, Walter', 'Heinrich S.', 'Franz v. S.', 'Pauli Bekehrung', 'Timotheus, Titus', 'Angela M.', 'Thomas v. A.', 'Valerius', 'Martina', 'Johannes Bosco'), # february ('Brigitta v. K.', 'Mariä Lichtmess', 'Blasius', 'Andreas C.', 'Agatha', 'Dorothea', 'Richard K.', 'Hieronymus', 'Apollonia, Erich', 'Wilhelm d. Gr.', 'Theodor', 'Reginald', 'Gerlinde', 'Valentin', 'Siegfried', 'Philippa', 'Alexius', 'Konstantia', 'Bonifatius', 'Leo d. W.', 'Petrus Dam.', 'Petri Stuhlfeier', 'Romana', 'Mathias', 'Walpurga', 'Alexander', 'Leander, Gabriel', 'Roman', None), # march ('Albin, Rüdiger', 'Karl, Agnes', 'Friedrich', 'Kasimir', 'Gerda, Diemar', 'Coletta, Fridolin', 'Reinhard', 'Johannes v. G.', 'Franziska v. R.', 'Emil, Gustav', 'Theresia R.', 'Maximilian', 'Gerald, Paulina', 'Mathilde', 'Klemens M. H.', 'Hilarius v. A.', 'Getrud', 'Eduard', 'Josev, Nährv. Jesu', 'Claudia, Irmgard', 'Alexandra', 'Lea, Elmar', 'Otto v. A.', 'Katharina v. Schw.', 'Verkündung des Herrn', 'Emmanuel', 'Frowin, Haimo', 'Johanna v. M.', 'Berthold v. K.', 'Amadeus v. S.', 'Cornelia'), # april ('Hugo, Irene', 'Sandra', 'Richard', 'Isidor', 'Vinzenz Ferr.', 'Sixtus I. Cölestin', 'Johann Bapt. de la Salle', 'Walter, Beate', 'Waltraud', 'Engelbert v. A.', 'Stanislaus', 'Julius, Hertha', 'Martin I., Ida v B.', 'Tiburtius', 'Waltmann', 'Bernadette', 'Eberhard', 'Aja Apollonius', 'Leo IX., Gerold', 'Simon v. T.', 'Konrad v. P., Anselm', 'Wolfhelm', 'Georg, Gerhard', 'Wilfried', 'Markus, Erwin, Ev.', 'Trudpert', 'Petrus Can.', 'Ludwig v. M.', 'Roswitha', 'Hildegard'), # may (None, 'Athanasius, Boris', 'Philipp, Jakob', 'Florian', 'Gotthard', 'Valerian', 'Gisela', 'Ida, Désiré', 'Volkmar', 'Antonin', 'Gangolf', 'Pankratius', 'Servatius', 'Bonifatius', 'Rupert, Sophie', 'Johannes', 'Walter, Pascal', 'Erich', 'Cölestin V., Ivo', 'Elfriede', 'Hermann, Josef', 'Rita, Julia', 'Renate', 'Vinzenz, Dagmar', 'Gregor VII.', 'Philip N.', 'Augustin v. C.', 'Wilhelm', 'Maximin', 'Ferdinand', 'Petronilla, Aldo'), # june ('Konrad, Silke', 'Armin, Eugen', 'Karl L., Silvia', 'Franz C., Klothilde', 'Bonifaz', 'Norbert', 'Robert', 'Medardus, Ilga', 'Ephräm, Gratia', 'Heinrich v. B., Diana', 'Barnabas, Alice', 'Leo III., Johann v. S. F.', 'Antonius v. P.', 'Burkhard, Gottschalk', 'Vitus, Veit', 'Benno v. M.', 'Rainer, Adolf v. M.', 'Markus, Marcellianus', 'Juliana v. F.', 'Adalbert, Florentina', 'Aloisius v. G.', 'Thomas M.', 'Edeltraud', 'Johannes der Täufer', 'Dorothea, Eleonore', 'Johann, Paul', 'Cyrill v. A., Harald', 'Irenäus, Diethild', 'Peter, Paul Judith', 'Otto, Ernst v. P.'), # july ('Theobald', 'Mariä, Heimsuchung', 'Thomas, Raimund', 'Elisabeth v. P.', 'Anton M. Zacc.', 'Maria Goretti', 'Willibald', 'Eugen III., Edgar K.', 'Gottfried, Veronika', 'Knud, Engelbert', 'Benedikt v. N., Oliver', 'Nabor, Felix', 'Heinrich II.', 'Roland', 'Egon, Balduin', 'Maria v. B. K., Carmen', 'Alexius', 'Friedrich, Arnold', 'Justa, Bernulf', 'Margareta', 'Daniel', 'Maria Magdalena', 'Brigitta', 'Christophorus', 'Jakob, Thea, Ap.', 'Anna, Joachim', 'Rudolf A.', 'Samuel, Viktor', 'Martha, Lucilla', 'Ingeborg', 'Ignatius v. L.'), # august ('Alfons v. L.', 'Eusebius v. V., Stefan', 'Lydia, Benno v. E.', 'Johannes M. V., Rainer', 'Oswald, Dominika', 'Christi Verklärung', 'Albert', 'Dominikus, Gustav', 'Edith', 'Laurentius, Astrid', 'Klara, Susanna', 'Hilaria', 'Gertrud v. A., Marco', 'Maximilian', 'Mariä Himmelfahrt', 'Stefan v. U., Theodor', 'Hyazinth', 'Helene, Claudia', 'Emilia B.', 'Bernhard v. Cl.', 'Pius X.', 'Regina, Siegfried A.', 'Rosa v. L., Philipp B.', 'Isolde, Michaela', 'Ludwig IX., Patricia', 'Margareta v. F.', 'Monika', 'Augustin', 'Sabine, Beatrix v. A.', 'Herbert v. K., Felix', 'Raimund N.'), # september ('Verena, Ruth', 'René, Ingrid', 'Gregor d. Gr.', 'Rosalia, Ida', 'Laurentius, Albert', 'Magnus, Beata', 'Regina, Ralph', 'Mariä Geburt', 'Grogonius', 'Nikolaus v. T., Diethard', 'Helga', 'Eberhard, Guido', 'Tobias', 'Kreuz-Erhöhung', 'Dolores, Melitta', 'Ludmilla, Edith', 'Robert B., Lambert', 'Josef v. C.', 'Wilma, Arnulf', 'Fausta, Candida', 'Matthäus', 'Moritz', 'Helene D., Thekla', 'Rupert v. S.', 'Nikolaus v. Fl.', 'Eugenia', 'Vinzenz v. P.', 'Wenzel v. B., Dietmar', 'Michael, Gabriel', 'Hieronymus'), # october ('Theresia v. K. J.', 'Schutzengelfest', 'Ewald, Udo', 'Franz v. Assisi, Edwin', 'Attila, Placidus', 'Bruno d. Karth.', 'Markus I.', 'Simeon', 'Dionysius', 'Viktor v. X.', 'Bruno v. K.', 'Maximilian, Horst', 'Eduard', 'Burkhard', 'Theresia v. A.', 'Hedwig', 'Ignatuis v. A., Rudolf', 'Lukas', 'Paul v. Kr., Frieda', 'Wendelin', 'Ursula', 'Kordula', 'Oda', 'Anton M. Cl.', 'Krispin', 'Nationalfeiertag', 'Wolfhard', 'Simon, Judas, Thadd.', 'Hermelindis', 'Alfons Rodr.', 'Wolfgang, Christoph'), # november ('Allerheiligen', 'Allerseelen', 'Hubert, Silvia', 'Karl Borr.', 'Emmerich', 'Christina d. K.', 'Engelbert', 'Gottfried', 'Theodor', 'Leo d. Gr., Andreas Av.', 'Martin v. T.', 'Emil, Christian', 'Eugen', 'Alberich', 'Leopold von Österreich', 'Othmar, Edmund', 'Gertrud, Hilda', 'Odo, Roman', 'Elisabeth von Th.', 'Edmund K.', 'Gelasius I.', 'Cäcilia', 'Klemens I., Felicitas', 'Chrysogonus, Flora', 'Katharina v. A.', 'Konrad', 'Oda, Modestus', 'Gunther, Stephan d. J.', 'Friedrich v. R.', 'Andreas'), # december ('Blanka, Natalie', 'Bibiana', 'Franz, Xaver', 'Barbara', 'Gerald', 'Nikolaus v. M.', 'Ambrosius', 'Mariä Empfängnis', 'Valerie', 'Diethard', 'David, Daniel', 'Johanna F. v. Ch.', 'Lucia, Ottilie', 'Franziska', 'Christiana, Nina', 'Adelheid', 'Lazarus, Jolanda', 'Gatian', 'Urban V.', 'Eugen v. A.', 'Ingomar', 'Jutta, Marian', 'Victoria', 'Heiliger Abend', 'Christtag', 'Stefanitag', 'Johannes', 'Unschuldige, Kinder', 'Thomas B., Tamara', 'Hermine', 'Silvester'), )
class Austria(NamedayMixin): '''Austrian namedays''' pass
1
1
0
0
0
0
0
0.13
1
0
0
0
0
0
0
2
124
11
100
2
99
13
2
2
1
0
2
0
0
3,047
Adman/pynameday
Adman_pynameday/pynameday/tests/tests.py
tests.SlovakiaTest
class SlovakiaTest(TestCase, NamedayMixinTest): """Slovakian nameday test""" def setUp(self): self.cal = Slovakia.NAMEDAYS
class SlovakiaTest(TestCase, NamedayMixinTest): '''Slovakian nameday test''' def setUp(self): pass
2
1
2
0
2
0
1
0.33
2
1
1
0
1
1
1
75
4
0
3
3
1
1
3
3
1
1
2
0
1
3,048
Adman/pynameday
Adman_pynameday/pynameday/tests/tests.py
tests.NamedayMixinTest
class NamedayMixinTest(object): MONTHS = 12 DAYS = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) cal = None def test_months(self): self.assertEqual(len(self.cal), self.MONTHS) def test_days(self): for i, j in enumerate(self.cal): self.assertEqual(len(j), self.DAYS[i])
class NamedayMixinTest(object): def test_months(self): pass def test_days(self): pass
3
0
3
0
3
0
2
0
1
1
0
3
2
0
2
2
11
2
9
7
6
0
9
7
6
2
1
1
3
3,049
Adman/pynameday
Adman_pynameday/pynameday/core.py
pynameday.core.NamedayMixin
class NamedayMixin(object): NAMEDAYS = () def get_nameday(self, month=None, day=None): """Return name(s) as a string based on given date and month. If no arguments given, use current date""" if month is None: month = datetime.now().month if day is None: day = datetime.now().day return self.NAMEDAYS[month-1][day-1] def get_month_namedays(self, month=None): """Return names as a tuple based on given month. If no month given, use current one""" if month is None: month = datetime.now().month return self.NAMEDAYS[month-1]
class NamedayMixin(object): def get_nameday(self, month=None, day=None): '''Return name(s) as a string based on given date and month. If no arguments given, use current date''' pass def get_month_namedays(self, month=None): '''Return names as a tuple based on given month. If no month given, use current one''' pass
3
2
7
0
5
2
3
0.33
1
1
0
3
2
0
2
2
18
2
12
4
9
4
12
4
9
3
1
1
5
3,050
Adman/python-cpsk-api
Adman_python-cpsk-api/cpsk/enums.py
cpsk.enums.Vehicle
class Vehicle(StrEnum): BUS = "BUS" TRAIN = "TRAIN" TRAM = "TRAM" UNKNOWN = "UNKNOWN" WALK = "WALK"
class Vehicle(StrEnum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
68
6
0
6
6
5
0
6
6
5
0
3
0
0
3,051
Adman/python-cpsk-api
Adman_python-cpsk-api/cpsk/enums.py
cpsk.enums.UsualDeparture
class UsualDeparture(StrEnum): ON_TIME = "ON TIME" DELAYED = "DELAYED"
class UsualDeparture(StrEnum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
68
3
0
3
3
2
0
3
3
2
0
3
0
0
3,052
Adman/python-cpsk-api
Adman_python-cpsk-api/cpsk/line.py
cpsk.line.Line
class Line: def __init__(self): self.f: str = "" self.t: str = "" self.departure: str = "" self.arrival: str = "" self.vehicle: Vehicle | None = None self.vehicle_id: str = "" self.walk_duration: str = "" self.delay_mins: int = 0 self.platform: str = "" self.date: str = "" self.usual_departure: UsualDeparture | None = None def __repr__(self): if self.vehicle == Vehicle.WALK: return f"[WALK] {self.walk_duration}" delay = "" if self.delay_mins: delay = " ({0} {1} delay)".format( self.delay_mins, "mins" if self.delay_mins > 1 else "min" ) platform = f" {self.platform}" if self.platform else "" return "[{0} {1}]{2} {3} {4} -> {5} {6}{7}".format( self.vehicle, self.vehicle_id, platform, self.f, self.departure, self.t, self.arrival, delay, ) def __str__(self): return self.__repr__()
class Line: def __init__(self): pass def __repr__(self): pass def __str__(self): pass
4
0
12
1
11
0
2
0
0
4
2
0
3
11
3
3
39
4
35
17
31
0
23
17
19
5
0
1
7
3,053
Adman/python-cpsk-api
Adman_python-cpsk-api/cpsk/drive.py
cpsk.drive.Drive
class Drive(object): def __init__(self): self.duration: str = "" self.distance: str = "" self.lines = [] def __repr__(self): return "{0} ({1}, {2})".format( " >> ".join(map(str, self.lines)), self.duration, self.distance, ) def __str__(self): return self.__repr__()
class Drive(object): def __init__(self): pass def __repr__(self): pass def __str__(self): pass
4
0
4
0
4
0
1
0
1
2
0
0
3
3
3
3
16
3
13
7
9
0
9
7
5
1
1
0
3
3,054
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.ReadInputRegisters
class ReadInputRegisters(ModbusFunction): """ Implement Modbus function code 04. "This function code is used to read from 1 to 125 contiguous input registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore input registers numbered 1-16 are addressed as 0-15. The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte. For each register, the first byte contains the high order bits and the second contains the low order bits." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.4 The request PDU with function code 04 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x04\\x00d\\x00\\x03') (4, 100, 3) The reponse PDU varies in length, depending on the request. By default, holding registers are 16 bit (2 bytes) values. So values of 3 holding registers is expressed in 2 * 3 = 6 bytes. ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Register values Quantity * 2 ================ =============== Assume the value of 100 is 8, 101 is 0 and 102 is also 15. The PDU can packed like this:: >>> data = [8, 0, 15] >>> struct.pack('>BBHHH', function_code, len(data) * 2, *data) b'\\x04\\x06\\x00\\x08\\x00\\x00\\x00\\x0f' """ function_code = READ_INPUT_REGISTERS max_quantity = 0x007D data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of registers to read. Quantity must be between 1 and 0x00FD. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 0x007D): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(0x007D)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read coils. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = cls() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 2 + self.quantity * 2 def create_response_pdu(self, data): """ Create response pdu. :param data: A list with values. :return: Byte array of at least 4 bytes. """ log.debug('Create multi bit response pdu {0}.'.format(data)) fmt = '>BB' + conf.TYPE_CHAR * len(data) return struct.pack(fmt, self.function_code, len(data) * 2, *data) @classmethod def create_from_response_pdu(cls, resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the number of registers read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoils`. """ read_input_registers = cls() read_input_registers.quantity = struct.unpack('>H', req_pdu[-2:])[0] fmt = '>' + (conf.TYPE_CHAR * read_input_registers.quantity) read_input_registers.data = list(struct.unpack(fmt, resp_pdu[2:])) return read_input_registers def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. :return: Result of call to endpoint. """ values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) if endpoint is None: raise IllegalDataAddressError() values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values
class ReadInputRegisters(ModbusFunction): ''' Implement Modbus function code 04. "This function code is used to read from 1 to 125 contiguous input registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore input registers numbered 1-16 are addressed as 0-15. The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte. For each register, the first byte contains the high order bits and the second contains the low order bits." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.4 The request PDU with function code 04 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
8
11
2
5
4
2
1.43
1
5
2
0
6
0
8
8
171
42
53
28
38
76
42
22
33
3
2
2
12
3,055
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/server/__init__.py
umodbus.server.AbstractRequestHandler
class AbstractRequestHandler(BaseRequestHandler): """ A subclass of :class:`socketserver.BaseRequestHandler` dispatching incoming Modbus requests using the server's :attr:`route_map`. """ def handle(self): try: while True: try: mbap_header = recv_exactly(self.request.recv, 7) remaining = self.get_meta_data(mbap_header)['length'] - 1 request_pdu = recv_exactly(self.request.recv, remaining) except ValueError: return response_adu = self.process(mbap_header + request_pdu) self.respond(response_adu) except: log.exception('Error while handling request') raise def process(self, request_adu): """ Process request ADU and return response. :param request_adu: A bytearray containing the ADU request. :return: A bytearray containing the response of the ADU request. """ meta_data = self.get_meta_data(request_adu) request_pdu = self.get_request_pdu(request_adu) response_pdu = self.execute_route(meta_data, request_pdu) response_adu = self.create_response_adu(meta_data, response_pdu) return response_adu def execute_route(self, meta_data, request_pdu): """ Execute configured route based on requests meta data and request PDU. :param meta_data: A dict with meta data. It must at least contain key 'unit_id'. :param request_pdu: A bytearray containing request PDU. :return: A bytearry containing reponse PDU. """ try: function = create_function_from_request_pdu(request_pdu) results =\ function.execute(meta_data['unit_id'], self.server.route_map) try: # ReadFunction's use results of callbacks to build response # PDU... return function.create_response_pdu(results) except TypeError: # ...other functions don't. return function.create_response_pdu() except ModbusError as e: function_code = get_function_code_from_request_pdu(request_pdu) return pack_exception_pdu(function_code, e.error_code) except Exception: log.exception('Could not handle request') function_code = get_function_code_from_request_pdu(request_pdu) return pack_exception_pdu(function_code, ServerDeviceFailureError.error_code) def respond(self, response_adu): """ Send response ADU back to client. :param response_adu: A bytearray containing the response of an ADU. """ log.debug('--> {0} - {1}.'.format(self.client_address[0], hexlify(response_adu))) self.request.sendall(response_adu)
class AbstractRequestHandler(BaseRequestHandler): ''' A subclass of :class:`socketserver.BaseRequestHandler` dispatching incoming Modbus requests using the server's :attr:`route_map`. ''' def handle(self): pass def process(self, request_adu): ''' Process request ADU and return response. :param request_adu: A bytearray containing the ADU request. :return: A bytearray containing the response of the ADU request. ''' pass def execute_route(self, meta_data, request_pdu): ''' Execute configured route based on requests meta data and request PDU. :param meta_data: A dict with meta data. It must at least contain key 'unit_id'. :param request_pdu: A bytearray containing request PDU. :return: A bytearry containing reponse PDU. ''' pass def respond(self, response_adu): ''' Send response ADU back to client. :param response_adu: A bytearray containing the response of an ADU. ''' pass
5
4
17
2
10
4
3
0.48
1
5
2
1
4
0
4
8
74
12
42
17
37
20
39
16
34
4
1
3
10
3,056
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.IllegalDataAddressError
class IllegalDataAddressError(ModbusError): """ The data address received in the request is not an allowable address for the server. """ error_code = 2 def __str__(self): return self.__doc__
class IllegalDataAddressError(ModbusError): ''' The data address received in the request is not an allowable address for the server. ''' def __str__(self): pass
2
1
2
0
2
0
1
0.75
1
0
0
0
1
0
1
11
8
1
4
3
2
3
4
3
2
1
4
0
1
3,057
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/route.py
umodbus.route.Map
class Map: def __init__(self): self._rules = [] def add_rule(self, endpoint, slave_ids, function_codes, addresses): self._rules.append(DataRule(endpoint, slave_ids, function_codes, addresses)) def match(self, slave_id, function_code, address): for rule in self._rules: if rule.match(slave_id, function_code, address): return rule.endpoint
class Map: def __init__(self): pass def add_rule(self, endpoint, slave_ids, function_codes, addresses): pass def match(self, slave_id, function_code, address): pass
4
0
3
0
3
0
2
0
0
1
1
0
3
1
3
3
12
2
10
6
6
0
9
6
5
3
0
2
5
3,058
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/route.py
umodbus.route.DataRule
class DataRule: def __init__(self, endpoint, slave_ids, function_codes, addresses): self.endpoint = endpoint self.slave_ids = slave_ids self.function_codes = function_codes self.addresses = addresses def match(self, slave_id, function_code, address): # A constraint of None matches any value matches = lambda values, v: values is None or v in values return matches(self.slave_ids, slave_id) and \ matches(self.function_codes, function_code) and \ matches(self.addresses, address)
class DataRule: def __init__(self, endpoint, slave_ids, function_codes, addresses): pass def match(self, slave_id, function_code, address): pass
3
0
6
0
5
1
1
0.09
0
0
0
0
2
4
2
2
13
1
11
8
8
1
9
8
6
1
0
0
2
3,059
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.WriteSingleRegister
class WriteSingleRegister(ModbusFunction): """ Implement Modbus function code 06. "This function code is used to write a single holding register in a remote device. The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. Therefore register numbered 1 is addressed as 0. The normal response is an echo of the request, returned after the register contents have been written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.6 The request PDU with function code 06 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x06\\x00d\\x00\\x03') (6, 100, 3) The reponse PDU is a copy of the request PDU. ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== """ function_code = WRITE_SINGLE_REGISTER address = None data = None _value = None @property def value(self): return self._value @value.setter def value(self, value): """ Value to be written on register. :param value: An integer. :raises: IllegalDataValueError when value isn't in range. """ try: struct.pack('>' + conf.TYPE_CHAR, value) except struct.error: raise IllegalDataValueError self._value = value @property def request_pdu(self): """ Build request PDU to write single register. :return: Byte array of 5 bytes with PDU. """ if None in [self.address, self.value]: # TODO Raise proper exception. raise Exception return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code, self.address, self.value) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, address, value = \ struct.unpack('>BH' + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, pdu) instance = cls() instance.address = address instance.value = value return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 5 def create_response_pdu(self): fmt = '>BH' + conf.TYPE_CHAR return struct.pack(fmt, self.function_code, self.address, self.value) @classmethod def create_from_response_pdu(cls, resp_pdu): """ Create instance from response PDU. :param resp_pdu: Byte array with request PDU. :return: Instance of :class:`WriteSingleRegister`. """ write_single_register = cls() address, value = struct.unpack('>H' + conf.TYPE_CHAR, resp_pdu[1:5]) write_single_register.address = address write_single_register.data = value return write_single_register def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. """ endpoint = route_map.match(slave_id, self.function_code, self.address) if endpoint is None: raise IllegalDataAddressError() endpoint(slave_id=slave_id, address=self.address, value=self.value, function_code=self.function_code)
class WriteSingleRegister(ModbusFunction): ''' Implement Modbus function code 06. "This function code is used to write a single holding register in a remote device. The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. Therefore register numbered 1 is addressed as 0. The normal response is an echo of the request, returned after the register contents have been written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.6 The request PDU with function code 06 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
7
9
2
5
3
1
1.21
1
3
2
0
6
0
8
8
140
34
48
25
33
58
39
19
30
2
2
1
11
3,060
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.WriteSingleCoil
class WriteSingleCoil(ModbusFunction): """ Implement Modbus function code 05. "This function code is used to write a single output to either ON or OFF in a remote device. The requested ON/OFF state is specified by a constant in the request data field. A value of FF 00 hex requests the output to be ON. A value of 00 00 requests it to be OFF. All other values are illegal and will not affect the output. The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. The requested ON/OFF state is specified by a constant in the Coil Value field. A value of 0XFF00 requests the coil to be ON. A value of 0X0000 requests the coil to be off. All other values are illegal and will not affect the coil. The normal response is an echo of the request, returned after the coil state has been written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.5 The request PDU with function code 05 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x05\\x00d\\xFF\\x00') (5, 100, 65280) The reponse PDU is a copy of the request PDU. ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== """ function_code = WRITE_SINGLE_COIL format_character = 'B' address = None data = None _value = None @property def value(self): if self._value == 0xFF00: return 1 return self._value @value.setter def value(self, value): if value not in [0, 1, 0xFF00]: raise IllegalDataValueError value = 0xFF00 if value == 1 else value self._value = value @property def request_pdu(self): """ Build request PDU to write single coil. :return: Byte array of 5 bytes with PDU. """ if None in [self.address, self.value]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.address, self._value) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. :param pdu: A response PDU. :return: Instance of this class. """ _, address, value = struct.unpack('>BHH', pdu) value = 1 if value == 0xFF00 else value instance = cls() instance.address = address instance.value = value return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 5 def create_response_pdu(self): """ Create response pdu. :param data: A list with values. :return: Byte array of at least 4 bytes. """ fmt = '>BHH' return struct.pack(fmt, self.function_code, self.address, self._value) @classmethod def create_from_response_pdu(cls, resp_pdu): """ Create instance from response PDU. :param resp_pdu: Byte array with request PDU. :return: Instance of :class:`WriteSingleCoil`. """ write_single_coil = cls() address, value = struct.unpack('>HH', resp_pdu[1:5]) value = 1 if value == 0xFF00 else value write_single_coil.address = address write_single_coil.data = value return write_single_coil def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. """ endpoint = route_map.match(slave_id, self.function_code, self.address) if endpoint is None: raise IllegalDataAddressError() endpoint(slave_id=slave_id, address=self.address, value=self.value, function_code=self.function_code)
class WriteSingleCoil(ModbusFunction): ''' Implement Modbus function code 05. "This function code is used to write a single output to either ON or OFF in a remote device. The requested ON/OFF state is specified by a constant in the request data field. A value of FF 00 hex requests the output to be ON. A value of 00 00 requests it to be OFF. All other values are illegal and will not affect the output. The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. The requested ON/OFF state is specified by a constant in the Coil Value field. A value of 0XFF00 requests the coil to be ON. A value of 0X0000 requests the coil to be off. All other values are illegal and will not affect the coil. The normal response is an echo of the request, returned after the coil state has been written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.5 The request PDU with function code 05 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
7
10
2
5
3
2
1.27
1
3
2
0
6
0
8
8
154
38
51
26
36
65
43
20
34
3
2
1
15
3,061
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.IllegalDataValueError
class IllegalDataValueError(ModbusError): """ The value contained in the request data field is not an allowable value for the server. """ error_code = 3 def __str__(self): return self.__doc__
class IllegalDataValueError(ModbusError): ''' The value contained in the request data field is not an allowable value for the server. ''' def __str__(self): pass
2
1
2
0
2
0
1
0.75
1
0
0
0
1
0
1
11
9
2
4
3
2
3
4
3
2
1
4
0
1
3,062
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.WriteMultipleCoils
class WriteMultipleCoils(ModbusFunction): """ Implement Modbus function 15 (0x0F) Write Multiple Coils. "This function code is used to force each coil in a sequence of coils to either ON or OFF in a remote device. The Request PDU specifies the coil references to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. The requested ON/OFF states are specified by contents of the request data field. A logical '1' in a bit position of the field requests the corresponding output to be ON. A logical '0' requests it to be OFF. The normal response returns the function code, starting address, and quantity of coils forced." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.11 The request PDU with function code 15 must be at least 7 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting Address 2 Quantity 2 Byte count 1 Value n ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHHBB', b'\\x0f\\x00d\\x00\\x03\\x01\\x05') (16, 100, 3, 1, 5) The reponse PDU is 5 bytes and contains following structure: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== """ function_code = WRITE_MULTIPLE_COILS starting_address = None _values = None _data = None @property def values(self): return self._values @values.setter def values(self, values): if not (1 <= len(values) <= 0x7B0): raise IllegalDataValueError for value in values: if value not in [0, 1]: raise IllegalDataValueError self._values = values @property def request_pdu(self): if None in [self.starting_address, self._values]: raise IllegalDataValueError bytes_ = [self.values[i:i + 8] for i in range(0, len(self.values), 8)] # Reduce each all bits per byte to a number. Byte # [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3. for index, byte in enumerate(bytes_): bytes_[index] = \ reduce(lambda a, b: (a << 1) + b, list(reversed(byte))) fmt = '>BHHB' + 'B' * len(bytes_) return struct.pack(fmt, self.function_code, self.starting_address, len(self.values), (len(self.values) + 7) // 8, *bytes_) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. This method requires some clarification regarding the unpacking of the status that are being passed to the callbacks. A coil status can be 0 or 1. The request PDU contains at least 1 byte, representing the status for 1 to 8 coils. Assume a request with starting address 100, quantity set to 3 and the value byte is 6. 0b110 is the binary reprensention of decimal 6. The Least Significant Bit (LSB) is status of coil with starting address. So status of coil 100 is 0, status of coil 101 is 1 and status of coil 102 is 1 too. coil address 102 101 100 1 1 0 Again, assume starting address 100 and byte value is 6. But now quantity is 4. So the value byte is addressing 4 coils. The binary representation of 6 is now 0b0110. LSB again is 0, meaning status of coil 100 is 0. Status of 101 and 102 is 1, like in the previous example. Status of coil 104 is 0. coil address 104 102 101 100 0 1 1 0 In short: the binary representation of the byte value is in reverse mapped to the coil addresses. In table below you can see some more examples. # quantity value binary representation | 102 101 100 == ======== ===== ===================== | === === === 01 1 0 0b0 - - 0 02 1 1 0b1 - - 1 03 2 0 0b00 - 0 0 04 2 1 0b01 - 0 1 05 2 2 0b10 - 1 0 06 2 3 0b11 - 1 1 07 3 0 0b000 0 0 0 08 3 1 0b001 0 0 1 09 3 2 0b010 0 1 0 10 3 3 0b011 0 1 1 11 3 4 0b100 1 0 0 12 3 5 0b101 1 0 1 13 3 6 0b110 1 1 0 14 3 7 0b111 1 1 1 :param pdu: A request PDU. """ _, starting_address, quantity, byte_count = \ struct.unpack('>BHHB', pdu[:6]) fmt = '>' + (conf.SINGLE_BIT_VALUE_FORMAT_CHARACTER * byte_count) values = struct.unpack(fmt, pdu[6:]) res = list() for i, value in enumerate(values): padding = 8 if (quantity - (8 * i)) // 8 > 0 else quantity % 8 fmt = '{{0:0{padding}b}}'.format(padding=padding) # Create binary representation of integer, convert it to a list # and reverse the list. res = res + [int(i) for i in fmt.format(value)][::-1] instance = cls() instance.starting_address = starting_address instance.quantity = quantity instance.values = res return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 5 def create_response_pdu(self): """ Create response pdu. :param data: A list with values. :return: Byte array 5 bytes. """ return struct.pack('>BHH', self.function_code, self.starting_address, len(self.values)) @classmethod def create_from_response_pdu(cls, resp_pdu): write_multiple_coils = cls() starting_address, data = struct.unpack('>HH', resp_pdu[1:5]) write_multiple_coils.starting_address = starting_address write_multiple_coils.data = data return write_multiple_coils def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. """ for index, value in enumerate(self.values): address = self.starting_address + index endpoint = route_map.match(slave_id, self.function_code, address) if endpoint is None: raise IllegalDataAddressError() endpoint(slave_id=slave_id, address=address, value=value, function_code=self.function_code)
class WriteMultipleCoils(ModbusFunction): ''' Implement Modbus function 15 (0x0F) Write Multiple Coils. "This function code is used to force each coil in a sequence of coils to either ON or OFF in a remote device. The Request PDU specifies the coil references to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. The requested ON/OFF states are specified by contents of the request data field. A logical '1' in a bit position of the field requests the corresponding output to be ON. A logical '0' requests it to be OFF. The normal response returns the function code, starting address, and quantity of coils forced." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.11 The request PDU with function code 15 must be at least 7 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting Address 2 Quantity 2 Byte count 1 Value n ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
5
17
4
7
7
2
1.46
1
7
2
0
6
0
8
8
211
51
65
35
50
95
53
29
44
4
2
2
17
3,063
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.IllegalFunctionError
class IllegalFunctionError(ModbusError): """ The function code received in the request is not an allowable action for the server. """ error_code = 1 def __str__(self): return 'Function code is not an allowable action for the server.'
class IllegalFunctionError(ModbusError): ''' The function code received in the request is not an allowable action for the server. ''' def __str__(self): pass
2
1
2
0
2
0
1
0.75
1
0
0
0
1
0
1
11
9
2
4
3
2
3
4
3
2
1
4
0
1
3,064
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.WriteMultipleRegisters
class WriteMultipleRegisters(ModbusFunction): """ Implement Modbus function 16 (0x10) Write Multiple Registers. "This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device. The requested written values are specified in the request data field. Data is packed as two bytes per register. The normal response returns the function code, starting address, and quantity of registers written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.12 The request PDU with function code 16 must be at least 8 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting Address 2 Quantity 2 Byte count 1 Value Quantity * 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHHBH', b'\\x10\\x00d\\x00\\x01\\x02\\x00\\x05') (16, 100, 1, 2, 5) The reponse PDU is 5 bytes and contains following structure: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== """ function_code = WRITE_MULTIPLE_REGISTERS starting_address = None _values = None _data = None @property def values(self): return self._values @values.setter def values(self, values): if not (1 <= len(values) <= 0x7B0): raise IllegalDataValueError for value in values: try: struct.pack(">" + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, value) except struct.error: raise IllegalDataValueError self._values = values self._values = values @property def request_pdu(self): fmt = '>BHHB' + (conf.TYPE_CHAR * len(self.values)) return struct.pack(fmt, self.function_code, self.starting_address, len(self.values), len(self.values) * 2, *self.values) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity, byte_count = \ struct.unpack('>BHHB', pdu[:6]) # Values are 16 bit, so each value takes up 2 bytes. fmt = '>' + (conf.MULTI_BIT_VALUE_FORMAT_CHARACTER * int((byte_count / 2))) values = list(struct.unpack(fmt, pdu[6:])) instance = cls() instance.starting_address = starting_address instance.values = values return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 5 def create_response_pdu(self): """ Create response pdu. :param data: A list with values. :return: Byte array 5 bytes. """ return struct.pack('>BHH', self.function_code, self.starting_address, len(self.values)) @classmethod def create_from_response_pdu(cls, resp_pdu): write_multiple_registers = cls() starting_address, data = struct.unpack('>HH', resp_pdu[1:5]) write_multiple_registers.starting_address = starting_address write_multiple_registers.data = data return write_multiple_registers def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. """ for index, value in enumerate(self.values): address = self.starting_address + index endpoint = route_map.match(slave_id, self.function_code, address) if endpoint is None: raise IllegalDataAddressError() endpoint(slave_id=slave_id, address=address, value=value, function_code=self.function_code)
class WriteMultipleRegisters(ModbusFunction): ''' Implement Modbus function 16 (0x10) Write Multiple Registers. "This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device. The requested written values are specified in the request data field. Data is packed as two bytes per register. The normal response returns the function code, starting address, and quantity of registers written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.12 The request PDU with function code 16 must be at least 8 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting Address 2 Quantity 2 Byte count 1 Value Quantity * 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
5
9
2
6
2
2
0.93
1
5
2
0
6
0
8
8
146
36
57
30
42
53
45
24
36
4
2
2
13
3,065
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.ServerDeviceBusyError
class ServerDeviceBusyError(ModbusError): """ The server is engaged in a long-duration program command. """ error_code = 6 def __str__(self): return self.__doc__
class ServerDeviceBusyError(ModbusError): ''' The server is engaged in a long-duration program command. ''' def __str__(self): pass
2
1
2
0
2
0
1
0.25
1
0
0
0
1
0
1
11
6
1
4
3
2
1
4
3
2
1
4
0
1
3,066
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.ServerDeviceFailureError
class ServerDeviceFailureError(ModbusError): """ An unrecoverable error occurred. """ error_code = 4 def __str__(self): return 'An unrecoverable error occurred.'
class ServerDeviceFailureError(ModbusError): ''' An unrecoverable error occurred. ''' def __str__(self): pass
2
1
2
0
2
0
1
0.25
1
0
0
0
1
0
1
11
6
1
4
3
2
1
4
3
2
1
4
0
1
3,067
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.ModbusFunction
class ModbusFunction(object): function_code = None
class ModbusFunction(object): pass
1
0
0
0
0
0
0
0
1
0
0
8
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
3,068
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.GatewayTargetDeviceFailedToRespondError
class GatewayTargetDeviceFailedToRespondError(ModbusError): """ Didn't get a response from target device. """ error_code = 11 def __repr__(self): return self.__doc__
class GatewayTargetDeviceFailedToRespondError(ModbusError): ''' Didn't get a response from target device. ''' def __repr__(self): pass
2
1
2
0
2
0
1
0.25
1
0
0
0
1
0
1
11
6
1
4
3
2
1
4
3
2
1
4
0
1
3,069
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.ReadDiscreteInputs
class ReadDiscreteInputs(ModbusFunction): """ Implement Modbus function code 02. "This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device. The Request PDU specifies the starting address, i.e. the address of the first input specified, and the number of inputs. In the PDU Discrete Inputs are addressed starting at zero. Therefore Discrete inputs numbered 1-16 are addressed as 0-15. The discrete inputs in the response message are packed as one input per bit of the data field. Status is indicated as 1= ON; 0= OFF. The LSB of the first data byte contains the input addressed in the query. The other inputs follow toward the high order end of this byte, and from low order to high order in subsequent bytes. If the returned input quantity is not a multiple of eight, the remaining bits in the final d ata byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.2 The request PDU with function code 02 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x02\\x00d\\x00\\x03') (2, 100, 3) The reponse PDU varies in length, depending on the request. 8 inputs require 1 byte. The amount of bytes needed represent status of the inputs to can be calculated with: bytes = ceil(quantity / 8). This response contains ceil(3 / 8) = 1 byte to describe the status of the inputs. The structure of a compleet response PDU looks like this: ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Coil status n ================ =============== Assume the status of 102 is 0, 101 is 1 and 100 is also 1. This is binary 011 which is decimal 3. The PDU can packed like this:: >>> struct.pack('>BBB', function_code, byte_count, 3) b'\\x02\\x01\\x03' """ function_code = READ_DISCRETE_INPUTS max_quantity = 2000 format_character = 'B' data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of inputs to read. Quantity must be between 1 and 2000. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 2000): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(2000)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read discrete inputs. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = cls() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 2 + int(math.ceil(self.quantity / 8)) def create_response_pdu(self, data): """ Create response pdu. :param data: A list with 0's and/or 1's. :return: Byte array of at least 3 bytes. """ log.debug('Create single bit response pdu {0}.'.format(data)) bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)] # Reduce each all bits per byte to a number. Byte # [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3. for index, byte in enumerate(bytes_): bytes_[index] = \ reduce(lambda a, b: (a << 1) + b, list(reversed(byte))) log.debug('Reduced single bit data to {0}.'.format(bytes_)) # The first 2 B's of the format encode the function code (1 byte) and # the length (1 byte) of the following byte series. Followed by # a B # for every byte in the series of bytes. 3 lead to the format '>BBB' # and 257 lead to the format '>BBBB'. fmt = '>BB' + self.format_character * len(bytes_) return struct.pack(fmt, self.function_code, len(bytes_), *bytes_) @classmethod def create_from_response_pdu(cls, resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the quantity of inputs read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of inputs read. :return: Instance of :class:`ReadDiscreteInputs`. """ read_discrete_inputs = cls() read_discrete_inputs.quantity = struct.unpack('>H', req_pdu[-2:])[0] byte_count = struct.unpack('>B', resp_pdu[1:2])[0] fmt = '>' + ('B' * byte_count) bytes_ = struct.unpack(fmt, resp_pdu[2:]) data = list() for i, value in enumerate(bytes_): padding = 8 if (read_discrete_inputs.quantity - (8 * i)) // 8 > 0 \ else read_discrete_inputs.quantity % 8 fmt = '{{0:0{padding}b}}'.format(padding=padding) # Create binary representation of integer, convert it to a list # and reverse the list. data = data + [int(i) for i in fmt.format(value)][::-1] read_discrete_inputs.data = data return read_discrete_inputs def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. :return: Result of call to endpoint. """ values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) if endpoint is None: raise IllegalDataAddressError() values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values
class ReadDiscreteInputs(ModbusFunction): ''' Implement Modbus function code 02. "This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device. The Request PDU specifies the starting address, i.e. the address of the first input specified, and the number of inputs. In the PDU Discrete Inputs are addressed starting at zero. Therefore Discrete inputs numbered 1-16 are addressed as 0-15. The discrete inputs in the response message are packed as one input per bit of the data field. Status is indicated as 1= ON; 0= OFF. The LSB of the first data byte contains the input addressed in the query. The other inputs follow toward the high order end of this byte, and from low order to high order in subsequent bytes. If the returned input quantity is not a multiple of eight, the remaining bits in the final d ata byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.2 The request PDU with function code 02 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
8
14
3
7
5
2
1.36
1
8
2
0
6
0
8
8
206
48
67
36
52
91
54
30
45
3
2
2
15
3,070
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.ReadHoldingRegisters
class ReadHoldingRegisters(ModbusFunction): """ Implement Modbus function code 03. "This function code is used to read the contents of a contiguous block of holding registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore registers numbered 1-16 are addressed as 0-15. The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte. For each register, the first byte contains the high order bits and the second contains the low order bits." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.3 The request PDU with function code 03 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x03\\x00d\\x00\\x03') (3, 100, 3) The reponse PDU varies in length, depending on the request. By default, holding registers are 16 bit (2 bytes) values. So values of 3 holding registers is expressed in 2 * 3 = 6 bytes. ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Register values Quantity * 2 ================ =============== Assume the value of 100 is 8, 101 is 0 and 102 is also 15. The PDU can packed like this:: >>> data = [8, 0, 15] >>> struct.pack('>BBHHH', function_code, len(data) * 2, *data) b'\\x03\\x06\\x00\\x08\\x00\\x00\\x00\\x0f' """ function_code = READ_HOLDING_REGISTERS max_quantity = 0x007D data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of registers to read. Quantity must be between 1 and 0x00FD. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 0x007D): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(0x007D)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read coils. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = cls() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 2 + self.quantity * 2 def create_response_pdu(self, data): """ Create response pdu. :param data: A list with values. :return: Byte array of at least 4 bytes. """ log.debug('Create multi bit response pdu {0}.'.format(data)) fmt = '>BB' + conf.TYPE_CHAR * len(data) return struct.pack(fmt, self.function_code, len(data) * 2, *data) @classmethod def create_from_response_pdu(cls, resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the number of registers read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoils`. """ read_holding_registers = cls() read_holding_registers.quantity = struct.unpack('>H', req_pdu[-2:])[0] read_holding_registers.byte_count = \ struct.unpack('>B', resp_pdu[1:2])[0] fmt = '>' + (conf.TYPE_CHAR * read_holding_registers.quantity) read_holding_registers.data = list(struct.unpack(fmt, resp_pdu[2:])) return read_holding_registers def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. :return: Result of call to endpoint. """ values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) if endpoint is None: raise IllegalDataAddressError() values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values
class ReadHoldingRegisters(ModbusFunction): ''' Implement Modbus function code 03. "This function code is used to read the contents of a contiguous block of holding registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore registers numbered 1-16 are addressed as 0-15. The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte. For each register, the first byte contains the high order bits and the second contains the low order bits." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.3 The request PDU with function code 03 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
8
11
2
5
4
2
1.38
1
5
2
0
6
0
8
8
173
42
55
28
40
76
43
22
34
3
2
2
12
3,071
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.MemoryParityError
class MemoryParityError(ModbusError): """ The server attempted to read record file, but detected a parity error in memory. """ error_code = 8 def __repr__(self): return self.__doc__
class MemoryParityError(ModbusError): ''' The server attempted to read record file, but detected a parity error in memory. ''' def __repr__(self): pass
2
1
2
0
2
0
1
0.75
1
0
0
0
1
0
1
11
9
2
4
3
2
3
4
3
2
1
4
0
1
3,072
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.GatewayPathUnavailableError
class GatewayPathUnavailableError(ModbusError): """ The gateway is probably misconfigured or overloaded. """ error_code = 10 def __repr__(self): return self.__doc__
class GatewayPathUnavailableError(ModbusError): ''' The gateway is probably misconfigured or overloaded. ''' def __repr__(self): pass
2
1
2
0
2
0
1
0.25
1
0
0
0
1
0
1
11
6
1
4
3
2
1
4
3
2
1
4
0
1
3,073
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/functions.py
umodbus.functions.ReadCoils
class ReadCoils(ModbusFunction): """ Implement Modbus function code 01. "This function code is used to read from 1 to 2000 contiguous status of coils in a remote device. The Request PDU specifies the starting address, i.e. the address of the first coil specified, and the number of coils. In the PDU Coils are addressed starting at zero. Therefore coils numbered 1-16 are addressed as 0-15. The coils in the response message are packed as one coil per bit of the data field. Status is indicated as 1= ON and 0= OFF. The LSB of the first data byte contains the output addressed in the query. The other coils follow toward the high order end of this byte, and from low order to high order in subsequent bytes. If the returned output quantity is not a multiple of eight, the remaining bits in the final data byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.1 The request PDU with function code 01 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x01\\x00d\\x00\\x03') (1, 100, 3) The reponse PDU varies in length, depending on the request. Each 8 coils require 1 byte. The amount of bytes needed represent status of the coils to can be calculated with: bytes = ceil(quantity / 8). This response contains ceil(3 / 8) = 1 byte to describe the status of the coils. The structure of a compleet response PDU looks like this: ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Coil status n ================ =============== Assume the status of 102 is 0, 101 is 1 and 100 is also 1. This is binary 011 which is decimal 3. The PDU can packed like this:: >>> struct.pack('>BBB', function_code, byte_count, 3) b'\\x01\\x01\\x03' """ function_code = READ_COILS max_quantity = 2000 format_character = 'B' data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of coils to read. Quantity must be between 1 and 2000. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 2000): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(2000)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read coils. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @classmethod def create_from_request_pdu(cls, pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = cls() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 2 + int(math.ceil(self.quantity / 8)) def create_response_pdu(self, data): """ Create response pdu. :param data: A list with 0's and/or 1's. :return: Byte array of at least 3 bytes. """ log.debug('Create single bit response pdu {0}.'.format(data)) bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)] # Reduce each all bits per byte to a number. Byte # [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3. for index, byte in enumerate(bytes_): bytes_[index] = \ reduce(lambda a, b: (a << 1) + b, list(reversed(byte))) log.debug('Reduced single bit data to {0}.'.format(bytes_)) # The first 2 B's of the format encode the function code (1 byte) and # the length (1 byte) of the following byte series. Followed by # a B # for every byte in the series of bytes. 3 lead to the format '>BBB' # and 257 lead to the format '>BBBB'. fmt = '>BB' + self.format_character * len(bytes_) return struct.pack(fmt, self.function_code, len(bytes_), *bytes_) @classmethod def create_from_response_pdu(cls, resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the quantity of coils read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoils`. """ read_coils = cls() read_coils.quantity = struct.unpack('>H', req_pdu[-2:])[0] byte_count = struct.unpack('>B', resp_pdu[1:2])[0] fmt = '>' + ('B' * byte_count) bytes_ = struct.unpack(fmt, resp_pdu[2:]) data = list() for i, value in enumerate(bytes_): padding = 8 if (read_coils.quantity - (8 * i)) // 8 > 0 \ else read_coils.quantity % 8 fmt = '{{0:0{padding}b}}'.format(padding=padding) # Create binary representation of integer, convert it to a list # and reverse the list. data = data + [int(i) for i in fmt.format(value)][::-1] read_coils.data = data return read_coils def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param route_map: Instance of modbus.route.Map. :return: Result of call to endpoint. """ values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) if endpoint is None: raise IllegalDataAddressError() values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values
class ReadCoils(ModbusFunction): ''' Implement Modbus function code 01. "This function code is used to read from 1 to 2000 contiguous status of coils in a remote device. The Request PDU specifies the starting address, i.e. the address of the first coil specified, and the number of coils. In the PDU Coils are addressed starting at zero. Therefore coils numbered 1-16 are addressed as 0-15. The coils in the response message are packed as one coil per bit of the data field. Status is indicated as 1= ON and 0= OFF. The LSB of the first data byte contains the output addressed in the query. The other coils follow toward the high order end of this byte, and from low order to high order in subsequent bytes. If the returned output quantity is not a multiple of eight, the remaining bits in the final data byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.1 The request PDU with function code 01 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\x01\x00d` -> `b pass
15
8
14
3
7
5
2
1.34
1
8
2
0
6
0
8
8
205
48
67
36
52
90
54
30
45
3
2
2
15
3,074
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/config.py
umodbus.config.Config
class Config(object): """ Class to hold global configuration. """ SINGLE_BIT_VALUE_FORMAT_CHARACTER = 'B' """ Format character used to (un)pack singlebit values (values used for writing from and writing to coils or discrete inputs) from structs. .. note:: Its value should not be changed. This attribute exists to be consistend with `MULTI_BIT_VALUE_FORMAT_CHARACTER`. """ MULTI_BIT_VALUE_FORMAT_CHARACTER = 'H' """ Format character used to (un)pack multibit values (values used for writing from and writing to registers) from structs. The format character depends on size of the value and whether values are signed or unsigned. By default multibit values are unsigned and use 16 bits. The default format character used for (un)packing structs is 'H'. .. note:: Its value should not be set directly. Instead use :attr:`SIGNED_VALUES` and :attr:`BIT_SIZE` to modify this value. """ def __init__(self): self.SIGNED_VALUES = os.environ.get('UMODBUS_SIGNED_VALUES', False) self.BIT_SIZE = os.environ.get('UMODBUS_BIT_SIZE', 16) @property def TYPE_CHAR(self): if self.SIGNED_VALUES: return 'h' return 'H' def _set_multi_bit_value_format_character(self): """ Set format character for multibit values. The format character depends on size of the value and whether values are signed or unsigned. """ self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \ self.MULTI_BIT_VALUE_FORMAT_CHARACTER.upper() if self.SIGNED_VALUES: self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \ self.MULTI_BIT_VALUE_FORMAT_CHARACTER.lower() @property def SIGNED_VALUES(self): """ Whether values are signed or not. Default is False. This value can also be set using the environment variable `UMODBUS_SIGNED_VALUES`. """ return self._SIGNED_VALUES @SIGNED_VALUES.setter def SIGNED_VALUES(self, value): """ Set signedness of values. This method effects `Config.MULTI_BIT_VALUE_FORMAT_CHARACTER`. :param value: Boolean indicting if values are signed or not. """ self._SIGNED_VALUES = value self._set_multi_bit_value_format_character() @property def BIT_SIZE(self): """ Bit size of values. Default is 16. This value can also be set using the environment variable `UMODBUS_BIT_SIZE`. """ return self._BIT_SIZE @BIT_SIZE.setter def BIT_SIZE(self, value): """ Set bit size of values. This method effects `Config.MULTI_BIT_VALUE_FORMAT_CHARACTER`. :param value: Number indication bit size. """ self._BIT_SIZE = value self._set_multi_bit_value_format_character()
class Config(object): ''' Class to hold global configuration. ''' def __init__(self): pass @property def TYPE_CHAR(self): pass def _set_multi_bit_value_format_character(self): ''' Set format character for multibit values. The format character depends on size of the value and whether values are signed or unsigned. ''' pass @property def SIGNED_VALUES(self): ''' Whether values are signed or not. Default is False. This value can also be set using the environment variable `UMODBUS_SIGNED_VALUES`. ''' pass @SIGNED_VALUES.setter def SIGNED_VALUES(self): ''' Set signedness of values. This method effects `Config.MULTI_BIT_VALUE_FORMAT_CHARACTER`. :param value: Boolean indicting if values are signed or not. ''' pass @property def BIT_SIZE(self): ''' Bit size of values. Default is 16. This value can also be set using the environment variable `UMODBUS_BIT_SIZE`. ''' pass @BIT_SIZE.setter def BIT_SIZE(self): ''' Set bit size of values. This method effects `Config.MULTI_BIT_VALUE_FORMAT_CHARACTER`. :param value: Number indication bit size. ''' pass
13
6
7
1
3
3
1
1.16
1
0
0
0
7
2
7
7
88
21
31
17
18
36
24
12
16
2
1
1
9
3,075
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/exceptions.py
umodbus.exceptions.AcknowledgeError
class AcknowledgeError(ModbusError): """ The server has accepted the requests and it processing it, but a long duration of time will be required to do so. """ error_code = 5 def __str__(self): return self.__doc__
class AcknowledgeError(ModbusError): ''' The server has accepted the requests and it processing it, but a long duration of time will be required to do so. ''' def __str__(self): pass
2
1
2
0
2
0
1
0.75
1
0
0
0
1
0
1
11
8
1
4
3
2
3
4
3
2
1
4
0
1
3,076
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/tests/unit/test_config.py
tests.unit.test_config.TestConfig
class TestConfig: def test_defaults(self, config): """ Test whether defaults configuration values are correct. """ assert config.SINGLE_BIT_VALUE_FORMAT_CHARACTER == 'B' assert config.MULTI_BIT_VALUE_FORMAT_CHARACTER == 'H' assert not config.SIGNED_VALUES def test_multi_bit_value_signed(self, config): """ Test if MULTI_BIT_VALUE_FORMAT_CHARACTER changes when setting signedness. """ assert config.MULTI_BIT_VALUE_FORMAT_CHARACTER == 'H' config.SIGNED_VALUES = True assert config.MULTI_BIT_VALUE_FORMAT_CHARACTER == 'h'
class TestConfig: def test_defaults(self, config): ''' Test whether defaults configuration values are correct. ''' pass def test_multi_bit_value_signed(self, config): ''' Test if MULTI_BIT_VALUE_FORMAT_CHARACTER changes when setting signedness. ''' pass
3
2
6
0
4
2
1
0.44
0
0
0
0
2
0
2
2
14
1
9
3
6
4
9
3
6
1
0
0
2
3,077
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/server/tcp.py
umodbus.server.tcp.RequestHandler
class RequestHandler(AbstractRequestHandler): """ A subclass of :class:`socketserver.BaseRequestHandler` dispatching incoming Modbus TCP/IP request using the server's :attr:`route_map`. """ def get_meta_data(self, request_adu): """" Extract MBAP header from request adu and return it. The dict has 4 keys: transaction_id, protocol_id, length and unit_id. :param request_adu: A bytearray containing request ADU. :return: Dict with meta data of request. """ try: transaction_id, protocol_id, length, unit_id = \ unpack_mbap(request_adu[:7]) except struct.error: raise ServerDeviceFailureError() return { 'transaction_id': transaction_id, 'protocol_id': protocol_id, 'length': length, 'unit_id': unit_id, } def get_request_pdu(self, request_adu): """ Extract PDU from request ADU and return it. :param request_adu: A bytearray containing request ADU. :return: An bytearray container request PDU. """ return request_adu[7:] def create_response_adu(self, meta_data, response_pdu): """ Build response ADU from meta data and response PDU and return it. :param meta_data: A dict with meta data. :param request_pdu: A bytearray containing request PDU. :return: A bytearray containing request ADU. """ response_mbap = pack_mbap( transaction_id=meta_data['transaction_id'], protocol_id=meta_data['protocol_id'], length=len(response_pdu) + 1, unit_id=meta_data['unit_id'] ) return response_mbap + response_pdu
class RequestHandler(AbstractRequestHandler): ''' A subclass of :class:`socketserver.BaseRequestHandler` dispatching incoming Modbus TCP/IP request using the server's :attr:`route_map`. ''' def get_meta_data(self, request_adu): '''" Extract MBAP header from request adu and return it. The dict has 4 keys: transaction_id, protocol_id, length and unit_id. :param request_adu: A bytearray containing request ADU. :return: Dict with meta data of request. ''' pass def get_request_pdu(self, request_adu): ''' Extract PDU from request ADU and return it. :param request_adu: A bytearray containing request ADU. :return: An bytearray container request PDU. ''' pass def create_response_adu(self, meta_data, response_pdu): ''' Build response ADU from meta data and response PDU and return it. :param meta_data: A dict with meta data. :param request_pdu: A bytearray containing request PDU. :return: A bytearray containing request ADU. ''' pass
4
4
14
2
7
5
1
0.74
1
1
1
0
3
0
3
11
48
8
23
6
19
17
12
6
8
2
2
1
4
3,078
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/server/serial/rtu.py
umodbus.server.serial.rtu.RTUServer
class RTUServer(AbstractSerialServer): @property def serial_port(self): return self._serial_port @serial_port.setter def serial_port(self, serial_port): """ Set timeouts on serial port based on baudrate to detect frames. """ char_size = get_char_size(serial_port.baudrate) # See docstring of get_char_size() for meaning of constants below. serial_port.inter_byte_timeout = 1.5 * char_size serial_port.timeout = 3.5 * char_size self._serial_port = serial_port def serve_once(self): """ Listen and handle 1 request. """ # 256 is the maximum size of a Modbus RTU frame. request_adu = self.serial_port.read(256) log.debug('<-- {0}'.format(hexlify(request_adu))) if len(request_adu) == 0: raise ValueError response_adu = self.process(request_adu) self.respond(response_adu) def process(self, request_adu): """ Process request ADU and return response. :param request_adu: A bytearray containing the ADU request. :return: A bytearray containing the response of the ADU request. """ validate_crc(request_adu) return super(RTUServer, self).process(request_adu) def create_response_adu(self, meta_data, response_pdu): """ Build response ADU from meta data and response PDU and return it. :param meta_data: A dict with meta data. :param request_pdu: A bytearray containing request PDU. :return: A bytearray containing request ADU. """ first_part_adu = struct.pack('>B', meta_data['unit_id']) + response_pdu return first_part_adu + get_crc(first_part_adu)
class RTUServer(AbstractSerialServer): @property def serial_port(self): pass @serial_port.setter def serial_port(self): ''' Set timeouts on serial port based on baudrate to detect frames. ''' pass def serve_once(self): ''' Listen and handle 1 request. ''' pass def process(self, request_adu): ''' Process request ADU and return response. :param request_adu: A bytearray containing the ADU request. :return: A bytearray containing the response of the ADU request. ''' pass def create_response_adu(self, meta_data, response_pdu): ''' Build response ADU from meta data and response PDU and return it. :param meta_data: A dict with meta data. :param request_pdu: A bytearray containing request PDU. :return: A bytearray containing request ADU. ''' pass
8
4
8
1
4
3
1
0.57
1
2
0
0
5
1
5
13
45
9
23
13
15
13
21
11
15
2
2
1
6
3,079
AdvancedClimateSystems/uModbus
AdvancedClimateSystems_uModbus/umodbus/client/serial/redundancy_check.py
umodbus.client.serial.redundancy_check.CRCError
class CRCError(Exception): """ Valid error to raise when CRC isn't correct. """ pass
class CRCError(Exception): ''' Valid error to raise when CRC isn't correct. ''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
3,080
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/base.py
Adyen.services.base.AdyenBase
class AdyenBase(object): def __setattr__(self, attr, value): client_attr = ["username", "password", "platform"] if attr in client_attr: if value: self.client[attr] = value else: super(AdyenBase, self).__setattr__(attr, value) def __getattr__(self, attr): client_attr = ["username", "password", "platform"] if attr in client_attr: return self.client[attr]
class AdyenBase(object): def __setattr__(self, attr, value): pass def __getattr__(self, attr): pass
3
0
6
0
6
0
3
0
1
1
0
2
2
0
2
2
13
1
12
5
9
0
11
5
8
3
1
2
5
3,081
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/legalEntityManagement/business_lines_api.py
Adyen.services.legalEntityManagement.business_lines_api.BusinessLinesApi
class BusinessLinesApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(BusinessLinesApi, self).__init__(client=client) self.service = "legalEntityManagement" self.baseUrl = "https://kyc-test.adyen.com/lem/v3" def create_business_line(self, request, idempotency_key=None, **kwargs): """ Create a business line """ endpoint = self.baseUrl + f"/businessLines" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def delete_business_line(self, id, idempotency_key=None, **kwargs): """ Delete a business line """ endpoint = self.baseUrl + f"/businessLines/{id}" method = "DELETE" return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs) def get_business_line(self, id, idempotency_key=None, **kwargs): """ Get a business line """ endpoint = self.baseUrl + f"/businessLines/{id}" method = "GET" return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs) def update_business_line(self, request, id, idempotency_key=None, **kwargs): """ Update a business line """ endpoint = self.baseUrl + f"/businessLines/{id}" method = "PATCH" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class BusinessLinesApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def create_business_line(self, request, idempotency_key=None, **kwargs): ''' Create a business line ''' pass def delete_business_line(self, id, idempotency_key=None, **kwargs): ''' Delete a business line ''' pass def get_business_line(self, id, idempotency_key=None, **kwargs): ''' Get a business line ''' pass def update_business_line(self, request, id, idempotency_key=None, **kwargs): ''' Update a business line ''' pass
6
5
6
0
4
2
1
0.76
1
1
0
0
5
2
5
8
43
6
21
16
15
16
21
16
15
1
3
0
5
3,082
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/legalEntityManagement/__init__.py
Adyen.services.legalEntityManagement.AdyenLegalEntityManagementApi
class AdyenLegalEntityManagementApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(AdyenLegalEntityManagementApi, self).__init__(client=client) self.business_lines_api = BusinessLinesApi(client=client) self.documents_api = DocumentsApi(client=client) self.hosted_onboarding_api = HostedOnboardingApi(client=client) self.legal_entities_api = LegalEntitiesApi(client=client) self.pci_questionnaires_api = PCIQuestionnairesApi(client=client) self.tax_e_delivery_consent_api = TaxEDeliveryConsentApi(client=client) self.terms_of_service_api = TermsOfServiceApi(client=client) self.transfer_instruments_api = TransferInstrumentsApi(client=client)
class AdyenLegalEntityManagementApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass
2
1
10
0
10
0
1
0.36
1
9
8
0
1
8
1
4
17
2
11
10
9
4
11
10
9
1
3
0
1
3,083
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/disputes.py
Adyen.services.disputes.AdyenDisputesApi
class AdyenDisputesApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(AdyenDisputesApi, self).__init__(client=client) self.service = "disputes" self.baseUrl = "https://ca-test.adyen.com/ca/services/DisputeService/v30" def accept_dispute(self, request, idempotency_key=None, **kwargs): """ Accept a dispute """ endpoint = self.baseUrl + f"/acceptDispute" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def defend_dispute(self, request, idempotency_key=None, **kwargs): """ Defend a dispute """ endpoint = self.baseUrl + f"/defendDispute" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def delete_dispute_defense_document(self, request, idempotency_key=None, **kwargs): """ Delete a defense document """ endpoint = self.baseUrl + f"/deleteDisputeDefenseDocument" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def retrieve_applicable_defense_reasons(self, request, idempotency_key=None, **kwargs): """ Get applicable defense reasons """ endpoint = self.baseUrl + f"/retrieveApplicableDefenseReasons" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def supply_defense_document(self, request, idempotency_key=None, **kwargs): """ Supply a defense document """ endpoint = self.baseUrl + f"/supplyDefenseDocument" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class AdyenDisputesApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def accept_dispute(self, request, idempotency_key=None, **kwargs): ''' Accept a dispute ''' pass def defend_dispute(self, request, idempotency_key=None, **kwargs): ''' Defend a dispute ''' pass def delete_dispute_defense_document(self, request, idempotency_key=None, **kwargs): ''' Delete a defense document ''' pass def retrieve_applicable_defense_reasons(self, request, idempotency_key=None, **kwargs): ''' Get applicable defense reasons ''' pass def supply_defense_document(self, request, idempotency_key=None, **kwargs): ''' Supply a defense document ''' pass
7
6
7
0
4
3
1
0.76
1
1
0
0
6
2
6
9
51
7
25
19
18
19
25
19
18
1
3
0
6
3,084
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/dataProtection.py
Adyen.services.dataProtection.AdyenDataProtectionApi
class AdyenDataProtectionApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(AdyenDataProtectionApi, self).__init__(client=client) self.service = "dataProtection" self.baseUrl = "https://ca-test.adyen.com/ca/services/DataProtectionService/v1" def request_subject_erasure(self, request, idempotency_key=None, **kwargs): """ Submit a Subject Erasure Request. """ endpoint = self.baseUrl + f"/requestSubjectErasure" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class AdyenDataProtectionApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def request_subject_erasure(self, request, idempotency_key=None, **kwargs): ''' Submit a Subject Erasure Request. ''' pass
3
2
6
0
4
2
1
0.78
1
1
0
0
2
2
2
5
19
3
9
7
6
7
9
7
6
1
3
0
2
3,085
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/utility_api.py
Adyen.services.checkout.utility_api.UtilityApi
class UtilityApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(UtilityApi, self).__init__(client=client) self.service = "checkout" self.baseUrl = "https://checkout-test.adyen.com/v71" def get_apple_pay_session(self, request, idempotency_key=None, **kwargs): """ Get an Apple Pay session """ endpoint = self.baseUrl + f"/applePay/sessions" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def origin_keys(self, request, idempotency_key=None, **kwargs): """ Create originKey values for domains Deprecated since Adyen Checkout API v67 """ endpoint = self.baseUrl + f"/originKeys" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def updates_order_for_paypal_express_checkout(self, request, idempotency_key=None, **kwargs): """ Updates the order for PayPal Express Checkout """ endpoint = self.baseUrl + f"/paypal/updateOrder" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class UtilityApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def get_apple_pay_session(self, request, idempotency_key=None, **kwargs): ''' Get an Apple Pay session ''' pass def origin_keys(self, request, idempotency_key=None, **kwargs): ''' Create originKey values for domains Deprecated since Adyen Checkout API v67 ''' pass def updates_order_for_paypal_express_checkout(self, request, idempotency_key=None, **kwargs): ''' Updates the order for PayPal Express Checkout ''' pass
5
4
7
0
4
3
1
0.82
1
1
0
0
4
2
4
7
37
6
17
13
12
14
17
13
12
1
3
0
4
3,086
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/recurring_api.py
Adyen.services.checkout.recurring_api.RecurringApi
class RecurringApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(RecurringApi, self).__init__(client=client) self.service = "checkout" self.baseUrl = "https://checkout-test.adyen.com/v71" def delete_token_for_stored_payment_details(self, storedPaymentMethodId, idempotency_key=None, **kwargs): """ Delete a token for stored payment details """ endpoint = self.baseUrl + f"/storedPaymentMethods/{storedPaymentMethodId}" method = "DELETE" return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs) def get_tokens_for_stored_payment_details(self, idempotency_key=None, **kwargs): """ Get tokens for stored payment details """ endpoint = self.baseUrl + f"/storedPaymentMethods" method = "GET" return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs) def stored_payment_methods(self, request, idempotency_key=None, **kwargs): """ Create a token to store payment details """ endpoint = self.baseUrl + f"/storedPaymentMethods" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class RecurringApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def delete_token_for_stored_payment_details(self, storedPaymentMethodId, idempotency_key=None, **kwargs): ''' Delete a token for stored payment details ''' pass def get_tokens_for_stored_payment_details(self, idempotency_key=None, **kwargs): ''' Get tokens for stored payment details ''' pass def stored_payment_methods(self, request, idempotency_key=None, **kwargs): ''' Create a token to store payment details ''' pass
5
4
6
0
4
2
1
0.76
1
1
0
0
4
2
4
7
35
5
17
13
12
13
17
13
12
1
3
0
4
3,087
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/payment_links_api.py
Adyen.services.checkout.payment_links_api.PaymentLinksApi
class PaymentLinksApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(PaymentLinksApi, self).__init__(client=client) self.service = "checkout" self.baseUrl = "https://checkout-test.adyen.com/v71" def get_payment_link(self, linkId, idempotency_key=None, **kwargs): """ Get a payment link """ endpoint = self.baseUrl + f"/paymentLinks/{linkId}" method = "GET" return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs) def payment_links(self, request, idempotency_key=None, **kwargs): """ Create a payment link """ endpoint = self.baseUrl + f"/paymentLinks" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def update_payment_link(self, request, linkId, idempotency_key=None, **kwargs): """ Update the status of a payment link """ endpoint = self.baseUrl + f"/paymentLinks/{linkId}" method = "PATCH" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class PaymentLinksApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def get_payment_link(self, linkId, idempotency_key=None, **kwargs): ''' Get a payment link ''' pass def payment_links(self, request, idempotency_key=None, **kwargs): ''' Create a payment link ''' pass def update_payment_link(self, request, linkId, idempotency_key=None, **kwargs): ''' Update the status of a payment link ''' pass
5
4
6
0
4
2
1
0.76
1
1
0
0
4
2
4
7
35
5
17
13
12
13
17
13
12
1
3
0
4
3,088
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/balancePlatform/transfer_routes_api.py
Adyen.services.balancePlatform.transfer_routes_api.TransferRoutesApi
class TransferRoutesApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(TransferRoutesApi, self).__init__(client=client) self.service = "balancePlatform" self.baseUrl = "https://balanceplatform-api-test.adyen.com/bcl/v2" def calculate_transfer_routes(self, request, idempotency_key=None, **kwargs): """ Calculate transfer routes """ endpoint = self.baseUrl + f"/transferRoutes/calculate" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class TransferRoutesApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def calculate_transfer_routes(self, request, idempotency_key=None, **kwargs): ''' Calculate transfer routes ''' pass
3
2
6
0
4
2
1
0.78
1
1
0
0
2
2
2
5
19
3
9
7
6
7
9
7
6
1
3
0
2
3,089
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/orders_api.py
Adyen.services.checkout.orders_api.OrdersApi
class OrdersApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(OrdersApi, self).__init__(client=client) self.service = "checkout" self.baseUrl = "https://checkout-test.adyen.com/v71" def cancel_order(self, request, idempotency_key=None, **kwargs): """ Cancel an order """ endpoint = self.baseUrl + f"/orders/cancel" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def get_balance_of_gift_card(self, request, idempotency_key=None, **kwargs): """ Get the balance of a gift card """ endpoint = self.baseUrl + f"/paymentMethods/balance" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def orders(self, request, idempotency_key=None, **kwargs): """ Create an order """ endpoint = self.baseUrl + f"/orders" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class OrdersApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def cancel_order(self, request, idempotency_key=None, **kwargs): ''' Cancel an order ''' pass def get_balance_of_gift_card(self, request, idempotency_key=None, **kwargs): ''' Get the balance of a gift card ''' pass def orders(self, request, idempotency_key=None, **kwargs): ''' Create an order ''' pass
5
4
6
0
4
2
1
0.76
1
1
0
0
4
2
4
7
35
5
17
13
12
13
17
13
12
1
3
0
4
3,090
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/donations_api.py
Adyen.services.checkout.donations_api.DonationsApi
class DonationsApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(DonationsApi, self).__init__(client=client) self.service = "checkout" self.baseUrl = "https://checkout-test.adyen.com/v71" def donation_campaigns(self, request, idempotency_key=None, **kwargs): """ Get a list of donation campaigns. """ endpoint = self.baseUrl + f"/donationCampaigns" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def donations(self, request, idempotency_key=None, **kwargs): """ Start a transaction for donations """ endpoint = self.baseUrl + f"/donations" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class DonationsApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def donation_campaigns(self, request, idempotency_key=None, **kwargs): ''' Get a list of donation campaigns. ''' pass def donations(self, request, idempotency_key=None, **kwargs): ''' Start a transaction for donations ''' pass
4
3
6
0
4
2
1
0.77
1
1
0
0
3
2
3
6
27
4
13
10
9
10
13
10
9
1
3
0
3
3,091
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/__init__.py
Adyen.services.checkout.AdyenCheckoutApi
class AdyenCheckoutApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(AdyenCheckoutApi, self).__init__(client=client) self.donations_api = DonationsApi(client=client) self.modifications_api = ModificationsApi(client=client) self.orders_api = OrdersApi(client=client) self.payment_links_api = PaymentLinksApi(client=client) self.payments_api = PaymentsApi(client=client) self.recurring_api = RecurringApi(client=client) self.utility_api = UtilityApi(client=client)
class AdyenCheckoutApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass
2
1
9
0
9
0
1
0.4
1
8
7
0
1
7
1
4
16
2
10
9
8
4
10
9
8
1
3
0
1
3,092
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/binlookup.py
Adyen.services.binlookup.AdyenBinlookupApi
class AdyenBinlookupApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(AdyenBinlookupApi, self).__init__(client=client) self.service = "binlookup" self.baseUrl = "https://pal-test.adyen.com/pal/servlet/BinLookup/v54" def get3ds_availability(self, request, idempotency_key=None, **kwargs): """ Check if 3D Secure is available """ endpoint = self.baseUrl + f"/get3dsAvailability" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def get_cost_estimate(self, request, idempotency_key=None, **kwargs): """ Get a fees cost estimate """ endpoint = self.baseUrl + f"/getCostEstimate" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class AdyenBinlookupApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def get3ds_availability(self, request, idempotency_key=None, **kwargs): ''' Check if 3D Secure is available ''' pass def get_cost_estimate(self, request, idempotency_key=None, **kwargs): ''' Get a fees cost estimate ''' pass
4
3
6
0
4
2
1
0.77
1
1
0
0
3
2
3
6
27
4
13
10
9
10
13
10
9
1
3
0
3
3,093
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/base.py
Adyen.services.base.AdyenServiceBase
class AdyenServiceBase(AdyenBase): def __init__(self, client=None): if client: self.client = client else: self.client = AdyenClient()
class AdyenServiceBase(AdyenBase): def __init__(self, client=None): pass
2
0
5
0
5
0
2
0
1
1
1
83
1
1
1
3
6
0
6
3
4
0
5
3
3
2
2
1
2
3,094
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/payments_api.py
Adyen.services.checkout.payments_api.PaymentsApi
class PaymentsApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(PaymentsApi, self).__init__(client=client) self.service = "checkout" self.baseUrl = "https://checkout-test.adyen.com/v71" def card_details(self, request, idempotency_key=None, **kwargs): """ Get the brands and other details of a card """ endpoint = self.baseUrl + f"/cardDetails" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def get_result_of_payment_session(self, sessionId, idempotency_key=None, **kwargs): """ Get the result of a payment session """ endpoint = self.baseUrl + f"/sessions/{sessionId}" method = "GET" return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs) def payment_methods(self, request, idempotency_key=None, **kwargs): """ Get a list of available payment methods """ endpoint = self.baseUrl + f"/paymentMethods" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def payments(self, request, idempotency_key=None, **kwargs): """ Start a transaction """ endpoint = self.baseUrl + f"/payments" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def payments_details(self, request, idempotency_key=None, **kwargs): """ Submit details for a payment """ endpoint = self.baseUrl + f"/payments/details" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def sessions(self, request, idempotency_key=None, **kwargs): """ Create a payment session """ endpoint = self.baseUrl + f"/sessions" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class PaymentsApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def card_details(self, request, idempotency_key=None, **kwargs): ''' Get the brands and other details of a card ''' pass def get_result_of_payment_session(self, sessionId, idempotency_key=None, **kwargs): ''' Get the result of a payment session ''' pass def payment_methods(self, request, idempotency_key=None, **kwargs): ''' Get a list of available payment methods ''' pass def payments(self, request, idempotency_key=None, **kwargs): ''' Start a transaction ''' pass def payments_details(self, request, idempotency_key=None, **kwargs): ''' Submit details for a payment ''' pass def sessions(self, request, idempotency_key=None, **kwargs): ''' Create a payment session ''' pass
8
7
7
0
4
3
1
0.76
1
1
0
0
7
2
7
10
59
8
29
22
21
22
29
22
21
1
3
0
7
3,095
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/services/checkout/modifications_api.py
Adyen.services.checkout.modifications_api.ModificationsApi
class ModificationsApi(AdyenServiceBase): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, client=None): super(ModificationsApi, self).__init__(client=client) self.service = "checkout" self.baseUrl = "https://checkout-test.adyen.com/v71" def cancel_authorised_payment(self, request, idempotency_key=None, **kwargs): """ Cancel an authorised payment """ endpoint = self.baseUrl + f"/cancels" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def cancel_authorised_payment_by_psp_reference(self, request, paymentPspReference, idempotency_key=None, **kwargs): """ Cancel an authorised payment """ endpoint = self.baseUrl + f"/payments/{paymentPspReference}/cancels" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def capture_authorised_payment(self, request, paymentPspReference, idempotency_key=None, **kwargs): """ Capture an authorised payment """ endpoint = self.baseUrl + f"/payments/{paymentPspReference}/captures" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def refund_captured_payment(self, request, paymentPspReference, idempotency_key=None, **kwargs): """ Refund a captured payment """ endpoint = self.baseUrl + f"/payments/{paymentPspReference}/refunds" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def refund_or_cancel_payment(self, request, paymentPspReference, idempotency_key=None, **kwargs): """ Refund or cancel a payment """ endpoint = self.baseUrl + f"/payments/{paymentPspReference}/reversals" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs) def update_authorised_amount(self, request, paymentPspReference, idempotency_key=None, **kwargs): """ Update an authorised amount """ endpoint = self.baseUrl + f"/payments/{paymentPspReference}/amountUpdates" method = "POST" return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
class ModificationsApi(AdyenServiceBase): '''NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. ''' def __init__(self, client=None): pass def cancel_authorised_payment(self, request, idempotency_key=None, **kwargs): ''' Cancel an authorised payment ''' pass def cancel_authorised_payment_by_psp_reference(self, request, paymentPspReference, idempotency_key=None, **kwargs): ''' Cancel an authorised payment ''' pass def capture_authorised_payment(self, request, paymentPspReference, idempotency_key=None, **kwargs): ''' Capture an authorised payment ''' pass def refund_captured_payment(self, request, paymentPspReference, idempotency_key=None, **kwargs): ''' Refund a captured payment ''' pass def refund_or_cancel_payment(self, request, paymentPspReference, idempotency_key=None, **kwargs): ''' Refund or cancel a payment ''' pass def update_authorised_amount(self, request, paymentPspReference, idempotency_key=None, **kwargs): ''' Update an authorised amount ''' pass
8
7
7
0
4
3
1
0.76
1
1
0
0
7
2
7
10
59
8
29
22
21
22
29
22
21
1
3
0
7
3,096
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/exceptions.py
Adyen.exceptions.AdyenAPIAuthenticationError
class AdyenAPIAuthenticationError(AdyenAPIResponseError): pass
class AdyenAPIAuthenticationError(AdyenAPIResponseError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
1
1
0
2
1
1
0
5
0
0
3,097
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/client.py
Adyen.client.AdyenResult
class AdyenResult(object): """ Args: message (dict, optional): Parsed message returned from API client. status_code (int, optional): Default 200. HTTP response code, ie 200, 404, 500, etc. psp (str, optional): Psp reference returned by Adyen for a payment. raw_request (str, optional): Raw request placed to Adyen. raw_response (str, optional): Raw response returned by Adyen. """ def __init__(self, message=None, status_code=200, psp="", raw_request="", raw_response=""): self.message = message self.status_code = status_code self.psp = psp self.raw_request = raw_request self.raw_response = raw_response self.details = {} def __str__(self): return repr(self.message)
class AdyenResult(object): ''' Args: message (dict, optional): Parsed message returned from API client. status_code (int, optional): Default 200. HTTP response code, ie 200, 404, 500, etc. psp (str, optional): Psp reference returned by Adyen for a payment. raw_request (str, optional): Raw request placed to Adyen. raw_response (str, optional): Raw response returned by Adyen. ''' def __init__(self, message=None, status_code=200, psp="", raw_request="", raw_response=""): pass def __str__(self): pass
3
1
5
0
5
0
1
0.82
1
0
0
0
2
6
2
2
23
3
11
10
7
9
10
9
7
1
1
0
2
3,098
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/exceptions.py
Adyen.exceptions.AdyenAPICommunicationError
class AdyenAPICommunicationError(AdyenAPIResponseError): pass
class AdyenAPICommunicationError(AdyenAPIResponseError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
1
1
0
2
1
1
0
5
0
0
3,099
Adyen/adyen-python-api-library
Adyen_adyen-python-api-library/Adyen/exceptions.py
Adyen.exceptions.AdyenAPIInvalidFormat
class AdyenAPIInvalidFormat(AdyenAPIResponseError): pass
class AdyenAPIInvalidFormat(AdyenAPIResponseError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
1
1
0
2
1
1
0
5
0
0