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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,100 |
5j9/wikitextparser
|
wikitextparser/_table.py
|
wikitextparser._table.Table
|
class Table(SubWikiTextWithAttrs):
__slots__ = '_attrs_match_cache'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._attrs_match_cache = None, None
@property
def nesting_level(self) -> int:
"""Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Table increases
the level by one.
"""
return self._nesting_level(('Table',)) - 1
@property
def _table_shadow(self) -> bytearray:
"""Remove Table spans from shadow and return it."""
shadow = self._shadow[:]
ss = self._span_data[0]
for s, e, _, _ in self._subspans('Table'):
if s == ss:
continue
shadow[s - ss : e - ss] = b'#' * (e - s)
return shadow
@property
def _match_table(self) -> list[list[Any]]:
"""Return match_table."""
table_shadow = self._table_shadow
# Remove table-start and table-end marks.
pos = table_shadow.find(10) # ord('\n')
lsp = _lstrip_increase(table_shadow, pos)
# Remove everything until the first row
try:
# while condition may raise IndexError of table is empty
while table_shadow[lsp] not in b'!|':
nlp = table_shadow.find(10, lsp) # ord('\n')
pos = nlp
lsp = _lstrip_increase(table_shadow, pos)
except IndexError:
return [[]]
# Start of the first row
match_table = []
pos = FIRST_NON_CAPTION_LINE(table_shadow, pos).start()
rsp = _row_separator_increase(table_shadow, pos)
pos = -1
while pos != rsp:
pos = rsp
# We have a new row.
m = NEWLINE_CELL_MATCH(table_shadow, pos)
# Don't add a row if there are no new cells.
if m:
match_row = [] # type: List[Any]
match_table.append(match_row)
while m is not None:
match_row.append(m)
sep = m['sep']
pos = m.end()
if sep == b'|':
m = INLINE_NONHAEDER_CELL_MATCH(table_shadow, pos)
while m is not None:
match_row.append(m)
pos = m.end()
m = INLINE_NONHAEDER_CELL_MATCH(table_shadow, pos)
elif sep == b'!':
m = INLINE_HAEDER_CELL_MATCH(table_shadow, pos)
while m is not None:
match_row.append(m)
pos = m.end()
m = INLINE_HAEDER_CELL_MATCH(table_shadow, pos)
pos = FIRST_NON_CAPTION_LINE(table_shadow, pos).start()
m = NEWLINE_CELL_MATCH(table_shadow, pos)
rsp = _row_separator_increase(table_shadow, pos)
return match_table
def data(
self,
span: bool = True,
strip: bool = True,
row: int = None,
column: int = None,
) -> list[list[str]] | list[str] | str:
"""Return a list containing lists of row values.
:param span: If true, calculate rows according to rowspans and colspans
attributes. Otherwise ignore them.
:param row: Return the specified row only. Zero-based index.
:param column: Return the specified column only. Zero-based index.
:param strip: strip data values
Note: Due to the lots of complications that it may cause, this function
won't look inside templates, parser functions, etc.
See https://www.mediawiki.org/wiki/Extension:Pipe_Escape for how
wiki-tables can be inserted within templates.
"""
match_table = self._match_table
# Note string is only used for extracting data, matching is done over
# the shadow.
string = self.string
table_data = [] # type: List[List[str]]
if strip:
for match_row in match_table:
row_data = [] # type: List[str]
table_data.append(row_data)
for m in match_row:
# Spaces after the first newline can be meaningful
s, e = m.span('data')
row_data.append(string[s:e].lstrip(' ').rstrip(WS))
else:
for match_row in match_table:
row_data = []
table_data.append(row_data)
for m in match_row:
s, e = m.span('data')
row_data.append(string[s:e])
if table_data:
if span:
table_attrs = [] # type: List[List[Dict[str, str]]]
for match_row in match_table:
row_attrs = [] # type: List[Dict[str, str]]
table_attrs.append(row_attrs)
row_attrs_append = row_attrs.append
for m in match_row:
s, e = m.span('attrs')
captures = ATTRS_MATCH(
string.encode('ascii', 'replace'), s, e
).captures
row_attrs_append(
dict(
zip(
captures('attr_name'),
captures('attr_value'),
)
)
)
table_data = _apply_attr_spans(table_attrs, table_data)
if row is None:
if column is None:
return table_data
return [r[column] for r in table_data]
if column is None:
return table_data[row]
return table_data[row][column]
def cells(
self,
row: int = None,
column: int = None,
span: bool = True,
) -> list[list[Cell]] | list[Cell] | Cell:
"""Return a list of lists containing Cell objects.
:param span: If is True, rearrange the result according to colspan and
rospan attributes.
:param row: Return the specified row only. Zero-based index.
:param column: Return the specified column only. Zero-based index.
If both row and column are provided, return the relevant cell object.
If only need the values inside cells, then use the ``data`` method
instead.
"""
tbl_span = self._span_data
ss = tbl_span[0]
match_table = self._match_table
shadow = self._shadow
type_ = id(tbl_span)
type_to_spans = self._type_to_spans
spans = type_to_spans.setdefault(type_, [])
table_cells = [] # type: List[List[Cell]]
table_attrs = [] # type: List[List[Dict[str, str]]]
attrs_match = None
for match_row in match_table:
row_cells = [] # type: List[Cell]
table_cells.append(row_cells)
if span:
row_attrs = [] # type: List[Dict[str, str]]
table_attrs.append(row_attrs)
row_attrs_append = row_attrs.append
for m in match_row:
header = m['sep'] == b'!'
ms, me = m.span()
cell_span = [ss + ms, ss + me, None, shadow[ms:me]]
if span:
s, e = m.span('attrs')
# Note: ATTRS_MATCH always matches, even to empty strings.
# Also ATTRS_MATCH should match against the cell string
# so that it can be used easily as cache later in Cells.
attrs_match = ATTRS_MATCH(shadow[ms:me], s - ms, e - ms)
captures = attrs_match.captures
# noinspection PyUnboundLocalVariable
row_attrs_append(
dict(
zip(captures('attr_name'), captures('attr_value'))
)
)
old_span = next((s for s in spans if s == cell_span), None)
if old_span is None:
insort_right(spans, cell_span)
else:
cell_span = old_span
row_cells.append(
Cell(
self._lststr,
header,
type_to_spans,
cell_span,
type_,
m,
attrs_match,
)
)
if table_cells and span:
table_cells = _apply_attr_spans(table_attrs, table_cells)
if row is None:
if column is None:
return table_cells
return [r[column] for r in table_cells]
if column is None:
return table_cells[row]
return table_cells[row][column]
@property
def caption(self) -> str | None:
"""Caption of the table. Support get and set."""
m = CAPTION_MATCH(self._shadow)
if m:
return self(*m.span('caption'))
return None
@caption.setter
def caption(self, newcaption: str) -> None:
shadow = self._shadow
m = CAPTION_MATCH(shadow)
if m:
s = m.end('attrs')
self[s if s != -1 else m.end('preattrs') : m.end('caption')] = (
newcaption
)
return
# There is no caption. Create one.
h, s, t = shadow.partition(b'\n')
# Insert caption after the first one.
self.insert(len(h + s), '|+' + newcaption + '\n')
@property
def _attrs_match(self) -> Any:
cache_match, cache_string = self._attrs_match_cache
string = self.string
if cache_string == string:
return cache_match
shadow = self._shadow
attrs_match = ATTRS_MATCH(shadow, 2, shadow.find(10)) # ord('\n')
self._attrs_match_cache = attrs_match, string
return attrs_match
@property
def caption_attrs(self) -> str | None:
"""Caption attributes. Support get and set operations."""
m = CAPTION_MATCH(self._shadow)
if m:
s, e = m.span('attrs')
if s != -1:
return self(s, e)
return None
@caption_attrs.setter
def caption_attrs(self, attrs: str) -> None:
shadow = self._shadow
h, s, t = shadow.partition(b'\n')
m = CAPTION_MATCH(shadow)
if not m: # There is no caption-line
self.insert(len(h + s), '|+' + attrs + '|\n')
else: # Caption and attrs or Caption but no attrs
end = m.end('attrs')
if end != -1:
self[m.end('preattrs') : end] = attrs
@property
def row_attrs(self) -> list[dict]:
"""Row attributes.
Use the setter of this property to set attributes for all rows.
Note that it will overwrite all the existing attr values.
"""
shadow = self._table_shadow
string = self.string
attrs = []
append = attrs.append
for row_match in FIND_ROWS(shadow):
s, e = row_match.span(1)
spans = ATTRS_MATCH(shadow, s, e).spans
append(
{
string[ns:ne]: string[vs:ve]
for (ns, ne), (vs, ve) in zip(
spans('attr_name'), spans('attr_value')
)
}
)
return attrs
@row_attrs.setter
def row_attrs(self, attrs: list[Mapping]):
for row_match, attrs_dict in reversed(
[*zip(FIND_ROWS(self._table_shadow), attrs)]
):
s, e = row_match.span(1)
del self[s:e]
self.insert(
s,
''.join(
[
f' {name}="{value}"' if value else f' {name}'
for name, value in attrs_dict.items()
]
),
)
|
class Table(SubWikiTextWithAttrs):
def __init__(self, *args, **kwargs):
pass
@property
def nesting_level(self) -> int:
'''Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Table increases
the level by one.
'''
pass
@property
def _table_shadow(self) -> bytearray:
'''Remove Table spans from shadow and return it.'''
pass
@property
def _match_table(self) -> list[list[Any]]:
'''Return match_table.'''
pass
def data(
self,
span: bool = True,
strip: bool = True,
row: int = None,
column: int = None,
) -> list[list[str]] | list[str] | str:
'''Return a list containing lists of row values.
:param span: If true, calculate rows according to rowspans and colspans
attributes. Otherwise ignore them.
:param row: Return the specified row only. Zero-based index.
:param column: Return the specified column only. Zero-based index.
:param strip: strip data values
Note: Due to the lots of complications that it may cause, this function
won't look inside templates, parser functions, etc.
See https://www.mediawiki.org/wiki/Extension:Pipe_Escape for how
wiki-tables can be inserted within templates.
'''
pass
def cells(
self,
row: int = None,
column: int = None,
span: bool = True,
) -> list[list[Cell]] | list[Cell] | Cell:
'''Return a list of lists containing Cell objects.
:param span: If is True, rearrange the result according to colspan and
rospan attributes.
:param row: Return the specified row only. Zero-based index.
:param column: Return the specified column only. Zero-based index.
If both row and column are provided, return the relevant cell object.
If only need the values inside cells, then use the ``data`` method
instead.
'''
pass
@property
def caption(self) -> str | None:
'''Caption of the table. Support get and set.'''
pass
@caption.setter
def caption(self) -> str | None:
pass
@property
def _attrs_match(self) -> Any:
pass
@property
def caption_attrs(self) -> str | None:
'''Caption attributes. Support get and set operations.'''
pass
@caption_attrs.setter
def caption_attrs(self) -> str | None:
pass
@property
def row_attrs(self) -> list[dict]:
'''Row attributes.
Use the setter of this property to set attributes for all rows.
Note that it will overwrite all the existing attr values.
'''
pass
@row_attrs.setter
def row_attrs(self) -> list[dict]:
pass
| 24 | 8 | 23 | 1 | 19 | 5 | 4 | 0.25 | 1 | 13 | 1 | 0 | 13 | 1 | 13 | 72 | 320 | 20 | 253 | 105 | 218 | 62 | 186 | 84 | 172 | 13 | 3 | 5 | 56 |
1,101 |
5j9/wikitextparser
|
wikitextparser/_tag.py
|
wikitextparser._tag.Tag
|
class Tag(SubWikiTextWithAttrs):
__slots__ = '_match_cache'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._match_cache = None, None
@property
def _match(self) -> Any:
"""Return the match object for the current tag. Cache the result."""
cached_match, cached_string = self._match_cache
string = self.string
if cached_string == string:
return cached_match
match = TAG_FULLMATCH(self._shadow)
self._match_cache = match, string
return match
_attrs_match = _match
@property
def name(self) -> str:
"""Tag's name. Support both get and set operations."""
return self._match['name'].decode()
@name.setter
def name(self, name: str) -> None:
# The name in the end tag should be replaced first because the spans
# of the match object change after each replacement.
span = self._match.span
start, end = span('end_name')
if start != -1:
self[start:end] = name
start, end = span('name')
self[start:end] = name
@property
def contents(self) -> str | None:
"""Tag contents. Support both get and set operations.
setter:
Set contents to a new value.
Note that if the tag is self-closing, then it will be expanded to
have a start tag and an end tag. For example:
>>> t = Tag('<t/>')
>>> t.contents = 'n'
>>> t.string
'<t>n</t>'
"""
s, e = self._match.span('contents')
return self(s, e)
@contents.setter
def contents(self, contents: str) -> None:
match = self._match
start, end = match.span('contents')
if start != -1:
self[start:end] = contents
else:
# This is a self-closing tag.
self[-1:] = f'>{contents}</{match["name"].decode()}>'
@property
def parsed_contents(self) -> SubWikiText:
"""Return the contents as a SubWikiText object."""
ss, _, _, byte_array = self._span_data
s, e = self._match.span('contents')
tts = self._type_to_spans
spans = tts.setdefault('SubWikiText', [])
ps, pe = span_tuple = ss + s, ss + e
try:
i = [(s[0], s[1]) for s in spans].index(span_tuple)
except ValueError:
span = [ps, pe, None, byte_array[s:e]]
spans.append(span)
spans.sort()
else:
span = spans[i]
return SubWikiText(self._lststr, tts, span, 'SubWikiText')
@property
def _extension_tags(self):
return super()._extension_tags[1:]
def get_tags(self, name=None) -> list[Tag]:
return super().get_tags(name)[1:]
@property
def _content_span(self) -> tuple[int, int]:
s = self.string
return s.find('>') + 1, s.rfind('<')
|
class Tag(SubWikiTextWithAttrs):
def __init__(self, *args, **kwargs):
pass
@property
def _match(self) -> Any:
'''Return the match object for the current tag. Cache the result.'''
pass
@property
def name(self) -> str:
'''Tag's name. Support both get and set operations.'''
pass
@name.setter
def name(self) -> str:
pass
@property
def contents(self) -> str | None:
'''Tag contents. Support both get and set operations.
setter:
Set contents to a new value.
Note that if the tag is self-closing, then it will be expanded to
have a start tag and an end tag. For example:
>>> t = Tag('<t/>')
>>> t.contents = 'n'
>>> t.string
'<t>n</t>'
'''
pass
@contents.setter
def contents(self) -> str | None:
pass
@property
def parsed_contents(self) -> SubWikiText:
'''Return the contents as a SubWikiText object.'''
pass
@property
def _extension_tags(self):
pass
def get_tags(self, name=None) -> list[Tag]:
pass
@property
def _content_span(self) -> tuple[int, int]:
pass
| 19 | 4 | 7 | 0 | 5 | 2 | 1 | 0.25 | 1 | 7 | 0 | 0 | 10 | 1 | 10 | 69 | 91 | 12 | 63 | 38 | 44 | 16 | 54 | 30 | 43 | 2 | 3 | 1 | 14 |
1,102 |
5j9/wikitextparser
|
wikitextparser/_template.py
|
wikitextparser._template.Template
|
class Template(SubWikiTextWithArgs):
"""Convert strings to Template objects.
The string should start with {{ and end with }}.
"""
__slots__ = ()
_name_args_matcher = TL_NAME_ARGS_FULLMATCH
_first_arg_sep = 124
@property
def _content_span(self) -> tuple[int, int]:
return 2, -2
def normal_name(
self,
rm_namespaces=('Template',),
*,
code: str | None = None,
capitalize=False,
) -> str:
"""Return normal form of self.name.
- Remove comments.
- Remove language code.
- Remove namespace ("template:" or any of `localized_namespaces`.
- Use space instead of underscore.
- Remove consecutive spaces.
- Use uppercase for the first letter if `capitalize`.
- Remove #anchor.
:param rm_namespaces: is used to provide additional localized
namespaces for the template namespace. They will be removed from
the result. Default is ('Template',).
:param capitalize: If True, convert the first letter of the
template's name to a capital letter. See
[[mw:Manual:$wgCapitalLinks]] for more info.
:param code: is the language code.
Example:
>>> Template(
... '{{ eN : tEmPlAtE : <!-- c --> t_1 # b | a }}'
... ).normal_name(code='en')
'T 1'
"""
# Remove comments
name = COMMENT_SUB('', self.name).strip(WS)
# Remove code
if code:
head, sep, tail = name.partition(':')
if not head and sep:
name = tail.strip(' ')
head, sep, tail = name.partition(':')
if code.lower() == head.strip(' ').lower():
name = tail.strip(' ')
# Remove namespace
head, sep, tail = name.partition(':')
if not head and sep:
name = tail.strip(' ')
head, sep, tail = name.partition(':')
if head:
ns = head.strip(' ').lower()
for namespace in rm_namespaces:
if namespace.lower() == ns:
name = tail.strip(' ')
break
# Use space instead of underscore
name = name.replace('_', ' ')
if capitalize:
# Use uppercase for the first letter
name = name[:1].upper() + name[1:]
# Remove #anchor
name, sep, tail = name.partition('#')
return ' '.join(name.split())
def rm_first_of_dup_args(self) -> None:
"""Eliminate duplicate arguments by removing the first occurrences.
Remove the first occurrences of duplicate arguments, regardless of
their value. Result of the rendered wikitext should remain the same.
Warning: Some meaningful data may be removed from wikitext.
Also see `rm_dup_args_safe` function.
"""
names = set() # type: set
for a in reversed(self.arguments):
name = a.name.strip(WS)
if name in names:
del a[: len(a.string)]
else:
names.add(name)
def rm_dup_args_safe(self, tag: str | None = None) -> None:
"""Remove duplicate arguments in a safe manner.
Remove the duplicate arguments only in the following situations:
1. Both arguments have the same name AND value. (Remove one of
them.)
2. Arguments have the same name and one of them is empty. (Remove
the empty one.)
Warning: Although this is considered to be safe and no meaningful data
is removed from wikitext, but the result of the rendered wikitext
may actually change if the second arg is empty and removed but
the first had had a value.
If `tag` is defined, it should be a string that will be appended to
the value of the remaining duplicate arguments.
Also see `rm_first_of_dup_args` function.
"""
name_to_lastarg_vals: dict[str, tuple[Argument, list[str]]] = {}
# Removing positional args affects their name. By reversing the list
# we avoid encountering those kind of args.
for arg in reversed(self.arguments):
name = arg.name.strip(WS)
if arg.positional:
# Value of keyword arguments is automatically stripped by MW.
val = arg.value
else:
# But it's not OK to strip whitespace in positional arguments.
val = arg.value.strip(WS)
if name in name_to_lastarg_vals:
# This is a duplicate argument.
if not val:
# This duplicate argument is empty. It's safe to remove it.
del arg[0 : len(arg.string)]
else:
# Try to remove any of the detected duplicates of this
# that are empty or their value equals to this one.
lastarg, dup_vals = name_to_lastarg_vals[name]
if val in dup_vals:
del arg[0 : len(arg.string)]
elif '' in dup_vals:
# This happens only if the last occurrence of name has
# been an empty string; other empty values will
# be removed as they are seen.
# In other words index of the empty argument in
# dup_vals is always 0.
del lastarg[0 : len(lastarg.string)]
dup_vals.pop(0)
else:
# It was not possible to remove any of the duplicates.
dup_vals.append(val)
if tag:
arg.value += tag
else:
name_to_lastarg_vals[name] = (arg, [val])
def set_arg(
self,
name: str,
value: str,
positional: bool | None = None,
before: str | None = None,
after: str | None = None,
preserve_spacing=False,
) -> None:
"""Set the value for `name` argument. Add it if it doesn't exist.
- Use `positional`, `before` and `after` keyword arguments only when
adding a new argument.
- If `before` is given, ignore `after`.
- If neither `before` nor `after` are given and it's needed to add a
new argument, then append the new argument to the end.
- If `positional` is True, try to add the given value as a positional
argument. Ignore `preserve_spacing` if positional is True.
If it's None, do what seems more appropriate.
"""
args = (*reversed(self.arguments),)
arg = get_arg(name, args)
# Updating an existing argument.
if arg:
if positional:
arg.positional = positional
if preserve_spacing:
val = arg.value
arg.value = val.replace(val.strip(WS), value, 1)
else:
arg.value = value
return
# Adding a new argument
if not name and positional is None:
positional = True
# Calculate the whitespace needed before arg-name and after arg-value.
if not positional and preserve_spacing and args:
before_names = []
name_lengths = []
before_values = []
after_values = []
for arg in args:
aname = arg.name
name_len = len(aname)
name_lengths.append(name_len)
before_names.append(STARTING_WS_MATCH(aname)[0])
arg_value = arg.value
before_values.append(STARTING_WS_MATCH(arg_value)[0])
after_values.append(ENDING_WS_MATCH(arg_value)[0])
pre_name_ws_mode = mode(before_names)
name_length_mode = mode(name_lengths)
post_value_ws_mode = mode(
[SPACE_AFTER_SEARCH(self.string)[0]] + after_values[1:]
)
pre_value_ws_mode = mode(before_values)
else:
preserve_spacing = False
# Calculate the string that needs to be added to the Template.
if positional:
# Ignore preserve_spacing for positional args.
addstring = '|' + value
else:
if preserve_spacing:
# noinspection PyUnboundLocalVariable
addstring = (
'|'
+ (pre_name_ws_mode + name.strip(WS)).ljust(
name_length_mode
)
+ '='
+ pre_value_ws_mode
+ value
+ post_value_ws_mode
)
else:
addstring = '|' + name + '=' + value
# Place the addstring in the right position.
if before:
arg = get_arg(before, args)
arg.insert(0, addstring)
elif after:
arg = get_arg(after, args)
arg.insert(len(arg.string), addstring)
else:
if args and not positional:
arg = args[0]
arg_string = arg.string
if preserve_spacing:
# Insert after the last argument.
# The addstring needs to be recalculated because we don't
# want to change the the whitespace before final braces.
# noinspection PyUnboundLocalVariable
arg[0 : len(arg_string)] = (
arg.string.rstrip(WS)
+ post_value_ws_mode
+ addstring.rstrip(WS)
+ after_values[0]
)
else:
arg.insert(len(arg_string), addstring)
else:
# The template has no arguments or the new arg is
# positional AND is to be added at the end of the template.
self.insert(-2, addstring)
def get_arg(self, name: str) -> Argument | None:
"""Return the last argument with the given name.
Return None if no argument with that name is found.
"""
return get_arg(name, reversed(self.arguments))
def has_arg(self, name: str, value: str | None = None) -> bool:
"""Return true if the is an arg named `name`.
Also check equality of values if `value` is provided.
Note: If you just need to get an argument and you want to LBYL, it's
better to get_arg directly and then check if the returned value
is None.
"""
for arg in reversed(self.arguments):
if arg.name.strip(WS) == name.strip(WS):
if value:
if arg.positional:
if arg.value == value:
return True
return False
if arg.value.strip(WS) == value.strip(WS):
return True
return False
return True
return False
def del_arg(self, name: str) -> None:
"""Delete all arguments with the given then."""
for arg in reversed(self.arguments):
if arg.name.strip(WS) == name.strip(WS):
del arg[:]
@property
def templates(self) -> list[Template]:
return super().templates[1:]
|
class Template(SubWikiTextWithArgs):
'''Convert strings to Template objects.
The string should start with {{ and end with }}.
'''
@property
def _content_span(self) -> tuple[int, int]:
pass
def normal_name(
self,
rm_namespaces=('Template',),
*,
code:
'''Return normal form of self.name.
- Remove comments.
- Remove language code.
- Remove namespace ("template:" or any of `localized_namespaces`.
- Use space instead of underscore.
- Remove consecutive spaces.
- Use uppercase for the first letter if `capitalize`.
- Remove #anchor.
:param rm_namespaces: is used to provide additional localized
namespaces for the template namespace. They will be removed from
the result. Default is ('Template',).
:param capitalize: If True, convert the first letter of the
template's name to a capital letter. See
[[mw:Manual:$wgCapitalLinks]] for more info.
:param code: is the language code.
Example:
>>> Template(
... '{{ eN : tEmPlAtE : <!-- c --> t_1 # b | a }}'
... ).normal_name(code='en')
'T 1'
'''
pass
def rm_first_of_dup_args(self) -> None:
'''Eliminate duplicate arguments by removing the first occurrences.
Remove the first occurrences of duplicate arguments, regardless of
their value. Result of the rendered wikitext should remain the same.
Warning: Some meaningful data may be removed from wikitext.
Also see `rm_dup_args_safe` function.
'''
pass
def rm_dup_args_safe(self, tag: str | None = None) -> None:
'''Remove duplicate arguments in a safe manner.
Remove the duplicate arguments only in the following situations:
1. Both arguments have the same name AND value. (Remove one of
them.)
2. Arguments have the same name and one of them is empty. (Remove
the empty one.)
Warning: Although this is considered to be safe and no meaningful data
is removed from wikitext, but the result of the rendered wikitext
may actually change if the second arg is empty and removed but
the first had had a value.
If `tag` is defined, it should be a string that will be appended to
the value of the remaining duplicate arguments.
Also see `rm_first_of_dup_args` function.
'''
pass
def set_arg(
self,
name: str,
value: str,
positional: bool | None = None,
before: str | None = None,
after: str | None = None,
preserve_spacing=False,
) -> None:
'''Set the value for `name` argument. Add it if it doesn't exist.
- Use `positional`, `before` and `after` keyword arguments only when
adding a new argument.
- If `before` is given, ignore `after`.
- If neither `before` nor `after` are given and it's needed to add a
new argument, then append the new argument to the end.
- If `positional` is True, try to add the given value as a positional
argument. Ignore `preserve_spacing` if positional is True.
If it's None, do what seems more appropriate.
'''
pass
def get_arg(self, name: str) -> Argument | None:
'''Return the last argument with the given name.
Return None if no argument with that name is found.
'''
pass
def has_arg(self, name: str, value: str | None = None) -> bool:
'''Return true if the is an arg named `name`.
Also check equality of values if `value` is provided.
Note: If you just need to get an argument and you want to LBYL, it's
better to get_arg directly and then check if the returned value
is None.
'''
pass
def del_arg(self, name: str) -> None:
'''Delete all arguments with the given then.'''
pass
@property
def templates(self) -> list[Template]:
pass
| 12 | 8 | 30 | 1 | 18 | 11 | 5 | 0.58 | 1 | 10 | 1 | 0 | 9 | 0 | 9 | 69 | 293 | 25 | 171 | 59 | 145 | 99 | 125 | 43 | 115 | 13 | 3 | 5 | 46 |
1,103 |
5j9/wikitextparser
|
wikitextparser/_wikilink.py
|
wikitextparser._wikilink.WikiLink
|
class WikiLink(SubWikiText):
__slots__ = '_cached_match'
@property
def _content_span(self) -> tuple[int, int]:
s = self.string
f = s.find
rf = s.rfind
return f('[', f('[') + 1) + 1, rf(']', None, rf(']'))
@property
def _match(self) -> Match[bytes]:
shadow = self._shadow
cached_match = getattr(self, '_cached_match', None)
if cached_match is not None and cached_match.string == shadow:
return cached_match
self._cached_match = match = FULLMATCH(shadow)
return match # type: ignore
@property
def target(self) -> str:
"""WikiLink's target, including the fragment.
Do not include the pipe (|) in setter and getter.
Deleter: delete the link target, including the pipe character.
Use `self.target = ''` if you don't want to remove the pipe.
"""
b, e = self._match.span(1)
return self(b, e)
@target.setter
def target(self, s: str) -> None:
b, e = self._match.span(1)
self[b:e] = s
@target.deleter
def target(self) -> None:
m = self._match
b, e = m.span(1)
if m[4] is None:
del self[b:e]
return
del self[b : e + 1]
@property
def text(self) -> str | None:
"""The [[inner text| of WikiLink ]] (not including the [[link]]trail).
setter: set a new value for self.text. Do not include the pipe.
deleter: delete self.text, including the pipe.
"""
b, e = self._match.span(4)
if b == -1:
return None
return self(b, e)
@text.setter
def text(self, s: str) -> None:
m = self._match
b, e = m.span(4)
if b == -1:
self.insert(m.end(1), '|' + s)
return
self[b:e] = s
@text.deleter
def text(self):
b, e = self._match.span(4)
if b == -1:
return
del self[b - 1 : e]
@property
def fragment(self) -> str | None:
"""Fragment identifier.
getter: target's fragment identifier (do not include the # character)
setter: set a new fragment (do not include the # character)
deleter: delete fragment, including the # character.
"""
b, e = self._match.span(3)
if b == -1:
return None
return self(b, e)
@fragment.setter
def fragment(self, s: str):
m = self._match
b, e = m.span(3)
if b == -1:
self.insert(m.end(2), '#' + s)
return
self[b:e] = s
@fragment.deleter
def fragment(self):
b, e = self._match.span(3)
if b == -1:
return
del self[b - 1 : e]
@property
def title(self) -> str:
"""Target's title
getter: get target's title (do not include the # character)
setter: set a new title (do not include the # character)
deleter: return new title, including the # character.
"""
s, e = self._match.span(2)
return self(s, e)
@title.setter
def title(self, s) -> None:
b, e = self._match.span(2)
self[b:e] = s
@title.deleter
def title(self) -> None:
m = self._match
s, e = m.span(2)
if m[3] is None:
del self[s:e]
else:
del self[s : e + 1]
@property
def wikilinks(self) -> list[WikiLink]:
return super().wikilinks[1:]
|
class WikiLink(SubWikiText):
@property
def _content_span(self) -> tuple[int, int]:
pass
@property
def _match(self) -> Match[bytes]:
pass
@property
def target(self) -> str:
'''WikiLink's target, including the fragment.
Do not include the pipe (|) in setter and getter.
Deleter: delete the link target, including the pipe character.
Use `self.target = ''` if you don't want to remove the pipe.
'''
pass
@target.setter
def target(self) -> str:
pass
@target.deleter
def target(self) -> str:
pass
@property
def text(self) -> str | None:
'''The [[inner text| of WikiLink ]] (not including the [[link]]trail).
setter: set a new value for self.text. Do not include the pipe.
deleter: delete self.text, including the pipe.
'''
pass
@text.setter
def text(self) -> str | None:
pass
@text.deleter
def text(self) -> str | None:
pass
@property
def fragment(self) -> str | None:
'''Fragment identifier.
getter: target's fragment identifier (do not include the # character)
setter: set a new fragment (do not include the # character)
deleter: delete fragment, including the # character.
'''
pass
@fragment.setter
def fragment(self) -> str | None:
pass
@fragment.deleter
def fragment(self) -> str | None:
pass
@property
def title(self) -> str:
'''Target's title
getter: get target's title (do not include the # character)
setter: set a new title (do not include the # character)
deleter: return new title, including the # character.
'''
pass
@title.setter
def title(self) -> str:
pass
@title.deleter
def title(self) -> str:
pass
@property
def wikilinks(self) -> list[WikiLink]:
pass
| 31 | 4 | 6 | 0 | 5 | 1 | 2 | 0.23 | 1 | 6 | 0 | 0 | 15 | 1 | 15 | 69 | 129 | 19 | 91 | 54 | 60 | 21 | 75 | 39 | 59 | 2 | 2 | 1 | 24 |
1,104 |
5j9/wikitextparser
|
wikitextparser/_wikilist.py
|
wikitextparser._wikilist.WikiList
|
class WikiList(SubWikiText):
"""Class to represent ordered, unordered, and definition lists."""
__slots__ = 'pattern', '_match_cache'
def __init__(
self,
string: str | MutableSequence[str],
pattern: str,
_match: Match | None = None,
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | None = None,
) -> None:
super().__init__(string, _type_to_spans, _span, _type)
self.pattern = pattern
if _match:
self._match_cache = _match, self.string
else:
self._match_cache = (
fullmatch(
LIST_PATTERN_FORMAT.replace(
b'{pattern}', pattern.encode(), 1
),
self._list_shadow,
MULTILINE,
),
self.string,
)
@property
def _list_shadow(self):
shadow_copy = self._shadow[:]
if ':' in self.pattern:
for m in EXTERNAL_LINK_FINDITER(shadow_copy):
s, e = m.span()
shadow_copy[s:e] = b'_' * (e - s)
return shadow_copy
@property
def _match(self) -> Match[bytes]:
"""Return the match object for the current list."""
cache_match, cache_string = self._match_cache
string = self.string
if cache_string == string:
return cache_match # type: ignore
cache_match = fullmatch(
LIST_PATTERN_FORMAT.replace(
b'{pattern}', self.pattern.encode(), 1
),
self._list_shadow,
MULTILINE,
)
self._match_cache = cache_match, string
return cache_match # type: ignore
@property
def items(self) -> list[str]:
"""Return items as a list of strings.
Do not include sub-items and the start pattern.
"""
items: list[str] = []
append = items.append
string = self.string
match = self._match
ms = match.start()
for s, e in match.spans('item'):
append(string[s - ms : e - ms])
return items
@property
def fullitems(self) -> list[str]:
"""Return list of item strings. Includes their start and sub-items."""
fullitems: list[str] = []
append = fullitems.append
string = self.string
match = self._match
ms = match.start()
# Sort because "fullitem" can be flipped compared to "items" in case
# of a definition list with the LIST_PATTERN_FORMAT regex.
for s, e in sorted(match.spans('fullitem')):
append(string[s - ms : e - ms])
return fullitems
@property
def level(self) -> int:
"""Return level of nesting for the current list.
Level is a one-based index, for example the level for `* a` will be 1.
"""
return len(self._match['pattern'])
def sublists(
self,
i: int | None = None,
pattern: str | Iterable[str] = (r'\#', r'\*', '[:;]'),
) -> list[WikiList]:
"""Return the Lists inside the item with the given index.
:param i: The index of the item which its sub-lists are desired.
:param pattern: The starting symbol for the desired sub-lists.
The `pattern` of the current list will be automatically added
as prefix.
"""
if isinstance(pattern, str):
patterns = (pattern,)
else:
patterns = pattern
self_pattern = self.pattern
get_lists = super().get_lists
sublists: list[WikiList] = []
sublists_append = sublists.append
if i is None:
# Any sublist is acceptable
for pattern in patterns:
for lst in get_lists(self_pattern + pattern):
sublists_append(lst)
else:
# Only return sub-lists that are within the given item
match = self._match
fullitem_spans = match.spans('fullitem')
ss = self._span_data[0]
ms = match.start()
s, e = fullitem_spans[i]
e -= ms - ss
s -= ms - ss
for pattern in patterns:
for lst in get_lists(self_pattern + pattern):
# noinspection PyProtectedMember
ls, le, _, _ = lst._span_data
if s <= ls and le <= e:
sublists_append(lst)
sublists.sort(key=attrgetter('_span_data'))
return sublists
def convert(self, newstart: str) -> None:
"""Convert to another list type by replacing starting pattern."""
match = self._match
ms = match.start()
for s, e in reversed(match.spans('pattern')):
self[s - ms : e - ms] = newstart
self.pattern = escape(newstart)
def get_lists(
self, pattern: str | Iterable[str] = (r'\#', r'\*', '[:;]')
) -> list[WikiList]:
return self.sublists(pattern=pattern)
|
class WikiList(SubWikiText):
'''Class to represent ordered, unordered, and definition lists.'''
def __init__(
self,
string: str | MutableSequence[str],
pattern: str,
_match: Match | None = None,
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | None = None,
) -> None:
pass
@property
def _list_shadow(self):
pass
@property
def _match(self) -> Match[bytes]:
'''Return the match object for the current list.'''
pass
@property
def items(self) -> list[str]:
'''Return items as a list of strings.
Do not include sub-items and the start pattern.
'''
pass
@property
def fullitems(self) -> list[str]:
'''Return list of item strings. Includes their start and sub-items.'''
pass
@property
def level(self) -> int:
'''Return level of nesting for the current list.
Level is a one-based index, for example the level for `* a` will be 1.
'''
pass
def sublists(
self,
i: int | None = None,
pattern: str | Iterable[str] = (r'\#', r'\*', '[:;]'),
) -> list[WikiList]:
'''Return the Lists inside the item with the given index.
:param i: The index of the item which its sub-lists are desired.
:param pattern: The starting symbol for the desired sub-lists.
The `pattern` of the current list will be automatically added
as prefix.
'''
pass
def convert(self, newstart: str) -> None:
'''Convert to another list type by replacing starting pattern.'''
pass
def get_lists(
self, pattern: str | Iterable[str] = (r'\#', r'\*', '[:;]')
) -> list[WikiList]:
pass
| 15 | 7 | 14 | 0 | 12 | 3 | 3 | 0.22 | 1 | 7 | 0 | 0 | 9 | 2 | 9 | 63 | 148 | 13 | 114 | 64 | 85 | 25 | 77 | 45 | 67 | 8 | 2 | 4 | 23 |
1,105 |
5j9/wikitextparser
|
wikitextparser/_wikitext.py
|
wikitextparser._wikitext.DeadIndexError
|
class DeadIndexError(TypeError):
pass
|
class DeadIndexError(TypeError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
1,106 |
5j9/wikitextparser
|
wikitextparser/_wikitext.py
|
wikitextparser._wikitext.SubWikiText
|
class SubWikiText(WikiText):
"""Define a class to be inherited by some subclasses of WikiText.
Allow focusing on a particular part of WikiText.
"""
__slots__ = '_type'
def __init__(
self,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list | None = None,
_type: str | int | None = None,
) -> None:
"""Initialize the object."""
if _type is None:
# assert _span is None
# assert _type_to_spans is None
# https://youtrack.jetbrains.com/issue/PY-29770
# noinspection PyDunderSlots,PyUnresolvedReferences
self._type = _type = type(self).__name__
super().__init__(string)
else:
# assert _span is not None
# assert _type_to_spans is not None
# https://youtrack.jetbrains.com/issue/PY-29770
# noinspection PyDunderSlots,PyUnresolvedReferences
self._type = _type
super().__init__(string, _type_to_spans)
self._span_data: list = _span # type: ignore
def _subspans(self, type_: str) -> list[list[int]]:
"""Yield all the sub-span indices excluding self._span."""
ss, se, _, _ = self._span_data
spans = self._type_to_spans[type_]
# Do not yield self._span by bisecting for s < ss.
# The second bisect is an optimization and should be on [se + 1],
# but empty spans are not desired thus [se] is used.
b = bisect_left(spans, [ss])
return [
span
for span in spans[b : bisect_right(spans, [se], b)]
if span[1] <= se
]
def ancestors(self, type_: str | None = None) -> list[WikiText]:
"""Return the ancestors of the current node.
:param type_: the type of the desired ancestors as a string.
Currently the following types are supported: {Template,
ParserFunction, WikiLink, Comment, Parameter, ExtensionTag}.
The default is None and means all the ancestors of any type above.
"""
if type_ is None:
types = SPAN_PARSER_TYPES
else:
types = (type_,)
lststr = self._lststr
type_to_spans = self._type_to_spans
ss, se, _, _ = self._span_data
ancestors = []
ancestors_append = ancestors.append
for type_ in types:
cls = globals()[type_]
spans = type_to_spans[type_]
for span in spans[: bisect_right(spans, [ss])]:
if se < span[1]:
ancestors_append(cls(lststr, type_to_spans, span, type_))
return sorted(ancestors, key=lambda i: ss - i._span_data[0])
def parent(self, type_: str | None = None) -> WikiText | None:
"""Return the parent node of the current object.
:param type_: the type of the desired parent object.
Currently the following types are supported: {Template,
ParserFunction, WikiLink, Comment, Parameter, ExtensionTag}.
The default is None and means the first parent, of any type above.
:return: parent WikiText object or None if no parent with the desired
`type_` is found.
"""
ancestors = self.ancestors(type_)
if ancestors:
return ancestors[0]
return None
|
class SubWikiText(WikiText):
'''Define a class to be inherited by some subclasses of WikiText.
Allow focusing on a particular part of WikiText.
'''
def __init__(
self,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list | None = None,
_type: str | int | None = None,
) -> None:
'''Initialize the object.'''
pass
def _subspans(self, type_: str) -> list[list[int]]:
'''Yield all the sub-span indices excluding self._span.'''
pass
def ancestors(self, type_: str | None = None) -> list[WikiText]:
'''Return the ancestors of the current node.
:param type_: the type of the desired ancestors as a string.
Currently the following types are supported: {Template,
ParserFunction, WikiLink, Comment, Parameter, ExtensionTag}.
The default is None and means all the ancestors of any type above.
'''
pass
def parent(self, type_: str | None = None) -> WikiText | None:
'''Return the parent node of the current object.
:param type_: the type of the desired parent object.
Currently the following types are supported: {Template,
ParserFunction, WikiLink, Comment, Parameter, ExtensionTag}.
The default is None and means the first parent, of any type above.
:return: parent WikiText object or None if no parent with the desired
`type_` is found.
'''
pass
| 5 | 5 | 19 | 1 | 11 | 7 | 3 | 0.66 | 1 | 5 | 0 | 10 | 4 | 2 | 4 | 54 | 85 | 8 | 47 | 27 | 36 | 31 | 35 | 21 | 30 | 5 | 1 | 3 | 10 |
1,107 |
5j9/wikitextparser
|
wikitextparser/_tag.py
|
wikitextparser._tag.SubWikiTextWithAttrs
|
class SubWikiTextWithAttrs(SubWikiText):
"""Define a class for SubWikiText objects that have attributes.
Any class that is going to inherit from SubWikiTextWithAttrs should provide
_attrs_match property. Note that matching should be done on shadow.
It's usually a good idea to cache the _attrs_match property.
"""
__slots__ = '_attrs_match'
@property
def attrs(self) -> dict[str, str]:
"""Return self attributes as a dictionary."""
spans = self._attrs_match.spans
string = self.string
return dict(
zip(
(string[s:e] for s, e in spans('attr_name')),
(string[s:e] for s, e in spans('attr_value')),
)
)
def has_attr(self, attr_name: str) -> bool:
"""Return True if self contains an attribute with the given name."""
string = self.string
return attr_name in (
string[s:e] for s, e in self._attrs_match.spans('attr_name')
)
def get_attr(self, attr_name: str) -> str | None:
"""Return the value of the last attribute with the given name.
Return None if the attr_name does not exist in self.
If there are already multiple attributes with the given name, only
return the value of the last one.
Return an empty string if the mentioned name is an empty attribute.
"""
spans = self._attrs_match.spans
string = self.string
for i, (s, e) in enumerate(reversed(spans('attr_name'))):
if string[s:e] == attr_name:
s, e = spans('attr_value')[-i - 1]
return string[s:e]
return None
def set_attr(self, attr_name: str, attr_value: str) -> None:
"""Set the value for the given attribute name.
If there are already multiple attributes with the given name, only
set the value for the last one.
If attr_value == '', use the implicit empty attribute syntax.
"""
match = self._attrs_match
string = self.string
for i, (s, e) in enumerate(reversed(match.spans('attr_name'))):
if string[s:e] == attr_name:
vs, ve = match.spans('attr_value')[-i - 1]
q = 1 if match.string[ve] in b'"\'' else 0
self[vs - q : ve + q] = f'"{attr_value}"'
return
# The attr_name is new, add a new attribute.
self.insert(
match.end('attr_insert'),
f' {attr_name}="{attr_value}"' if attr_value else f' {attr_name}',
)
return
def del_attr(self, attr_name: str) -> None:
"""Delete all the attributes with the given name.
Pass if the attr_name is not found in self.
"""
match = self._attrs_match
string = self.string
# Must be done in reversed order because the spans
# change after each deletion.
for i, (s, e) in enumerate(reversed(match.spans('attr_name'))):
if string[s:e] == attr_name:
start, stop = match.spans('attr')[-i - 1]
del self[start:stop]
|
class SubWikiTextWithAttrs(SubWikiText):
'''Define a class for SubWikiText objects that have attributes.
Any class that is going to inherit from SubWikiTextWithAttrs should provide
_attrs_match property. Note that matching should be done on shadow.
It's usually a good idea to cache the _attrs_match property.
'''
@property
def attrs(self) -> dict[str, str]:
'''Return self attributes as a dictionary.'''
pass
def has_attr(self, attr_name: str) -> bool:
'''Return True if self contains an attribute with the given name.'''
pass
def get_attr(self, attr_name: str) -> str | None:
'''Return the value of the last attribute with the given name.
Return None if the attr_name does not exist in self.
If there are already multiple attributes with the given name, only
return the value of the last one.
Return an empty string if the mentioned name is an empty attribute.
'''
pass
def set_attr(self, attr_name: str, attr_value: str) -> None:
'''Set the value for the given attribute name.
If there are already multiple attributes with the given name, only
set the value for the last one.
If attr_value == '', use the implicit empty attribute syntax.
'''
pass
def del_attr(self, attr_name: str) -> None:
'''Delete all the attributes with the given name.
Pass if the attr_name is not found in self.
'''
pass
| 7 | 6 | 13 | 1 | 9 | 4 | 3 | 0.52 | 1 | 6 | 0 | 3 | 5 | 0 | 5 | 59 | 80 | 10 | 46 | 23 | 39 | 24 | 35 | 22 | 29 | 5 | 2 | 2 | 13 |
1,108 |
5j9/wikitextparser
|
wikitextparser/_comment_bold_italic.py
|
wikitextparser._comment_bold_italic.Bold
|
class Bold(BoldItalic):
__slots__ = ()
@property
def _match(self) -> Match[str]:
return BOLD_FULLMATCH(self.string)
|
class Bold(BoldItalic):
@property
def _match(self) -> Match[str]:
pass
| 3 | 0 | 2 | 0 | 2 | 1 | 1 | 0.2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 59 | 6 | 1 | 5 | 4 | 2 | 1 | 4 | 3 | 2 | 1 | 3 | 0 | 1 |
1,109 |
5j9/wikitextparser
|
wikitextparser/_parser_function.py
|
wikitextparser._parser_function.ParserFunction
|
class ParserFunction(SubWikiTextWithArgs):
__slots__ = ()
_name_args_matcher = PF_NAME_ARGS_FULLMATCH
_first_arg_sep = 58
@property
def parser_functions(self) -> list[ParserFunction]:
return super().parser_functions[1:]
|
class ParserFunction(SubWikiTextWithArgs):
@property
def parser_functions(self) -> list[ParserFunction]:
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 61 | 9 | 2 | 7 | 6 | 4 | 0 | 6 | 5 | 4 | 1 | 3 | 0 | 1 |
1,110 |
5j9/wikitextparser
|
wikitextparser/_argument.py
|
wikitextparser._argument.Argument
|
class Argument(SubWikiText):
"""Create a new Argument Object.
Note that in MediaWiki documentation `arguments` are (also) called
parameters. In this module the convention is:
{{{parameter}}}, {{template|argument}}.
See https://www.mediawiki.org/wiki/Help:Templates for more information.
"""
__slots__ = '_shadow_match_cache', '_parent'
def __init__(
self,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | int | None = None,
_parent: SubWikiTextWithArgs | None = None,
):
super().__init__(string, _type_to_spans, _span, _type)
self._parent = _parent or self
self._shadow_match_cache = None, None
@property
def _shadow_match(self) -> Match[bytes]:
cached_shadow_match, cache_string = self._shadow_match_cache
self_string = str(self)
if cache_string == self_string:
return cached_shadow_match # type: ignore
ss, se, _, _ = self._span_data
parent = self._parent
ps = parent._span_data[0]
shadow_match = ARG_SHADOW_FULLMATCH(parent._shadow[ss - ps : se - ps])
self._shadow_match_cache = shadow_match, self_string
return shadow_match # type: ignore
@property
def name(self) -> str:
"""Argument's name.
getter: return the position as a string, for positional arguments.
setter: convert it to keyword argument if positional.
"""
ss = self._span_data[0]
shadow_match = self._shadow_match
if shadow_match['eq']:
s, e = shadow_match.span('pre_eq')
return self._lststr[0][ss + s : ss + e]
# positional argument
position = 1
parent_find = self._parent._shadow.find
parent_start = self._parent._span_data[0]
for s, e, _, _ in self._type_to_spans[self._type]:
if ss <= s:
break
if parent_find(b'=', s - parent_start, e - parent_start) != -1:
# This is a keyword argument.
continue
# This is a preceding positional argument.
position += 1
return str(position)
@name.setter
def name(self, newname: str) -> None:
if self._shadow_match['eq']:
self[1 : 1 + len(self._shadow_match['pre_eq'])] = newname
else:
self.insert(1, newname + '=')
@property
def positional(self) -> bool:
"""True if self is positional, False if keyword.
setter:
If set to False, convert self to keyword argumentn.
Raise ValueError on trying to convert positional to keyword
argument.
"""
return False if self._shadow_match['eq'] else True
@positional.setter
def positional(self, to_positional: bool) -> None:
shadow_match = self._shadow_match
if shadow_match['eq']:
# Keyword argument
if to_positional:
del self[1 : shadow_match.end('eq')]
else:
return
if to_positional:
# Positional argument. to_positional is True.
return
# Positional argument. to_positional is False.
raise ValueError(
'Converting positional argument to keyword argument is not '
'possible without knowing the new name. '
'You can use `self.name = somename` instead.'
)
@property
def value(self) -> str:
"""Value of self.
Support both keyword or positional arguments.
getter:
Return value of self.
setter:
Assign a new value to self.
"""
shadow_match = self._shadow_match
if shadow_match['eq']:
return self(shadow_match.start('post_eq'), None)
return self(1, None)
@value.setter
def value(self, newvalue: str) -> None:
shadow_match = self._shadow_match
if shadow_match['eq']:
self[shadow_match.start('post_eq') :] = newvalue
else:
self[1:] = newvalue
@property
def _lists_shadow_ss(self):
shadow_match = self._shadow_match
if shadow_match['eq']:
post_eq = shadow_match['post_eq']
ls_post_eq = post_eq.lstrip()
return (
bytearray(ls_post_eq),
self._span_data[0]
+ shadow_match.start('post_eq')
+ len(post_eq)
- len(ls_post_eq),
)
return bytearray(shadow_match[0][1:]), self._span_data[0] + 1
|
class Argument(SubWikiText):
'''Create a new Argument Object.
Note that in MediaWiki documentation `arguments` are (also) called
parameters. In this module the convention is:
{{{parameter}}}, {{template|argument}}.
See https://www.mediawiki.org/wiki/Help:Templates for more information.
'''
def __init__(
self,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | int | None = None,
_parent: SubWikiTextWithArgs | None = None,
):
pass
@property
def _shadow_match(self) -> Match[bytes]:
pass
@property
def name(self) -> str:
'''Argument's name.
getter: return the position as a string, for positional arguments.
setter: convert it to keyword argument if positional.
'''
pass
@name.setter
def name(self) -> str:
pass
@property
def positional(self) -> bool:
'''True if self is positional, False if keyword.
setter:
If set to False, convert self to keyword argumentn.
Raise ValueError on trying to convert positional to keyword
argument.
'''
pass
@positional.setter
def positional(self) -> bool:
pass
@property
def value(self) -> str:
'''Value of self.
Support both keyword or positional arguments.
getter:
Return value of self.
setter:
Assign a new value to self.
'''
pass
@value.setter
def value(self) -> str:
pass
@property
def _lists_shadow_ss(self):
pass
| 18 | 4 | 12 | 0 | 9 | 3 | 2 | 0.33 | 1 | 8 | 0 | 0 | 9 | 2 | 9 | 63 | 136 | 14 | 93 | 47 | 68 | 31 | 65 | 32 | 55 | 5 | 2 | 2 | 22 |
1,111 |
5j9/wikitextparser
|
wikitextparser/_cell.py
|
wikitextparser._cell.Cell
|
class Cell(SubWikiTextWithAttrs):
__slots__ = '_header', '_match_cache', '_attrs_match_cache'
def __init__(
self,
string: str | MutableSequence[str],
header: bool = False,
_type_to_spans: TypeToSpans | None = None,
_span: list | None = None,
_type: int | None = None,
_match: Match | None = None,
_attrs_match: Match | None = None,
) -> None:
super().__init__(string, _type_to_spans, _span, _type)
self._header = header
if _match:
string = self.string
self._match_cache = _match, string
if _attrs_match:
self._attrs_match_cache = _attrs_match, string
else:
cell_start = _match.start()
attrs_start, attrs_end = _match.span('attrs')
self._attrs_match_cache = (
ATTRS_MATCH(
_match[0],
attrs_start - cell_start,
attrs_end - cell_start,
),
string,
)
else:
self._attrs_match_cache = self._match_cache = None, None
@property
def _match(self) -> Match[bytes]:
"""Return the match object for the current tag. Cache the result.
Be extra careful when using this property. The position of match
may be something other than zero if the match is cached from the
parent object (the initial value).
"""
cache_match, cache_string = self._match_cache
string = self.string
if cache_string == string:
return cache_match # type: ignore
shadow = self._shadow
if shadow[0] == 10: # ord('\n')
m = NEWLINE_CELL_MATCH(shadow)
self._header = m['sep'] == 33 # ord('!')
elif self._header:
m = INLINE_HAEDER_CELL_MATCH(shadow)
else:
m = INLINE_NONHAEDER_CELL_MATCH(shadow)
self._match_cache = m, string
self._attrs_match_cache = None, None
return m # type: ignore
@property
def value(self) -> str:
"""Cell's value.
getter: Return this cell's value.
setter: Assign new_value to self.
"""
m = self._match
offset = m.start()
s, e = m.span('data')
return self(s - offset, e - offset)
@value.setter
def value(self, new_value: str) -> None:
m = self._match
offset = m.start()
s, e = m.span('data')
self[s - offset : e - offset] = new_value
@property
def _attrs_match(self):
"""Return the match object for attributes."""
cache, cache_string = self._attrs_match_cache
string = self.string
if cache_string == string:
return cache
s, e = self._match.span('attrs')
attrs_match = ATTRS_MATCH(self._shadow, s, e)
self._attrs_match_cache = attrs_match, string
return attrs_match
def set_attr(self, attr_name: str, attr_value: str) -> None:
"""Set the value for the given attribute name.
If there are already multiple attributes with that name, only
set the value for the last one.
If attr_value == '', use the implicit empty attribute syntax.
"""
# Note: The set_attr method of the parent class cannot be used instead
# of this method because a cell could be without any attrs placeholder
# which means the appropriate piping should be added around attrs by
# this method. Also ATTRS_MATCH does not have any 'start' group.
cell_match = self._match
shadow = cell_match.string
attrs_start, attrs_end = cell_match.span('attrs')
if attrs_start != -1:
encoded_attr_name = attr_name.encode()
attrs_m = ATTRS_MATCH(shadow, attrs_start, attrs_end)
for i, n in enumerate(reversed(attrs_m.captures('attr_name'))):
if n == encoded_attr_name:
vs, ve = attrs_m.spans('attr_value')[-i - 1]
q = 1 if attrs_m.string[ve] in b'"\'' else 0
self[vs - q : ve + q] = f'"{attr_value}"'
return
# We have some attributes, but none of them is attr_name
attr_end = cell_match.end('attrs')
fmt = '{}="{}" ' if shadow[attr_end - 1] == 32 else ' {}="{}"'
self.insert(attr_end, fmt.format(attr_name, attr_value))
return
# There is no attributes span in this cell. Create one.
fmt = ' {}="{}" |' if attr_value else ' {} |'
if shadow[0] == 10: # ord('\n')
self.insert(
cell_match.start('sep') + 1, fmt.format(attr_name, attr_value)
)
return
# An inline cell
self.insert(2, fmt.format(attr_name, attr_value))
return
@property
def is_header(self) -> bool:
"""Return True if this is a header cell."""
return self._header
|
class Cell(SubWikiTextWithAttrs):
def __init__(
self,
string: str | MutableSequence[str],
header: bool = False,
_type_to_spans: TypeToSpans | None = None,
_span: list | None = None,
_type: int | None = None,
_match: Match | None = None,
_attrs_match: Match | None = None,
) -> None:
pass
@property
def _match(self) -> Match[bytes]:
'''Return the match object for the current tag. Cache the result.
Be extra careful when using this property. The position of match
may be something other than zero if the match is cached from the
parent object (the initial value).
'''
pass
@property
def value(self) -> str:
'''Cell's value.
getter: Return this cell's value.
setter: Assign new_value to self.
'''
pass
@value.setter
def value(self) -> str:
pass
@property
def _attrs_match(self):
'''Return the match object for attributes.'''
pass
def set_attr(self, attr_name: str, attr_value: str) -> None:
'''Set the value for the given attribute name.
If there are already multiple attributes with that name, only
set the value for the last one.
If attr_value == '', use the implicit empty attribute syntax.
'''
pass
@property
def is_header(self) -> bool:
'''Return True if this is a header cell.'''
pass
| 13 | 5 | 17 | 0 | 13 | 4 | 3 | 0.28 | 1 | 8 | 0 | 0 | 7 | 3 | 7 | 66 | 132 | 10 | 99 | 52 | 77 | 28 | 72 | 38 | 64 | 8 | 3 | 3 | 20 |
1,112 |
5monkeys/content-io
|
5monkeys_content-io/tests/__init__.py
|
tests.ReplacerPlugin
|
class ReplacerPlugin(BasePlugin):
ext = 'rpl'
def load_node(self, node):
node.uri = node.uri.clone(path="page/loaded.rpl")
node.content = "REPLACED"
return self.load(node.content)
def render_node(self, node, data):
node.uri = node.uri.clone(path="page/rendered.rpl")
return self.render(data)
|
class ReplacerPlugin(BasePlugin):
def load_node(self, node):
pass
def render_node(self, node, data):
pass
| 3 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 12 | 12 | 3 | 9 | 4 | 6 | 0 | 9 | 4 | 6 | 1 | 2 | 0 | 2 |
1,113 |
5monkeys/content-io
|
5monkeys_content-io/tests/__init__.py
|
tests.UppercasePlugin
|
class UppercasePlugin(BasePlugin):
ext = 'up'
def load(self, content):
try:
return json.loads(content) if content else None
except ValueError:
return content
def save(self, data):
if isinstance(data, dict):
return json.dumps(data)
else:
return json.dumps(dict(name=data))
def render(self, data):
name = data if isinstance(data, six.string_types) else data['name']
return name.upper()
|
class UppercasePlugin(BasePlugin):
def load(self, content):
pass
def save(self, data):
pass
def render(self, data):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 13 | 19 | 4 | 15 | 6 | 11 | 0 | 14 | 6 | 10 | 3 | 2 | 1 | 7 |
1,114 |
5monkeys/content-io
|
5monkeys_content-io/tests/test_api.py
|
tests.test_api.ApiTest
|
class ApiTest(BaseTest):
def setUp(self):
super(ApiTest, self).setUp()
from cio.conf import settings
settings.configure(
PLUGINS=[
'cio.plugins.txt.TextPlugin',
'cio.plugins.md.MarkdownPlugin',
'tests.UppercasePlugin'
]
)
def test_get(self):
node = cio.get('label/email', default=u'fallback')
self.assertEqual(node.content, u'fallback')
self.assertEqual(node.initial_uri, 'label/email')
self.assertEqual(node.uri, 'i18n://sv-se@label/email.txt')
def test_get_with_empty_default(self):
node = cio.get('page/title', default=u'', lazy=False)
self.assertEqual(node.content, u'')
node = cio.get('page/body', default=None, lazy=False)
self.assertIsNone(node.content)
# Testing same non existing uri's twice to assert cache handles None/"" default
node = cio.get('page/title', default=u'', lazy=False)
self.assertEqual(node.content, u'')
node = cio.get('page/body', default=None, lazy=False)
self.assertIsNone(node.content)
def test_get_with_context(self):
node = cio.get('page/title', default=u'{Welcome} {firstname} {lastname}!')
content = node.render(firstname=u'Jonas', lastname=u'Lundberg')
self.assertEqual(content, u'{Welcome} Jonas Lundberg!')
def test_get_with_local_cache_pipe_settings(self):
def assert_local_thread():
settings.configure(local=True, CACHE={'PIPE': {'CACHE_ON_GET': False}})
self.assertIn('BACKEND', settings.CACHE, 'Cache settings should be merged')
# Test twice so that not the first get() caches the reponse in pipeline
with self.assertCache(calls=1, misses=1, hits=0, sets=0):
cio.get('local/settings', default=u'default', lazy=False)
with self.assertCache(calls=1, misses=1, hits=0, sets=0):
cio.get('local/settings', default=u'default', lazy=False)
thread = threading.Thread(target=assert_local_thread)
thread.start()
thread.join()
# Back on main thread, settings should not be affected
# Test twice to make sure first get chaches the reponse in pipeline
with self.assertCache(calls=2, misses=1, hits=0, sets=1):
cio.get('local/settings', default=u'default', lazy=False)
with self.assertCache(calls=1, misses=0, hits=1, sets=0):
cio.get('local/settings', default=u'default', lazy=False)
def test_set(self):
with self.assertRaises(URI.Invalid):
cio.set('page/title', 'fail')
with self.assertRaises(URI.Invalid):
cio.set('page/title.txt', 'fail')
node = cio.set('i18n://sv-se@label/email.up', u'e-post')
self.assertEqual(node.uri, 'i18n://sv-se@label/email.up#1')
cache.clear()
node = cio.get('label/email', u'fallback')
self.assertEqual(node.content, u'E-POST')
self.assertEqual(node.uri, 'i18n://sv-se@label/email.up#1')
self.assertEqual(node.initial, u'fallback')
self.assertEqual(len(node.meta.keys()), 0) # No meta returned from non-versioned api get
self.assertEqual(repr(node._node), '<Node: i18n://sv-se@label/email.up#1>')
self.assertEqual(node.for_json(), {
'uri': node.uri,
'content': node.content,
'meta': node.meta
})
node = cio.set('sv-se@label/email', u'e-post', publish=False)
self.assertEqual(node.uri, 'i18n://sv-se@label/email.txt#draft')
self.assertKeys(node.meta, 'modified_at', 'is_published')
node = cio.publish(node.uri)
self.assertKeys(node.meta, 'modified_at', 'published_at', 'is_published')
self.assertTrue(node.meta['is_published'])
node = cio.get('label/email')
self.assertEqual(node.uri, 'i18n://sv-se@label/email.txt#2')
self.assertEqual(node.content, u'e-post')
self.assertEqual(node.uri.ext, 'txt')
self.assertEqual(len(node.meta.keys()), 0)
# Try publish non-existing node/uri
node = cio.publish('i18n://sv-se@foo/bar.txt#draft')
self.assertIsNone(node)
def test_delete(self):
with self.assertRaises(URI.Invalid):
cio.delete('foo/bar')
node = cio.set('i18n://sv-se@label/email.txt', u'e-post')
uri = node.uri
self.assertEqual(cache.get(uri)['content'], u'e-post')
uris = cio.delete('sv-se@label/email#1', 'sv-se@foo/bar')
self.assertListEqual(uris, ['sv-se@label/email#1'])
with self.assertRaises(NodeDoesNotExist):
storage.get(uri)
self.assertIsNone(cache.get(uri))
def test_revisions(self):
def assertRevisions(*revs):
revisions = set(cio.revisions('i18n://sv-se@page/title'))
assert revisions == set(revs)
self.assertEqual(len(set(cio.revisions('i18n://sv-se@page/title'))), 0)
node = cio.load('sv-se@page/title')
self.assertDictEqual(node, {
'uri': 'i18n://sv-se@page/title.txt',
'data': None,
'content': None,
'meta': {}
})
# First draft
with self.assertDB(selects=1, inserts=1, updates=0):
with self.assertCache(calls=0):
node = cio.set('i18n://sv-se@page/title.txt', u'Content-IO', publish=False)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.txt#draft')
assertRevisions(('i18n://sv-se@page/title.txt#draft', False))
self.assertIsNone(cio.get('page/title').content)
# Publish first draft, version 1
with self.assertDB(calls=4, selects=2, updates=2):
with self.assertCache(calls=1, sets=1):
node = cio.publish(node.uri)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.txt#1')
assertRevisions(('i18n://sv-se@page/title.txt#1', True))
self.assertEqual(cio.get('page/title').content, u'Content-IO')
# Second draft
with self.assertDB(selects=1, inserts=1, updates=0):
with self.assertCache(calls=0):
node = cio.set('i18n://sv-se@page/title.up', u'Content-IO - Fast!', publish=False)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.up#draft')
assertRevisions(('i18n://sv-se@page/title.txt#1', True), ('i18n://sv-se@page/title.up#draft', False))
self.assertEqual(cio.get('page/title').content, u'Content-IO')
# Publish second draft, version 2
with self.assertDB(calls=4, selects=2, updates=2):
with self.assertCache(calls=1, sets=1):
node = cio.publish(node.uri)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.up#2')
assertRevisions(('i18n://sv-se@page/title.txt#1', False), ('i18n://sv-se@page/title.up#2', True))
self.assertEqual(cio.get('page/title').content, u'CONTENT-IO - FAST!')
# Alter published version 2
with self.assertDB(calls=2, selects=1, inserts=0, updates=1):
with self.assertCache(calls=0):
node = cio.set('i18n://sv-se@page/title.up#2', u'Content-IO - Lightening fast!', publish=False)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.up#2')
assertRevisions(('i18n://sv-se@page/title.txt#1', False), ('i18n://sv-se@page/title.up#2', True))
self.assertEqual(cio.get('page/title').content, u'CONTENT-IO - FAST!') # Not published, still in cache
# Re-publish version 2, no change
with self.assertDB(selects=1, inserts=0, updates=0):
with self.assertCache(calls=1, sets=1):
node = cio.publish(node.uri)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.up#2')
assertRevisions(('i18n://sv-se@page/title.txt#1', False), ('i18n://sv-se@page/title.up#2', True))
self.assertEqual(cio.get('page/title').content, u'CONTENT-IO - LIGHTENING FAST!')
# Rollback version 1
with self.assertDB(calls=3, selects=1, updates=2):
with self.assertCache(calls=1, sets=1):
node = cio.publish('i18n://sv-se@page/title#1')
self.assertEqual(node.uri, 'i18n://sv-se@page/title.txt#1')
assertRevisions(('i18n://sv-se@page/title.txt#1', True), ('i18n://sv-se@page/title.up#2', False))
self.assertEqual(cio.get('page/title').content, u'Content-IO')
# Assert get specific version doesn't mess up the cache
cache.clear()
with self.assertCache(calls=0):
self.assertEqual(cio.get('page/title#2').content, u'CONTENT-IO - LIGHTENING FAST!')
with self.assertCache(calls=2, misses=1, sets=1):
self.assertEqual(cio.get('page/title').content, u'Content-IO')
# Load version 1 and 2
data = cio.load('sv-se@page/title#1')
self.assertEqual(data['uri'], 'i18n://sv-se@page/title.txt#1')
self.assertEqual(data['data'], u'Content-IO')
data = cio.load('sv-se@page/title#2')
self.assertEqual(data['uri'], 'i18n://sv-se@page/title.up#2')
self.assertEqual(data['data'], {u'name': u'Content-IO - Lightening fast!'})
# Load without version and expect published version
data = cio.load('sv-se@page/title')
self.assertEqual(data['uri'], 'i18n://sv-se@page/title.txt#1')
self.assertEqual(data['data'], u'Content-IO')
def test_search(self):
cio.set('i18n://sv-se@label/email.txt', u'e-post')
uris = cio.search()
self.assertEqual(len(uris), 1)
uris = cio.search('foo/')
self.assertEqual(len(uris), 0)
uris = cio.search('label/')
self.assertEqual(len(uris), 1)
def test_environment_state(self):
with cio.env(i18n='en-us'):
node = cio.get('page/title')
self.assertEqual(node.uri, 'i18n://en-us@page/title.txt')
node = cio.get('page/title')
self.assertEqual(node.uri, 'i18n://sv-se@page/title.txt')
def test_non_distinct_uri(self):
node1 = cio.get('page/title', u'Title1')
node2 = cio.get('page/title', u'Title2')
self.assertEqual(six.text_type(node1), u'Title1')
self.assertEqual(six.text_type(node2), u'Title1')
node1 = cio.get('page/title', u'Title1', lazy=False)
cache.clear()
node2 = cio.get('page/title', u'Title2', lazy=False)
self.assertEqual(six.text_type(node1), u'Title1')
self.assertEqual(six.text_type(node2), u'Title2') # Second node not buffered, therefore unique default content
def test_fallback(self):
with cio.env(i18n=('sv-se', 'en-us', 'en-uk')):
cio.set('i18n://bogus@label/email.txt', u'epost')
cio.set('i18n://en-uk@label/surname.txt', u'surname')
with self.assertCache(misses=2, sets=2):
with self.assertDB(calls=6, selects=6):
node1 = cio.get('i18n://label/email')
node2 = cio.get('i18n://label/surname', u'efternamn')
self.assertEqual(node1.uri.namespace, 'sv-se') # No fallback, stuck on first namespace, sv-se
self.assertEqual(node1.namespace_uri.namespace, 'sv-se')
self.assertIsNone(node1.content)
self.assertEqual(node2.uri.namespace, 'en-uk')
self.assertEqual(node2.namespace_uri.namespace, 'sv-se')
self.assertEqual(node2.content, u'surname')
cache.clear()
with self.assertCache(misses=2, sets=2):
with self.assertDB(calls=6):
cio.get('i18n://label/email', lazy=False)
cio.get('i18n://label/surname', u'lastname', lazy=False)
def test_uri_redirect(self):
cio.set('i18n://sv-se@page/title.txt', u'Title')
node = cio.get('i18n://sv-se@page/title', u'Default')
self.assertEqual(node.uri, 'i18n://sv-se@page/title.txt#1')
self.assertEqual(node.content, u'Title')
node = cio.get('i18n://sv-se@page/title.up', u'Default Upper', lazy=False)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.up')
self.assertEqual(node.content, u'DEFAULT UPPER') # Cache still contains 'Title', but plugin diff and skipped
cached_node = cache.get(node.uri)
self.assertDictEqual(cached_node, {'uri': node.uri, 'content': u'DEFAULT UPPER'})
cache.clear()
node = cio.get('i18n://sv-se@page/title.up', u'Default-Upper', lazy=False)
self.assertEqual(node.uri, 'i18n://sv-se@page/title.up')
self.assertEqual(node.content, u'DEFAULT-UPPER') # Cache cleared, storage plugin mismatch, default fallback
def test_node_meta(self):
node = cio.set('sv-se@page/title', u'', author=u'lundberg')
self.assertEqual(node.meta.get('author'), u'lundberg')
node = cio.get('page/title')
self.assertEqual(len(node.meta.keys()), 0) # Cached node has no meta
node = cio.load('sv-se@page/title#1')
meta = node['meta']
self.assertKeys(meta, 'author', 'modified_at', 'published_at', 'is_published')
self.assertEqual(meta.get('author'), u'lundberg')
cio.set('sv-se@page/title#1', u'', comment=u'This works!')
node = cio.load('sv-se@page/title#1')
meta = node['meta']
self.assertKeys(meta, 'author', 'comment', 'modified_at', 'published_at', 'is_published')
self.assertEqual(meta.get('author'), u'lundberg')
self.assertEqual(meta.get('comment'), u'This works!')
cio.set('sv-se@page/title#1', u'', comment=None)
node = cio.load('sv-se@page/title#1')
meta = node['meta']
self.assertKeys(meta, 'author', 'modified_at', 'published_at', 'is_published')
self.assertEqual(meta.get('author'), u'lundberg')
self.assertNotIn('comment', meta)
def test_pipes_hits(self):
with cio.env(i18n=('sv-se', 'en-us')):
with self.assertDB(inserts=2):
with self.assertCache(calls=2, sets=2):
cio.set('i18n://sv-se@label/email.txt', u'epost')
cio.set('i18n://en-us@label/surname.txt', u'surname')
# Lazy gets
with self.assertDB(calls=0):
with self.assertCache(calls=0):
node1 = cio.get('label/email')
node2 = cio.get('i18n://label/surname')
node3 = cio.get('i18n://monkey@label/zipcode', default=u'postnummer')
# with self.assertDB(calls=2), self.assertCache(calls=5, hits=1, misses=2, sets=2):
with self.assertDB(calls=4, selects=4):
with self.assertCache(calls=2, hits=1, misses=2, sets=2):
self.assertEqual(six.text_type(node1), u'epost')
self.assertEqual(node2.content, u'surname')
self.assertEqual(six.text_type(node3), u'postnummer')
with self.assertDB(calls=0):
with self.assertCache(calls=1, hits=3):
node1 = cio.get('label/email')
node2 = cio.get('i18n://label/surname')
node3 = cio.get('i18n://monkey@label/zipcode', default=u'postnummer')
self.assertEqual(six.text_type(node1), u'epost')
self.assertEqual(node2.content, u'surname')
self.assertEqual(six.text_type(node3), u'postnummer')
self.assertIsNotNone(repr(node1))
self.assertIsNotNone(str(node1))
def test_forced_empty_content(self):
with self.assertRaises(ValueError):
cio.set('i18n://sv-se@none', None)
node = cio.set('i18n://[email protected]', u'')
node = cio.get(node.uri, default=u'fallback')
self.assertEqual(six.text_type(node), u'')
def test_load_pipeline(self):
with self.assertRaises(ImportError):
pipeline.add_pipe('foo.Bar')
def test_unknown_plugin(self):
with self.assertRaises(ImproperlyConfigured):
cio.set('i18n://sv-se@foo/bar.baz#draft', 'raise')
def test_abandoned_buffered_node(self):
cio.set('sv-se@foo/bar', u'foobar')
node = cio.get('foo/bar')
self.assertFalse(node._flushed)
self.assertIn('get', pipeline._buffer._buffer)
# Mess things up...
pipeline.clear()
self.assertFalse(node._flushed)
self.assertNotIn('get', pipeline._buffer._buffer)
self.assertEqual(node.content, u'foobar')
self.assertTrue(node._flushed)
def test_publish_without_version(self):
cio.set('i18n://sv-se@page/apa.txt', u'Bananas', publish=False)
node = cio.publish('i18n://sv-se@page/apa.txt')
self.assertEqual(node.content, 'Bananas')
def test_load_without_version(self):
cio.set('i18n://sv-se@page/apa.txt', u'Many bananas')
node = cio.load('i18n://sv-se@page/apa.txt')
self.assertEqual(node['content'], 'Many bananas')
def test_load_new_without_extension(self):
node = cio.load('i18n://sv-se@page/monkey')
self.assertEqual(node['content'], None)
|
class ApiTest(BaseTest):
def setUp(self):
pass
def test_get(self):
pass
def test_get_with_empty_default(self):
pass
def test_get_with_context(self):
pass
def test_get_with_local_cache_pipe_settings(self):
pass
def assert_local_thread():
pass
def test_set(self):
pass
def test_delete(self):
pass
def test_revisions(self):
pass
def assertRevisions(*revs):
pass
def test_search(self):
pass
def test_environment_state(self):
pass
def test_non_distinct_uri(self):
pass
def test_fallback(self):
pass
def test_uri_redirect(self):
pass
def test_node_meta(self):
pass
def test_pipes_hits(self):
pass
def test_forced_empty_content(self):
pass
def test_load_pipeline(self):
pass
def test_unknown_plugin(self):
pass
def test_abandoned_buffered_node(self):
pass
def test_publish_without_version(self):
pass
def test_load_without_version(self):
pass
def test_load_new_without_extension(self):
pass
| 25 | 0 | 16 | 2 | 13 | 3 | 1 | 0.21 | 1 | 10 | 4 | 0 | 22 | 0 | 22 | 27 | 386 | 76 | 292 | 56 | 266 | 62 | 277 | 56 | 251 | 1 | 2 | 3 | 24 |
1,115 |
5monkeys/content-io
|
5monkeys_content-io/tests/test_app.py
|
tests.test_app.AppTest
|
class AppTest(BaseTest):
def test_version(self):
self.assertEqual(get_version((1, 2, 3, 'alpha', 1)), '1.2.3a1')
self.assertEqual(get_version((1, 2, 3, 'beta', 2)), '1.2.3b2')
self.assertEqual(get_version((1, 2, 3, 'rc', 3)), '1.2.3c3')
self.assertEqual(get_version((1, 2, 3, 'final', 4)), '1.2.3')
def test_settings(self):
self.assertEqual(settings.URI_NAMESPACE_SEPARATOR, default_settings.URI_NAMESPACE_SEPARATOR)
pre = settings.STORAGE
with settings():
settings.configure(STORAGE='bogus.newstorage')
self.assertEqual(settings.STORAGE, 'bogus.newstorage')
self.assertEqual(settings.STORAGE, pre)
self.assertEqual(settings.STORAGE['NAME'], ':memory:', "Should've been overridden")
settings.STORAGE['PIPE'] = {'FOO': 'bar'}
def assert_local_thread_settings():
settings.configure(local=True, STORAGE={'PIPE': {'HAM': 'spam'}})
self.assertEqual(settings.STORAGE['PIPE']['FOO'], 'bar')
self.assertEqual(settings.STORAGE['PIPE']['HAM'], 'spam')
thread = threading.Thread(target=assert_local_thread_settings)
thread.start()
thread.join()
self.assertEqual(settings.STORAGE['PIPE']['FOO'], 'bar')
self.assertNotIn('HAM', settings.STORAGE['PIPE'])
def test_environment(self):
"""
'default': {
'g11n': 'global',
'i18n': (django_settings.LANGUAGE_CODE,),
'l10n': (project_name(django_settings) or 'local',)
}
"""
env = settings.ENVIRONMENT
self.assertDictEqual(env['default'], {'g11n': 'global', 'i18n': 'sv-se', 'l10n': 'tests'})
with self.assertRaises(IndexError):
cio.env.pop()
with cio.env(i18n='sv', l10n=['loc'], g11n=('glob',)):
self.assertTupleEqual(cio.env.i18n, ('sv',))
self.assertTupleEqual(cio.env.l10n, ('loc',))
self.assertTupleEqual(cio.env.g11n, ('glob',))
with self.assertRaises(SystemError):
cio.env.__init__()
def test_context(self):
self.assertTupleEqual(cio.env.state.i18n, ('sv-se',))
with settings():
settings.ENVIRONMENT['bogus'] = {
'g11n': 'global',
'i18n': ('sv', 'en'),
'l10n': ('foo', 'bar')
}
with cio.env('bogus'):
self.assertTupleEqual(cio.env.state.i18n, ('sv', 'en'))
self.assertTupleEqual(cio.env.state.l10n, ('foo', 'bar'))
with cio.env(i18n='en-us'):
node = cio.get('i18n://label/firstname', lazy=False)
buffered_node = cio.get('i18n://label/email')
self.assertTupleEqual(cio.env.i18n, ('en-us',))
self.assertEqual(len(pipeline._buffer), 1)
self.assertEqual(len(pipeline.history), 1)
def assert_new_thread_env():
self.assertTupleEqual(cio.env.i18n, ('sv-se',))
self.assertEqual(len(pipeline._buffer), 0)
self.assertEqual(len(pipeline.history), 0)
cio.get('i18n://label/surname', lazy=False)
self.assertEqual(len(pipeline.history), 1)
thread = threading.Thread(target=assert_new_thread_env)
thread.start()
thread.join()
buffered_node.flush()
self.assertEqual(len(pipeline._buffer), 0)
self.assertEqual(len(pipeline.history), 2)
self.assertListEqual(pipeline.history.list('get'), [node, buffered_node._node])
self.assertNotIn('bogus', settings.ENVIRONMENT.keys())
|
class AppTest(BaseTest):
def test_version(self):
pass
def test_settings(self):
pass
def assert_local_thread_settings():
pass
def test_environment(self):
'''
'default': {
'g11n': 'global',
'i18n': (django_settings.LANGUAGE_CODE,),
'l10n': (project_name(django_settings) or 'local',)
}
'''
pass
def test_context(self):
pass
def assert_new_thread_env():
pass
| 7 | 1 | 16 | 3 | 13 | 1 | 1 | 0.11 | 1 | 3 | 0 | 0 | 4 | 0 | 4 | 9 | 92 | 19 | 66 | 13 | 59 | 7 | 62 | 13 | 55 | 1 | 2 | 2 | 6 |
1,116 |
5monkeys/content-io
|
5monkeys_content-io/tests/test_cache.py
|
tests.test_cache.CacheTest
|
class CacheTest(BaseTest):
uri = 'i18n://sv-se@label/email.txt'
def test_cached_node(self):
with self.assertRaises(NodeDoesNotExist):
storage.get(self.uri)
content = cache.get(self.uri)
self.assertIsNone(content)
node, _ = storage.set(self.uri + '#draft', u'e-post')
storage.publish(node['uri'])
with self.assertCache(calls=2, misses=1, sets=1):
node = cio.get('i18n://label/email', lazy=False)
cached_node = cache.get('i18n://sv-se@label/email')
self.assertIsInstance(cached_node, dict)
self.assertKeys(cached_node, 'uri', 'content')
_uri, content = cached_node['uri'], cached_node['content']
self.assertEqual(_uri, 'i18n://sv-se@label/email.txt#1')
self.assertTrue(content == node.content == u'e-post')
with self.assertCache(calls=1, misses=0, hits=1):
node = cio.get('i18n://label/email', lazy=False)
self.assertEqual(node.uri, 'i18n://sv-se@label/email.txt#1')
cio.delete(self.uri)
content = cache.get(self.uri)
self.assertIsNone(content)
def test_cache_encoding(self):
cio.set(self.uri, u'epost')
cached_node = cache.get(self.uri)
content = cached_node['content']
self.assertIsInstance(content, six.text_type)
self.assertEqual(content, u'epost')
cache.set('i18n://sv-se@label/email.txt#1', u'epost')
nodes = cache.get_many((self.uri, self.uri))
self.assertDictEqual(nodes, {self.uri: {'uri': 'i18n://sv-se@label/email.txt#1', 'content': u'epost'}})
def test_cache_delete(self):
uris = ['i18n://[email protected]', 'i18n://[email protected]']
cache.set(uris[0], u'Foo')
cache.set(uris[1], u'Bar')
with self.assertCache(hits=2):
cache.get_many(uris)
cache.delete_many(uris)
with self.assertCache(misses=2):
cache.get_many(uris)
def test_cache_set(self):
with self.assertRaises(URI.Invalid):
cache.set('i18n://sv-se@foo', u'Bar')
nodes = {
'i18n://[email protected]#1': u'Foo',
'i18n://[email protected]#2': u'Bar'
}
cache.set_many(nodes)
with self.assertCache(calls=1, hits=2):
result = cache.get_many(['i18n://sv-se@foo', 'i18n://sv-se@bar'])
self.assertDictEqual(result, {
'i18n://sv-se@foo': {'uri': 'i18n://[email protected]#1', 'content': u'Foo'},
'i18n://sv-se@bar': {'uri': 'i18n://[email protected]#2', 'content': u'Bar'}
})
|
class CacheTest(BaseTest):
def test_cached_node(self):
pass
def test_cache_encoding(self):
pass
def test_cache_delete(self):
pass
def test_cache_set(self):
pass
| 5 | 0 | 17 | 4 | 13 | 2 | 1 | 0.16 | 1 | 4 | 3 | 0 | 4 | 0 | 4 | 9 | 74 | 19 | 55 | 16 | 50 | 9 | 49 | 16 | 44 | 1 | 2 | 1 | 4 |
1,117 |
5monkeys/content-io
|
5monkeys_content-io/tests/test_plugins.py
|
tests.test_plugins.PluginTest
|
class PluginTest(BaseTest):
def test_resolve_plugin(self):
with self.assertRaises(UnknownPlugin):
plugins.get('xyz')
plugin = plugins.resolve('i18n://sv-se@page/title.txt')
self.assertIsInstance(plugin, TextPlugin)
with self.assertRaises(UnknownPlugin):
plugins.resolve('i18n://sv-se@page/title.foo')
def test_register_plugin(self):
with self.assertRaises(ImportError):
plugins.register('foo.bar.BogusPlugin')
with self.assertRaises(ImportError):
plugins.register('cio.plugins.text.BogusPlugin')
def test_plugin(self):
self.assertSetEqual(set(plugins.plugins.keys()), set(['txt', 'md']))
settings.configure(PLUGINS=[
'cio.plugins.txt.TextPlugin',
'cio.plugins.md.MarkdownPlugin',
'tests.UppercasePlugin'
])
self.assertSetEqual(set(plugins.plugins.keys()), set(['txt', 'md', 'up']))
node = cio.set('sv-se@page/title.up', {'name': u'lundberg'}, publish=False)
self.assertListEqual(node._content, [{'name': u'lundberg'}, u'{"name": "lundberg"}', u'LUNDBERG'])
cio.publish(node.uri)
node = cio.get('page/title')
raw_content = storage.get(node.uri)
self.assertIsNotNone(raw_content)
self.assertEqual(raw_content['uri'], 'i18n://sv-se@page/title.up#1')
self.assertEqual(raw_content['content'], u'{"name": "lundberg"}')
self.assertEqual(node.content, u'LUNDBERG')
self.assertEqual(node.uri.ext, 'up')
self.assertSetEqual(set(p for p in plugins), set(('txt', 'md', 'up')))
def test_replace_node_in_render_and_load(self):
settings.configure(PLUGINS=[
'cio.plugins.txt.TextPlugin',
'cio.plugins.md.MarkdownPlugin',
'tests.ReplacerPlugin'
])
node = cio.set('sv-se@page/mine.rpl#1', "My own content")
self.assertNotEqual(node.uri.path, 'page/mine.rpl')
self.assertEqual(node.uri.path, 'page/rendered.rpl')
self.assertEqual(node.content, 'REPLACED')
node = cio.load('sv-se@page/loaded.rpl')
self.assertEqual(node['uri'].path, 'page/loaded')
def test_settings(self):
settings.configure(TXT={
'foo': 'bar'
})
plugin = plugins.get('txt')
self.assertEqual(plugin.settings['foo'], 'bar')
def test_markdown(self):
markdown = plugins.get('md')
self.assertEqual(markdown.render('# Title'), '<h1>Title</h1>')
def test_markdown_handles_empty_data(self):
markdown = plugins.get('md')
|
class PluginTest(BaseTest):
def test_resolve_plugin(self):
pass
def test_register_plugin(self):
pass
def test_plugin(self):
pass
def test_replace_node_in_render_and_load(self):
pass
def test_settings(self):
pass
def test_markdown(self):
pass
def test_markdown_handles_empty_data(self):
pass
| 8 | 0 | 9 | 2 | 8 | 0 | 1 | 0.05 | 1 | 4 | 2 | 0 | 7 | 0 | 7 | 12 | 74 | 19 | 55 | 15 | 47 | 3 | 45 | 15 | 37 | 1 | 2 | 1 | 7 |
1,118 |
5monkeys/content-io
|
5monkeys_content-io/tests/test_storage.py
|
tests.test_storage.StorageTest
|
class StorageTest(BaseTest):
def test_get_storage(self):
backend = get_backend('sqlite://:memory:')
self.assertTrue(issubclass(backend.__class__, StorageBackend))
backend = '.'.join((SqliteBackend.__module__, SqliteBackend.__name__))
with self.assertRaises(ImproperlyConfigured):
backend = get_backend(backend)
backend = get_backend({
'BACKEND': backend,
'NAME': ':memory:'
})
self.assertTrue(issubclass(backend.__class__, DatabaseBackend))
with self.assertRaises(ImportError):
get_backend('foo.Bar')
with self.assertRaises(ImportError):
get_backend('cio.storage.backends.orm.Bogus')
with self.assertRaises(InvalidBackend):
get_backend('invalid')
with self.assertRaises(InvalidBackend):
get_backend('foo://')
def test_bogus_backend(self):
class BogusStorage(CacheBackend, StorageBackend):
pass
bogus = BogusStorage()
self.assertIsNone(bogus.scheme)
with self.assertRaises(NotImplementedError):
bogus._get(None)
with self.assertRaises(NotImplementedError):
bogus._get_many(None)
with self.assertRaises(NotImplementedError):
bogus._set(None, None)
with self.assertRaises(NotImplementedError):
bogus._set_many(None)
with self.assertRaises(NotImplementedError):
bogus._delete(None)
with self.assertRaises(NotImplementedError):
bogus._delete_many(None)
with self.assertRaises(NotImplementedError):
bogus.publish(None)
with self.assertRaises(NotImplementedError):
bogus.get_revisions(None)
def test_create_update(self):
storage.set('i18n://[email protected]#draft', u'first')
node = storage.get('i18n://sv-se@a#draft')
self.assertEqual(node['content'], u'first')
self.assertEqual(node['uri'], 'i18n://[email protected]#draft')
storage.set('i18n://[email protected]#draft', u'second')
node = storage.get('i18n://sv-se@a#draft')
self.assertEqual(node['content'], u'second')
self.assertEqual(node['uri'], 'i18n://[email protected]#draft')
def test_get(self):
storage.set('i18n://[email protected]#draft', u'A')
storage.set('i18n://[email protected]#draft', u'B')
node = storage.get('i18n://sv-se@a#draft')
self.assertEqual(node['uri'], 'i18n://[email protected]#draft')
self.assertEqual(node['content'], u'A')
storage.publish('i18n://sv-se@a#draft')
storage.publish('i18n://sv-se@b#draft')
nodes = storage.get_many(('i18n://sv-se@a', 'i18n://sv-se@b'))
for node in nodes.values():
node.pop('meta')
self.assertDictEqual(nodes, {
'i18n://sv-se@a': {
'uri': 'i18n://[email protected]#1',
'content': u'A'
},
'i18n://sv-se@b': {
'uri': 'i18n://[email protected]#1',
'content': u'B'
}
})
def test_delete(self):
storage.set('i18n://[email protected]#draft', u'A')
storage.set('i18n://[email protected]#draft', u'B')
node = storage.get('i18n://sv-se@a#draft')
self.assertEqual(node['content'], u'A')
deleted_node = storage.delete('sv-se@a#draft')
deleted_node.pop('meta')
self.assertDictEqual(deleted_node, {'uri': 'i18n://[email protected]#draft', 'content': u'A'})
deleted_nodes = storage.delete_many(('sv-se@a#draft', 'sv-se@b#draft'))
for node in deleted_nodes.values():
node.pop('meta')
self.assertDictEqual(deleted_nodes, {
'i18n://sv-se@b#draft': {'uri': 'i18n://[email protected]#draft', 'content': u'B'}
})
def test_nonexisting_node(self):
with self.assertRaises(URI.Invalid):
storage.get('?')
with self.assertRaises(NodeDoesNotExist):
storage.get('sv-se@page/title')
def test_plugin_mismatch(self):
storage.set('i18n://[email protected]#draft', u'A')
storage.publish('i18n://[email protected]#draft')
with self.assertRaises(NodeDoesNotExist):
storage.get('i18n://[email protected]')
nodes = storage.get_many(('i18n://[email protected]',))
self.assertDictEqual(nodes, {})
def test_node_integrity(self):
storage.backend._create(URI('i18n://[email protected]#draft'), u'first')
with self.assertRaises(PersistenceError):
storage.backend._create(URI('i18n://sv-se@a'), u'second')
with self.assertRaises(PersistenceError):
storage.backend._create(URI('i18n://[email protected]'), u'second')
with self.assertRaises(PersistenceError):
storage.backend._create(URI('i18n://sv-se@a#draft'), u'second')
def test_search(self):
storage.set('i18n://sv-se@foo/bar.txt#draft', u'')
storage.set('i18n://sv-se@foo/bar/baz.md#draft', u'')
storage.set('i18n://en@foo/bar/baz.md#draft', u'')
storage.set('i18n://en@foo/bar/baz.md#1', u'')
storage.set('i18n://en@ham/spam.txt#draft', u'')
storage.set('l10n://a@foo/bar.md#draft', u'')
storage.set('l10n://b@foo/bar/baz.txt#draft', u'')
uris = storage.search()
self.assertListEqual(uris, [
'i18n://en@foo/bar/baz.md',
'i18n://en@ham/spam.txt',
'i18n://sv-se@foo/bar.txt',
'i18n://sv-se@foo/bar/baz.md',
'l10n://a@foo/bar.md',
'l10n://b@foo/bar/baz.txt',
])
uris = storage.search('i18n://')
self.assertListEqual(uris, [
'i18n://en@foo/bar/baz.md',
'i18n://en@ham/spam.txt',
'i18n://sv-se@foo/bar.txt',
'i18n://sv-se@foo/bar/baz.md',
])
uris = storage.search('en@')
self.assertListEqual(uris, [
'i18n://en@foo/bar/baz.md',
'i18n://en@ham/spam.txt',
])
uris = storage.search('foo/')
self.assertListEqual(uris, [
'i18n://en@foo/bar/baz.md',
'i18n://sv-se@foo/bar.txt',
'i18n://sv-se@foo/bar/baz.md',
'l10n://a@foo/bar.md',
'l10n://b@foo/bar/baz.txt',
])
uris = storage.search('sv-se@foo/')
self.assertListEqual(uris, [
'i18n://sv-se@foo/bar.txt',
'i18n://sv-se@foo/bar/baz.md',
])
uris = storage.search('i18n://foo/')
self.assertListEqual(uris, [
'i18n://en@foo/bar/baz.md',
'i18n://sv-se@foo/bar.txt',
'i18n://sv-se@foo/bar/baz.md',
])
uris = storage.search('i18n://en@')
self.assertListEqual(uris, [
'i18n://en@foo/bar/baz.md',
'i18n://en@ham/spam.txt',
])
|
class StorageTest(BaseTest):
def test_get_storage(self):
pass
def test_bogus_backend(self):
pass
class BogusStorage(CacheBackend, StorageBackend):
def test_create_update(self):
pass
def test_get_storage(self):
pass
def test_delete(self):
pass
def test_nonexisting_node(self):
pass
def test_plugin_mismatch(self):
pass
def test_node_integrity(self):
pass
def test_search(self):
pass
| 11 | 0 | 19 | 2 | 17 | 4 | 1 | 0.2 | 1 | 12 | 10 | 0 | 9 | 0 | 9 | 14 | 184 | 26 | 158 | 21 | 147 | 32 | 113 | 21 | 102 | 2 | 2 | 1 | 11 |
1,119 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/pipes/base.py
|
cio.pipeline.pipes.base.BasePipe
|
class BasePipe(object):
"""
Optional implementable pipe methods:
def get_request(self, request):
pass
def get_response(self, response):
return response
def set_request(self, request):
pass
def set_response(self, response):
return response
def delete_request(self, request):
pass
def delete_response(self, response):
return response
def publish_request(self, request):
pass
def publish_response(self, response):
return response
"""
def materialize_node(self, node, uri, content, meta=None):
"""
Set node uri and content from backend
"""
node.uri = uri
node.content = content
node.meta = meta if meta is not None else {}
|
class BasePipe(object):
'''
Optional implementable pipe methods:
def get_request(self, request):
pass
def get_response(self, response):
return response
def set_request(self, request):
pass
def set_response(self, response):
return response
def delete_request(self, request):
pass
def delete_response(self, response):
return response
def publish_request(self, request):
pass
def publish_response(self, response):
return response
'''
def materialize_node(self, node, uri, content, meta=None):
'''
Set node uri and content from backend
'''
pass
| 2 | 2 | 7 | 0 | 4 | 3 | 2 | 4.4 | 1 | 0 | 0 | 5 | 1 | 0 | 1 | 1 | 36 | 9 | 5 | 2 | 3 | 22 | 5 | 2 | 3 | 2 | 1 | 0 | 2 |
1,120 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/history.py
|
cio.pipeline.history.NodeHistory
|
class NodeHistory(ThreadLocalObject):
def __init__(self):
super(NodeHistory, self).__init__()
self._history = defaultdict(list)
def __len__(self):
return sum(len(nodes) for nodes in self._history.values())
def log(self, method, *nodes):
self._history[method].extend(nodes)
def list(self, method):
return self._history[method]
def clear(self):
self._history.clear()
|
class NodeHistory(ThreadLocalObject):
def __init__(self):
pass
def __len__(self):
pass
def log(self, method, *nodes):
pass
def list(self, method):
pass
def clear(self):
pass
| 6 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 5 | 1 | 5 | 10 | 17 | 5 | 12 | 7 | 6 | 0 | 12 | 7 | 6 | 1 | 2 | 0 | 5 |
1,121 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/__init__.py
|
cio.backends.CacheManager
|
class CacheManager(BackendManager, CacheBackend):
def _get_backend_config(self):
return settings.CACHE
def _update_backend_settings(self, config):
settings.CACHE = config
def get(self, uri):
uri = self._clean_get_uri(uri)
return self.backend.get(uri)
def get_many(self, uris):
uris = self._clean_get_uris(uris)
return self.backend.get_many(uris)
def set(self, uri, content):
uri = self._clean_set_uri(uri)
self.backend.set(uri, content)
def set_many(self, nodes):
nodes = dict((self._clean_set_uri(uri), content) for uri, content in six.iteritems(nodes))
self.backend.set_many(nodes)
def delete(self, uri):
uri = self._clean_delete_uri(uri)
self.backend.delete(uri)
def delete_many(self, uris):
uris = self._clean_delete_uris(uris)
self.backend.delete_many(uris)
def clear(self):
self.backend.clear()
def _is_valid_backend(self, backend):
return isinstance(backend, CacheBackend)
def _clean_get_uri(self, uri):
return self._clean_uri(uri, 'namespace', 'path')
def _clean_set_uri(self, uri):
return self._clean_uri(uri, 'namespace', 'path', 'ext')
def _clean_delete_uri(self, uri):
return self._clean_uri(uri, 'namespace', 'path')
|
class CacheManager(BackendManager, CacheBackend):
def _get_backend_config(self):
pass
def _update_backend_settings(self, config):
pass
def get(self, uri):
pass
def get_many(self, uris):
pass
def set(self, uri, content):
pass
def set_many(self, nodes):
pass
def delete(self, uri):
pass
def delete_many(self, uris):
pass
def clear(self):
pass
def _is_valid_backend(self, backend):
pass
def _clean_get_uri(self, uri):
pass
def _clean_set_uri(self, uri):
pass
def _clean_delete_uri(self, uri):
pass
| 14 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 2 | 1 | 0 | 0 | 13 | 0 | 13 | 47 | 46 | 13 | 33 | 14 | 19 | 0 | 33 | 14 | 19 | 1 | 3 | 0 | 13 |
1,122 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/__init__.py
|
cio.backends.StorageManager
|
class StorageManager(BackendManager, StorageBackend):
def _get_backend_config(self):
return settings.STORAGE
def _update_backend_settings(self, config):
settings.STORAGE = config
def get(self, uri):
uri = self._clean_get_uri(uri)
return self.backend.get(uri)
def get_many(self, uris):
uris = self._clean_get_uris(uris)
return self.backend.get_many(uris)
def set(self, uri, content, **meta):
uri = self._clean_set_uri(uri)
if content is None:
raise ValueError('Can not persist content equal to None for URI "%s".' % uri)
return self.backend.set(uri, content, **meta)
def delete(self, uri):
uri = self._clean_delete_uri(uri)
return self.backend.delete(uri)
def delete_many(self, uris):
uris = self._clean_delete_uris(uris)
return self.backend.delete_many(uris)
def publish(self, uri, **meta):
uri = self._clean_publish_uri(uri)
return self.backend.publish(uri, **meta)
def get_revisions(self, uri):
uri = self._clean_get_uri(uri)
return self.backend.get_revisions(uri)
def search(self, uri=None):
_uri = URI(uri)
if not uri or settings.URI_SCHEME_SEPARATOR not in uri:
_uri = _uri.clone(scheme=None)
return self.backend.search(uri=_uri)
def _is_valid_backend(self, backend):
return isinstance(backend, StorageBackend)
def _clean_get_uri(self, uri):
return self._clean_uri(uri, 'namespace', 'path')
def _clean_set_uri(self, uri):
return self._clean_uri(uri, 'namespace', 'path', 'ext', 'version')
def _clean_delete_uri(self, uri):
return self._clean_uri(uri, 'namespace', 'path', 'version')
def _clean_publish_uri(self, uri):
return self._clean_uri(uri, 'namespace', 'path', 'version')
|
class StorageManager(BackendManager, StorageBackend):
def _get_backend_config(self):
pass
def _update_backend_settings(self, config):
pass
def get(self, uri):
pass
def get_many(self, uris):
pass
def set(self, uri, content, **meta):
pass
def delete(self, uri):
pass
def delete_many(self, uris):
pass
def publish(self, uri, **meta):
pass
def get_revisions(self, uri):
pass
def search(self, uri=None):
pass
def _is_valid_backend(self, backend):
pass
def _clean_get_uri(self, uri):
pass
def _clean_set_uri(self, uri):
pass
def _clean_delete_uri(self, uri):
pass
def _clean_publish_uri(self, uri):
pass
| 16 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 2 | 2 | 1 | 0 | 15 | 0 | 15 | 38 | 60 | 17 | 43 | 17 | 27 | 0 | 43 | 17 | 27 | 2 | 3 | 1 | 17 |
1,123 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/handler.py
|
cio.pipeline.handler.PipelineHandler
|
class PipelineHandler(object):
def __init__(self):
self.history = NodeHistory()
self._buffer = NodeBuffer()
self.load()
settings.watch(self.load)
def load(self):
self.pipes = []
for pipe_path in settings.PIPELINE:
self.add_pipe(pipe_path)
self.build()
def add_pipe(self, pipe):
try:
if isinstance(pipe, type):
pipe_class = pipe
else:
pipe_class = import_class(pipe)
except ImportError as e:
raise ImportError('Could not import content-io pipe "%s" (Is it on sys.path?): %s' % (pipe, e))
else:
self.pipes.append(pipe_class)
def build(self):
self._pipeline = defaultdict(list)
for pipe_class in self.pipes:
pipe = pipe_class()
for call in PIPELINE_CALLS:
request_handler = getattr(pipe, '%s_request' % call, None)
response_handler = getattr(pipe, '%s_response' % call, None)
self._pipeline[call].append((request_handler, response_handler))
def send(self, method, *nodes):
request = dict((node.uri, node) for node in nodes)
response_chain = []
# Iterate request chain
for request_handler, response_handler in self._pipeline[method]:
if request_handler:
pipe_response = request_handler(request)
else:
pipe_response = None
# Build response chain
response_chain.append((response_handler, pipe_response))
# Go no further in pipeline if out of node requests
if not request:
break
# Turn request to response
response = request
# Iterate response chain
for response_handler, pipe_response in reversed(response_chain):
if response and response_handler:
response = response_handler(response)
if pipe_response:
response.update(pipe_response)
# Log response
self.history.log(method, *response.values())
return response
def buffer(self, method, node):
callback = partial(self.flush, method)
buffered_node = BufferedNode(node, callback=callback)
self._buffer.add(method, buffered_node)
return buffered_node
def flush(self, method, sender=None):
# Extract nodes from buffer
buffer = self._buffer.pop(method)
# Re-buffer triggering node if buffer for some reason is empty
if not buffer:
logger.warn(
'Tried to flush empty buffer, '
'triggered by probably abandoned or cached node: %r',
sender
)
self._buffer.add(method, sender)
buffer = self._buffer.pop(method)
# Extract and flatten wrapped nodes, send only distinct uri's
nodes = (buffered_nodes[0]._node for buffered_nodes in buffer.values())
# Send nodes through pipeline
response = self.send(method, *nodes)
# Update buffered nodes to make sure uri duplicates,
# not sent through pipeline, gets content
for node in response.values():
for buffered_node in buffer[node.initial_uri]:
buffered_node.content = node.content
def clear(self):
self._buffer.clear()
self.history.clear()
|
class PipelineHandler(object):
def __init__(self):
pass
def load(self):
pass
def add_pipe(self, pipe):
pass
def build(self):
pass
def send(self, method, *nodes):
pass
def buffer(self, method, node):
pass
def flush(self, method, sender=None):
pass
def clear(self):
pass
| 9 | 0 | 12 | 1 | 9 | 2 | 3 | 0.17 | 1 | 9 | 3 | 0 | 8 | 4 | 8 | 8 | 102 | 19 | 71 | 33 | 62 | 12 | 65 | 32 | 56 | 7 | 1 | 2 | 22 |
1,124 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/base.py
|
cio.backends.base.BaseBackend
|
class BaseBackend(object):
scheme = None
def __init__(self, **config):
self.config = config
|
class BaseBackend(object):
def __init__(self, **config):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 2 | 1 | 1 | 1 | 1 | 6 | 2 | 4 | 4 | 2 | 0 | 4 | 4 | 2 | 1 | 1 | 0 | 1 |
1,125 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/exceptions.py
|
cio.backends.exceptions.InvalidBackend
|
class InvalidBackend(Exception):
pass
|
class InvalidBackend(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 |
1,126 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/exceptions.py
|
cio.backends.exceptions.NodeDoesNotExist
|
class NodeDoesNotExist(Exception):
pass
|
class NodeDoesNotExist(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 |
1,127 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/locmem/__init__.py
|
cio.backends.locmem.Backend
|
class Backend(LocMemCacheBackend):
pass
|
class Backend(LocMemCacheBackend):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
1,128 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/locmem/backend.py
|
cio.backends.locmem.backend.LocMemCacheBackend
|
class LocMemCacheBackend(CacheBackend):
scheme = 'locmem'
def __init__(self, **config):
super(LocMemCacheBackend, self).__init__(**config)
self._cache = {}
self.calls = 0
self.hits = 0
self.misses = 0
self.sets = 0
def clear(self):
self._cache.clear()
def _get(self, key):
value = self._cache.get(key)
self.calls += 1
if value is None:
self.misses += 1
else:
self.hits += 1
return value
def _get_many(self, keys):
result = {}
for key in keys:
value = self._cache.get(key)
if value is not None:
result[key] = value
self.hits += 1
else:
self.misses += 1
self.calls += 1
return result
def _set(self, key, value):
self._cache[key] = value
self.calls += 1
self.sets += 1
def _set_many(self, data):
for key, value in six.iteritems(data):
self._cache[key] = value
self.sets += 1
self.calls += 1
def _delete(self, key):
if key in self._cache:
del self._cache[key]
self.calls += 1
def _delete_many(self, keys):
for key in keys:
self._delete(key)
self.calls -= 1 # Revert individual _delete call count
self.calls += 1
|
class LocMemCacheBackend(CacheBackend):
def __init__(self, **config):
pass
def clear(self):
pass
def _get(self, key):
pass
def _get_many(self, keys):
pass
def _set(self, key, value):
pass
def _set_many(self, data):
pass
def _delete(self, key):
pass
def _delete_many(self, keys):
pass
| 9 | 0 | 6 | 0 | 6 | 0 | 2 | 0.02 | 1 | 1 | 0 | 1 | 8 | 5 | 8 | 28 | 57 | 9 | 48 | 21 | 39 | 1 | 46 | 21 | 37 | 3 | 3 | 2 | 14 |
1,129 |
5monkeys/content-io
|
5monkeys_content-io/tests/test_utils.py
|
tests.test_utils.UtilsTest
|
class UtilsTest(BaseTest):
def test_uri(self):
self.assertEqual(URI('i18n://sv@page/title.txt'), 'i18n://sv@page/title.txt')
uri = URI(scheme='i18n', namespace='sv-se', path='page/title', ext='txt')
self.assertEqual(uri, 'i18n://sv-se@page/title.txt')
uri = URI('page/title')
self.assertFalse(uri.is_absolute())
self.assertEqual(uri.scheme, 'i18n')
self.assertIsNone(uri.namespace)
self.assertEqual(uri.path, 'page/title')
self.assertIsNone(uri.ext)
uri = uri.clone(namespace='sv-se')
self.assertFalse(uri.is_absolute())
self.assertEqual(uri, 'i18n://sv-se@page/title')
uri = uri.clone(ext='txt')
self.assertEqual(uri, 'i18n://sv-se@page/title.txt')
self.assertTrue(uri.is_absolute())
uri = uri.clone(path='images/me.jpg/title', version='draft')
self.assertEqual(uri, 'i18n://sv-se@images/me.jpg/title.txt#draft')
self.assertEqual(uri.version, 'draft')
self.assertEqual(uri.path, 'images/me.jpg/title')
self.assertEqual(uri.ext, 'txt')
uri = uri.clone(ext=None)
self.assertEqual(uri, 'i18n://sv-se@images/me.jpg/title#draft')
self.assertIsNone(uri.ext)
with settings(URI_DEFAULT_SCHEME='l10n'):
uri = URI('page/title')
self.assertEqual(uri, 'l10n://page/title')
self.assertEqual(uri.scheme, 'l10n')
uri = uri.clone(scheme=None)
self.assertEqual(uri, 'page/title')
self.assertEqual(uri.scheme, None)
uri = URI('i18n://sv@page/title.txt#draft')
self.assertEqual(uri, 'i18n://sv@page/title.txt#draft')
self.assertEqual(uri.version, 'draft')
def test_uri_query_params(self):
# Verify query params are snatched up
uri = URI('i18n://sv@page/title.txt?var=someval')
self.assertEqual(uri, 'i18n://sv@page/title.txt?var=someval')
self.assertDictEqual(uri.query, {
'var': ['someval']
})
# Verify query params work with version
uri = URI('i18n://sv@page/title.txt?var=someval#2')
self.assertEqual(uri, 'i18n://sv@page/title.txt?var=someval#2')
self.assertDictEqual(uri.query, {
'var': ['someval']
})
# Verify multiple query parameters are handled
uri = URI('i18n://sv@page/title.txt?var=someval&second=2')
self.assertEqual(uri, 'i18n://sv@page/title.txt?var=someval&second=2')
self.assertDictEqual(uri.query, {
'var': ['someval'],
'second': ['2'],
})
# Verify query params can be replaced when cloned
uri = uri.clone(query={
'var': ['newval'],
'second': ['1']
})
self.assertDictEqual(uri.query, {
'var': ['newval'],
'second': ['1']
})
exact_copy = uri.clone()
self.assertEqual(exact_copy, uri)
self.assertDictEqual(exact_copy.query, uri.query)
self.assertEqual(exact_copy.query['second'], ['1'])
self.assertNotEqual(id(exact_copy.query), id(uri.query))
# Verify replacement works
uri = URI('i18n://sv@page/title.txt?var=someval&second=2').clone(query=None)
self.assertEqual(uri.query, None)
# Verify unicode strings are handled correctly
value = quote(u'räv')
unicode_uri = u'i18n://sv@page/title.txt?fox=' + value
uri = URI(unicode_uri.encode('utf-8'))
self.assertEqual(uri, unicode_uri)
self.assertDictEqual(uri.query, {
u'fox': [u'räv']
})
# Verify query parameter order
uri = URI(b'i18n://sv@page/title.txt?fox=1&variable=2&last=3')
self.assertEqual(uri, 'i18n://sv@page/title.txt?fox=1&variable=2&last=3')
self.assertDictEqual(uri.query, {
'fox': ['1'],
'variable': ['2'],
'last': ['3']
})
# Verify empty variables are handled correctly
uri = URI(u'i18n://sv@page/title.txt?fox=&variable')
self.assertEqual(uri, 'i18n://sv@page/title.txt?fox=&variable=')
self.assertDictEqual(uri.query, {
'fox': [],
'variable': []
})
# Verify delimiters as values and/or keys
value = quote(u'i18n://sv@page/title.txt#1')
unicode_uri = u'i18n://sv@page/title.txt?fox=' + value
uri = URI(unicode_uri.encode('utf-8'))
self.assertEqual(uri, unicode_uri)
self.assertDictEqual(uri.query, {
'fox': [u'i18n://sv@page/title.txt#1']
})
# Verify multiple query params with same key return last entry
uri = URI('i18n://sv@page/title.txt?key=a&key=b&key=c')
self.assertEqual(uri, 'i18n://sv@page/title.txt?key=c')
self.assertDictEqual(uri.query, {
'key': ['c']
})
# Verify query string handles when no values are inputted
uri = URI('i18n://sv@page/title.txt?')
self.assertEqual(uri, 'i18n://sv@page/title.txt')
self.assertEqual(uri.query, None)
# Verify query string handles when keys without values are inputted
uri = URI('i18n://sv@page/title.txt?key')
self.assertEqual(uri, 'i18n://sv@page/title.txt?key=')
self.assertEqual(uri.query, {
'key': []
})
def test_formatter(self):
tests = [
(u"These are no variables: {} {0} {x} {x:f} {x!s} {x!r:.2f} { y } {{ y }}", {}, None),
(u"This is no variable {\n\t'foo!': 'bar', ham: 'spam'\n}", {}, None),
(u"These are variabls {v}, {n!s}, {n:.2f}, {n!s:>5}", dict(v=u'VALUE', n=1),
u"These are variabls VALUE, 1, 1.00, 1"),
(u"This is {mixed} with variables {}, {x}", dict(x=u'X'),
u"This is {mixed} with variables {}, X")
]
formatter = ContentFormatter()
for template, context, value in tests:
self.assertEqual(formatter.format(template, **context), value or template)
def test_import_class(self):
CF = import_class('cio.utils.formatters', 'ContentFormatter')
self.assertEqual(CF, ContentFormatter)
with self.assertRaises(ImportError):
import_class('cio.utils.formatters', 'FooBar')
def test_lazy_shortcut(self):
uri_module = lazy_shortcut('cio.utils', 'uri')
self.assertEqual(uri_module.URI, URI)
|
class UtilsTest(BaseTest):
def test_uri(self):
pass
def test_uri_query_params(self):
pass
def test_formatter(self):
pass
def test_import_class(self):
pass
def test_lazy_shortcut(self):
pass
| 6 | 0 | 32 | 4 | 25 | 4 | 1 | 0.16 | 1 | 5 | 3 | 0 | 5 | 0 | 5 | 10 | 166 | 27 | 127 | 16 | 121 | 20 | 92 | 16 | 86 | 2 | 2 | 1 | 6 |
1,130 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/sqlite/__init__.py
|
cio.backends.sqlite.Backend
|
class Backend(SqliteBackend):
pass
|
class Backend(SqliteBackend):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
1,131 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/buffer.py
|
cio.pipeline.buffer.NodeBuffer
|
class NodeBuffer(ThreadLocalObject):
def __init__(self):
super(NodeBuffer, self).__init__()
self._buffer = {}
def __len__(self):
return sum(len(method_nodes) for method_nodes in self._buffer.values())
def add(self, method, node):
if method not in self._buffer:
self._buffer[method] = defaultdict(list)
buffer = self._buffer[method]
buffer[node.initial_uri].append(node)
def pop(self, method):
buffer = self._buffer.get(method, defaultdict(list))
if buffer:
_clone = dict(buffer)
buffer.clear()
buffer = _clone
return buffer
def clear(self):
self._buffer.clear()
|
class NodeBuffer(ThreadLocalObject):
def __init__(self):
pass
def __len__(self):
pass
def add(self, method, node):
pass
def pop(self, method):
pass
def clear(self):
pass
| 6 | 0 | 4 | 1 | 4 | 0 | 1 | 0 | 1 | 3 | 0 | 0 | 5 | 1 | 5 | 10 | 28 | 8 | 20 | 10 | 14 | 0 | 20 | 10 | 14 | 2 | 2 | 1 | 7 |
1,132 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/buffer.py
|
cio.pipeline.buffer.BufferedNode
|
class BufferedNode(Node):
def __init__(self, node, callback):
self._node = node
self._callback = callback
self._flushed = False
def __repr__(self):
if self._flushed:
uri = self.uri
else:
uri = self._node.initial_uri
return '<BufferedNode: %s>' % uri
def flush(self):
if not self._flushed:
self._callback(self)
@property
def uri(self):
self.flush()
return self._node.uri
def get_content(self):
self.flush()
return self._node.content
def set_content(self, content):
self._flushed = True
self._node.content = content
content = property(get_content, set_content)
@property
def meta(self):
return self._node.meta
@property
def initial(self):
return self._node.initial
@property
def initial_uri(self):
return self._node.initial_uri
@property
def namespace_uri(self):
return self._node.namespace_uri
|
class BufferedNode(Node):
def __init__(self, node, callback):
pass
def __repr__(self):
pass
def flush(self):
pass
@property
def uri(self):
pass
def get_content(self):
pass
def set_content(self, content):
pass
@property
def meta(self):
pass
@property
def initial(self):
pass
@property
def initial_uri(self):
pass
@property
def namespace_uri(self):
pass
| 16 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 10 | 3 | 10 | 23 | 48 | 11 | 37 | 21 | 21 | 0 | 31 | 16 | 20 | 2 | 2 | 1 | 12 |
1,133 |
5monkeys/content-io
|
5monkeys_content-io/cio/node.py
|
cio.node.Node
|
class Node(object):
_formatter = ContentFormatter()
def __init__(self, uri, content=None, **meta):
self.env = env.state
self._uri = [uri, URI(uri)]
self._content = [content]
self.meta = meta
def __repr__(self):
return '<Node: %s>' % self.uri
def __bytes__(self):
content = self.render()
if isinstance(content, six.text_type):
content = content.encode('utf-8')
return content or b''
def __unicode__(self):
return self.render() or ''
__str__ = __bytes__ if six.PY2 else __unicode__
def render(self, **context):
if self.content is not None:
if context:
return self._formatter.format(self.content, **context)
else:
return self.content
def get_uri(self):
return self._uri[-1]
def set_uri(self, uri):
if uri != self.get_uri():
self._uri.append(URI(uri))
uri = property(get_uri, set_uri)
def get_content(self):
return self._content[-1]
def set_content(self, content):
if content != self.get_content():
self._content.append(content)
content = property(get_content, set_content)
@property
def initial(self):
return self._content[0]
@property
def initial_uri(self):
return self._uri[0]
@property
def namespace_uri(self):
"""
Finds and returns first applied URI of this node that has a namespace.
:return str: uri
"""
try:
return next(
iter(filter(lambda uri: URI(uri).namespace, self._uri))
)
except StopIteration:
return None
def for_json(self):
return {
'uri': six.text_type(self.uri),
'content': self.content,
'meta': self.meta if self.meta is not None else {}
}
|
class Node(object):
def __init__(self, uri, content=None, **meta):
pass
def __repr__(self):
pass
def __bytes__(self):
pass
def __unicode__(self):
pass
def render(self, **context):
pass
def get_uri(self):
pass
def set_uri(self, uri):
pass
def get_content(self):
pass
def set_content(self, content):
pass
@property
def initial(self):
pass
@property
def initial_uri(self):
pass
@property
def namespace_uri(self):
'''
Finds and returns first applied URI of this node that has a namespace.
:return str: uri
'''
pass
def for_json(self):
pass
| 17 | 1 | 4 | 0 | 4 | 0 | 2 | 0.07 | 1 | 3 | 1 | 1 | 13 | 4 | 13 | 13 | 77 | 18 | 55 | 26 | 38 | 4 | 45 | 23 | 31 | 3 | 1 | 2 | 20 |
1,134 |
5monkeys/content-io
|
5monkeys_content-io/tests/__init__.py
|
tests.BaseTest
|
class BaseTest(TestCase):
def setUp(self):
from cio.environment import env
from cio.backends import cache, storage
from cio.pipeline import pipeline
from cio.plugins import plugins
env.reset()
cache.clear()
storage.backend._call_delete()
pipeline.clear()
plugins.load()
self.configure()
def configure(self):
from cio.conf import settings
settings.configure(
ENVIRONMENT={
'default': {
'i18n': 'sv-se',
'l10n': 'tests',
'g11n': 'global'
}
},
PLUGINS=[
'cio.plugins.txt.TextPlugin',
'cio.plugins.md.MarkdownPlugin'
]
)
def assertKeys(self, dict, *keys):
self.assertEqual(set(dict.keys()), set(keys))
@contextmanager
def assertCache(self, calls=-1, hits=-1, misses=-1, sets=-1):
from cio.backends import cache
cb = cache.backend
cb.calls = 0
cb.hits = 0
cb.misses = 0
cb.sets = 0
yield
if calls >= 0:
assert cb.calls == calls, '%s != %s' % (cb.calls, calls)
if hits >= 0:
assert cb.hits == hits, '%s != %s' % (cb.hits, hits)
if misses >= 0:
assert cb.misses == misses, '%s != %s' % (cb.misses, misses)
if sets >= 0:
assert cb.sets == sets, '%s != %s' % (cb.sets, sets)
@contextmanager
def assertDB(self, calls=-1, selects=-1, inserts=-1, updates=-1, deletes=-1):
from cio.backends import storage
backend = storage.backend
backend.start_debug()
yield
count = lambda cmd: len([q for q in backend.queries if q['sql'].split(' ', 1)[0].upper().startswith(cmd)])
if calls >= 0:
call_count = len(backend.queries)
assert call_count == calls, '%s != %s' % (call_count, calls)
if selects >= 0:
select_count = count('SELECT')
assert select_count == selects, '%s != %s' % (select_count, selects)
if inserts >= 0:
insert_count = count('INSERT')
assert insert_count == inserts, '%s != %s' % (insert_count, inserts)
if updates >= 0:
update_count = count('UPDATE')
assert update_count == updates, '%s != %s' % (update_count, updates)
if deletes >= 0:
delete_count = count('DELETE')
assert delete_count == deletes, '%s != %s' % (delete_count, deletes)
backend.stop_debug()
|
class BaseTest(TestCase):
def setUp(self):
pass
def configure(self):
pass
def assertKeys(self, dict, *keys):
pass
@contextmanager
def assertCache(self, calls=-1, hits=-1, misses=-1, sets=-1):
pass
@contextmanager
def assertDB(self, calls=-1, selects=-1, inserts=-1, updates=-1, deletes=-1):
pass
| 8 | 0 | 15 | 2 | 13 | 0 | 3 | 0 | 1 | 1 | 0 | 6 | 5 | 0 | 5 | 5 | 84 | 15 | 69 | 23 | 54 | 0 | 55 | 21 | 42 | 6 | 1 | 1 | 14 |
1,135 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/sqlite/backend.py
|
cio.backends.sqlite.backend.SqliteBackend
|
class SqliteBackend(DatabaseBackend):
def __init__(self, **config):
super(SqliteBackend, self).__init__(**config)
self.debug = False
self.queries = []
if 'NAME' not in self.config:
raise ImproperlyConfigured('Missing sqlite database name.')
database = self.config['NAME']
kwargs = self.config.get('OPTIONS', {})
self._connection = sqlite3.connect(database, **kwargs)
self._setup()
def _setup(self):
with self._connection as con:
con.execute("""
CREATE TABLE IF NOT EXISTS "content_io_node" (
"id" integer NOT NULL PRIMARY KEY ASC AUTOINCREMENT,
"key" varchar(255) NOT NULL,
"content" text NOT NULL,
"plugin" varchar(8) NOT NULL,
"version" varchar(255) NOT NULL,
"is_published" bool NOT NULL,
"meta" text
);
""")
con.execute('CREATE INDEX IF NOT EXISTS "content_io_node_key" ON "content_io_node" ("key");')
def start_debug(self):
self.queries = []
self.debug = True
def stop_debug(self):
self.queries = []
self.debug = False
def _call(self, command, query, **params):
with self._connection as con:
cursor = con.cursor()
sql = command + ' ' + query
cursor.execute(sql, params)
if self.debug:
self.queries.append({'sql': sql, 'params': params})
return cursor
def _call_select(self, query, **params):
return self._call('SELECT', query, **params)
def _call_insert(self, query, **params):
self._call('INSERT INTO content_io_node', query, **params)
def _call_update(self, query, **params):
self._call('UPDATE content_io_node SET', query, **params)
def _call_delete(self, where='', **params):
command = 'DELETE FROM content_io_node'
if where:
command += ' WHERE'
self._call(command, where, **params)
def publish(self, uri, **meta):
node = self._get(uri)
if not node['is_published']:
# Assign version number
if not node['version'].isdigit():
result = self._call_select('version FROM content_io_node WHERE key=:key', key=node['key'])
revisions = (r[0] for r in result.fetchall())
version = self._get_next_version(revisions)
node['version'] = version
# Un publish any other revision
self._call_update('is_published=0 WHERE key=:key', key=node['key'])
# Publish this version
node['meta'] = self._merge_meta(node['meta'], meta)
node['is_published'] = 1
self._call_update('version=:version, is_published=1, meta=:meta WHERE id=:id',
id=node['id'],
version=node['version'],
meta=node['meta'])
return self._serialize(uri, node)
def get_revisions(self, uri):
key = self._build_key(uri)
nodes = self._call_select('plugin, version, is_published FROM content_io_node WHERE key=:key', key=key)
return [(uri.clone(ext=ext, version=ver), bool(pub)) for ext, ver, pub in nodes.fetchall()]
def search(self, uri):
query = 'DISTINCT key, plugin FROM content_io_node'
where = {}
if uri.scheme:
where['key LIKE :scheme'] = 'scheme', uri.scheme + '%'
if uri.namespace:
where['key LIKE :namespace'] = 'namespace', '%://' + uri.namespace + '@%'
if uri.path:
where['key LIKE :path'] = 'path', '%@' + uri.path + '%'
if where:
query += ' WHERE ' + ' AND '.join(where.keys())
query += ' ORDER BY key, plugin'
nodes = self._call_select(query, **dict(where.values()))
return [URI(key).clone(ext=ext) for key, ext in nodes.fetchall()]
def _get(self, uri):
columns = ('id', 'key', 'content', 'plugin', 'version', 'is_published', 'meta')
query = ', '.join(columns) + ' FROM content_io_node WHERE '
statements = ['key=:key']
params = {'key': self._build_key(uri)}
if uri.ext:
statements.append('plugin=:plugin')
params['plugin'] = uri.ext
if uri.version:
statements.append('version=:version')
params['version'] = uri.version
else:
statements.append('is_published=1')
query += ' AND '.join(statements)
result = self._call_select(query, **params)
node = result.fetchone()
if node is None:
raise NodeDoesNotExist('Node for uri "%s" does not exist' % uri)
else:
return dict((c, v) for c, v in six.moves.zip(columns, node))
def _create(self, uri, content, **meta):
node = {
'key': self._build_key(uri),
'content': content,
'plugin': uri.ext,
'version': uri.version,
'is_published': 0,
'meta': self._encode_meta(meta)
}
try:
self._call_insert("""
(key, content, plugin, version, is_published, meta) VALUES
(:key, :content, :plugin, :version, 0, :meta)
""", **node)
except IntegrityError as e:
raise PersistenceError('Failed to create node for uri "%s"; %s' % (uri, e))
return node
def _update(self, uri, content, **meta):
node = self._get(uri)
node.update({
'content': content,
'plugin': uri.ext,
'version': uri.version,
'meta': self._merge_meta(node['meta'], meta)
})
self._call_update("""
content=:content, plugin=:plugin, version=:version, meta=:meta
WHERE id=:id
""", **node)
return node
def _delete(self, node):
self._call_delete('id=:id', id=node['id'])
|
class SqliteBackend(DatabaseBackend):
def __init__(self, **config):
pass
def _setup(self):
pass
def start_debug(self):
pass
def stop_debug(self):
pass
def _call(self, command, query, **params):
pass
def _call_select(self, query, **params):
pass
def _call_insert(self, query, **params):
pass
def _call_update(self, query, **params):
pass
def _call_delete(self, where='', **params):
pass
def publish(self, uri, **meta):
pass
def get_revisions(self, uri):
pass
def search(self, uri):
pass
def _get(self, uri):
pass
def _create(self, uri, content, **meta):
pass
def _update(self, uri, content, **meta):
pass
def _delete(self, node):
pass
| 17 | 0 | 9 | 1 | 8 | 0 | 2 | 0.02 | 1 | 7 | 4 | 1 | 16 | 3 | 16 | 40 | 167 | 28 | 136 | 45 | 119 | 3 | 103 | 42 | 86 | 5 | 4 | 2 | 29 |
1,136 |
5monkeys/content-io
|
5monkeys_content-io/cio/conf/__init__.py
|
cio.conf.LocalSettings
|
class LocalSettings(ThreadLocalObject):
def __init__(self, base):
super(LocalSettings, self).__init__()
self._base = base
self._local = {}
def __contains__(self, key):
return key in self._local
def get(self, var):
return self._local[var]
def set(self, **vars):
def deepupdate(original, update):
for key, value in six.iteritems(original):
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
for setting, value in six.iteritems(vars):
if isinstance(value, dict):
base_value = self._base.get(setting)
if base_value and isinstance(base_value, dict):
deepupdate(base_value, value)
self._local[setting] = value
|
class LocalSettings(ThreadLocalObject):
def __init__(self, base):
pass
def __contains__(self, key):
pass
def get(self, var):
pass
def set(self, **vars):
pass
def deepupdate(original, update):
pass
| 6 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 4 | 2 | 4 | 9 | 29 | 6 | 23 | 11 | 17 | 0 | 22 | 11 | 16 | 4 | 2 | 3 | 11 |
1,137 |
5monkeys/content-io
|
5monkeys_content-io/cio/conf/__init__.py
|
cio.conf.Settings
|
class Settings(dict):
def __init__(self, conf=None, **settings):
super(Settings, self).__init__()
self._listeners = set()
self._local = LocalSettings(self)
self.configure(conf=conf, **settings)
@contextmanager
def __call__(self, **settings):
state = self.deepcopy()
self.configure(**settings)
yield
self.clear()
self.update(state)
def deepcopy(self):
copy = {}
for key, value in six.iteritems(self):
if isinstance(value, dict):
value = dict(value)
if isinstance(value, list):
value = list(value)
copy[key] = value
return copy
def configure(self, conf=None, local=False, **settings):
if isinstance(conf, ModuleType):
conf = conf.__dict__
if local:
self._local.set(**conf or settings)
else:
for setting, value in six.iteritems(conf or settings):
if setting.isupper():
self[setting] = value
for callback in self._listeners:
try:
callback()
except Exception as e:
logger.warn('Failed to notify callback about new settings; %s', e)
def watch(self, callback):
self._listeners.add(callback)
def __getitem__(self, key):
"""
First try environment specific setting, then this config
"""
if key in self._local:
return self._local.get(key)
return super(Settings, self).__getitem__(key)
__getattr__ = __getitem__
def __setattr__(self, name, value):
if name.isupper():
self[name] = value
else:
super(Settings, self).__setattr__(name, value)
|
class Settings(dict):
def __init__(self, conf=None, **settings):
pass
@contextmanager
def __call__(self, **settings):
pass
def deepcopy(self):
pass
def configure(self, conf=None, local=False, **settings):
pass
def watch(self, callback):
pass
def __getitem__(self, key):
'''
First try environment specific setting, then this config
'''
pass
def __setattr__(self, name, value):
pass
| 9 | 1 | 7 | 1 | 6 | 0 | 3 | 0.06 | 1 | 5 | 1 | 0 | 7 | 2 | 7 | 34 | 63 | 12 | 48 | 18 | 39 | 3 | 45 | 16 | 37 | 7 | 2 | 3 | 18 |
1,138 |
5monkeys/content-io
|
5monkeys_content-io/cio/environment.py
|
cio.environment.Environment
|
class Environment(ThreadLocalObject):
def __init__(self):
super(Environment, self).__init__()
self.reset()
settings.watch(self.reset)
@contextmanager
def __call__(self, name=None, i18n=None, l10n=None, g11n=None):
if name:
self.push(name)
else:
self.push_state(i18n=i18n, l10n=l10n, g11n=g11n)
yield
self.pop()
def reset(self):
self._stack = []
self.push(DEFAULT)
def push(self, name):
env = settings.ENVIRONMENT[name]
self.push_state(**env)
def _ensure_tuple(self, ns):
if isinstance(ns, tuple):
return ns
elif isinstance(ns, six.string_types):
return ns,
elif hasattr(ns, '__iter__'):
return tuple(ns)
else:
return ns,
def push_state(self, i18n=None, l10n=None, g11n=None):
i18n = self._ensure_tuple(i18n or self.i18n)
l10n = self._ensure_tuple(l10n or self.l10n)
g11n = self._ensure_tuple(g11n or self.g11n)
state = State(i18n, l10n, g11n)
self._stack.append(state)
def pop(self):
if len(self._stack) == 1:
raise IndexError('Unable to pop last environment state')
self._stack.pop()
@property
def state(self):
return self._stack[-1]
@property
def i18n(self):
return self.state.i18n
@property
def l10n(self):
return self.state.l10n
@property
def g11n(self):
return self.state.g11n
|
class Environment(ThreadLocalObject):
def __init__(self):
pass
@contextmanager
def __call__(self, name=None, i18n=None, l10n=None, g11n=None):
pass
def reset(self):
pass
def push(self, name):
pass
def _ensure_tuple(self, ns):
pass
def push_state(self, i18n=None, l10n=None, g11n=None):
pass
def pop(self):
pass
@property
def state(self):
pass
@property
def i18n(self):
pass
@property
def l10n(self):
pass
@property
def g11n(self):
pass
| 17 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 3 | 0 | 0 | 11 | 1 | 11 | 16 | 61 | 11 | 50 | 20 | 33 | 0 | 41 | 15 | 29 | 4 | 2 | 1 | 16 |
1,139 |
5monkeys/content-io
|
5monkeys_content-io/cio/__init__.py
|
cio.lazy_shortcut
|
class lazy_shortcut(object):
def __init__(self, module, target):
self._evaluated = False
self.module = module
self.targets = target.split('.', 1)
def __call__(self, *args, **kwargs):
target = self.__evaluate__()
return target(*args, **kwargs)
def __getattr__(self, item):
target = self.__evaluate__()
return getattr(target, item)
def __evaluate__(self):
if not self._evaluated:
from .utils.imports import import_module
# Evaluate target
target = import_module(self.module)
for name in self.targets:
target = getattr(target, name)
# Point module shortcut variable to target
__module__ = sys.modules[__name__]
setattr(__module__, name, target)
self._evaluated = True
return target
|
class lazy_shortcut(object):
def __init__(self, module, target):
pass
def __call__(self, *args, **kwargs):
pass
def __getattr__(self, item):
pass
def __evaluate__(self):
pass
| 5 | 0 | 6 | 1 | 5 | 1 | 2 | 0.1 | 1 | 0 | 0 | 0 | 4 | 3 | 4 | 4 | 29 | 6 | 21 | 14 | 15 | 2 | 21 | 14 | 15 | 3 | 1 | 2 | 6 |
1,140 |
5monkeys/content-io
|
5monkeys_content-io/cio/backends/exceptions.py
|
cio.backends.exceptions.PersistenceError
|
class PersistenceError(Exception):
pass
|
class PersistenceError(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 |
1,141 |
5monkeys/content-io
|
5monkeys_content-io/cio/utils/uri.py
|
cio.utils.uri.URI
|
class URI(six.text_type):
@staticmethod
def __new__(cls, uri=None, scheme=None, namespace=None, path=None, ext=None, version=None, query=None):
if isinstance(uri, URI):
return uri
elif uri is not None:
return URI._parse(uri)
else:
return URI._render(scheme, namespace, path, ext, version, query)
@classmethod
def _parse(cls, uri):
if isinstance(uri, six.binary_type):
uri = uri.decode('utf-8')
query = None
base, _, version = uri.partition(settings.URI_VERSION_SEPARATOR)
base, _, querystring = base.partition(settings.URI_QUERY_SEPARATOR)
if querystring:
query = OrderedDict()
variable_pairs = querystring.split(settings.URI_QUERY_PARAMETER_SEPARATOR)
for pair in variable_pairs:
if not pair:
continue
key, _, value = pair.partition(settings.URI_QUERY_VARIABLE_SEPARATOR)
key = unquote(key)
value = unquote(value)
query[key] = [value] if value else []
scheme, _, path = base.rpartition(settings.URI_SCHEME_SEPARATOR)
namespace, _, path = path.rpartition(settings.URI_NAMESPACE_SEPARATOR)
_path, _, ext = path.rpartition(settings.URI_EXT_SEPARATOR)
if '/' in ext:
ext = ''
else:
path = _path
if not path and ext:
path, ext = ext, ''
return cls._render(
scheme or settings.URI_DEFAULT_SCHEME,
namespace or None,
path,
ext or None,
version or None,
query or None
)
@classmethod
def _render(cls, scheme, namespace, path, ext, version, query):
def parts_gen():
if scheme:
yield scheme
yield settings.URI_SCHEME_SEPARATOR
if namespace:
yield namespace
yield settings.URI_NAMESPACE_SEPARATOR
if path:
yield path
if ext:
yield settings.URI_EXT_SEPARATOR
yield ext
if query:
yield settings.URI_QUERY_SEPARATOR
for i, (key, value) in enumerate(query.items()):
if i:
yield settings.URI_QUERY_PARAMETER_SEPARATOR
yield quote(key)
yield settings.URI_QUERY_VARIABLE_SEPARATOR
if value:
yield quote(value[0])
if version:
yield settings.URI_VERSION_SEPARATOR
yield version
uri = six.text_type.__new__(cls, u''.join(parts_gen()))
uri.scheme = scheme
uri.namespace = namespace
uri.path = path
uri.ext = ext
uri.version = version
uri.query = dict(query) if query is not None else None
return uri
def is_absolute(self):
"""
Validates that uri contains all parts except version
"""
return self.namespace and self.ext and self.scheme and self.path
def has_parts(self, *parts):
return not any(getattr(self, part, None) is None for part in parts)
def clone(self, **parts):
part = lambda part: parts.get(part, getattr(self, part))
args = (part(p) for p in ('scheme', 'namespace', 'path', 'ext', 'version', 'query'))
return URI._render(*args)
class Invalid(Exception):
pass
|
class URI(six.text_type):
@staticmethod
def __new__(cls, uri=None, scheme=None, namespace=None, path=None, ext=None, version=None, query=None):
pass
@classmethod
def _parse(cls, uri):
pass
@classmethod
def _render(cls, scheme, namespace, path, ext, version, query):
pass
def parts_gen():
pass
def is_absolute(self):
'''
Validates that uri contains all parts except version
'''
pass
def has_parts(self, *parts):
pass
def clone(self, **parts):
pass
class Invalid(Exception):
| 12 | 1 | 16 | 1 | 15 | 0 | 4 | 0.03 | 1 | 3 | 0 | 0 | 3 | 0 | 6 | 6 | 103 | 13 | 87 | 25 | 75 | 3 | 74 | 22 | 65 | 10 | 1 | 4 | 26 |
1,142 |
5monkeys/content-io
|
5monkeys_content-io/cio/utils/thread.py
|
cio.utils.thread.ThreadLocalObject
|
class ThreadLocalObject(local):
"""
Base class to inherit from when thread local instances are needed.
"""
initialized = False
def __init__(self):
if self.initialized:
raise SystemError('%s initialized too many times' % self.__class__.__name__)
self.initialized = True
|
class ThreadLocalObject(local):
'''
Base class to inherit from when thread local instances are needed.
'''
def __init__(self):
pass
| 2 | 1 | 4 | 0 | 4 | 0 | 2 | 0.5 | 1 | 1 | 0 | 4 | 1 | 0 | 1 | 5 | 10 | 1 | 6 | 3 | 4 | 3 | 6 | 3 | 4 | 2 | 1 | 1 | 2 |
1,143 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/pipes/cache.py
|
cio.pipeline.pipes.cache.CachePipe
|
class CachePipe(BasePipe):
def get_request(self, request):
response = {}
# Only get nodes from cache without specified version
uris = tuple(uri for uri, node in six.iteritems(request) if not node.uri.version)
if uris:
cached_nodes = cache.get_many(uris)
for uri, cached_node in six.iteritems(cached_nodes):
node = response[node.uri] = request.pop(uri)
self.materialize_node(node, **cached_node)
return response
def get_response(self, response):
nodes = {}
# Cache nodes without specified version (i.e. default or published)
for uri, node in six.iteritems(response):
if not uri.version:
origin_uri = node.uri.clone(namespace=uri.namespace)
nodes[origin_uri] = node.content
# Empty node meta to be coherent with cached nodes
node.meta.clear()
pipe_config = settings.CACHE.get('PIPE', {})
cache_on_get = pipe_config.get('CACHE_ON_GET', True)
if nodes and cache_on_get:
cache.set_many(nodes)
return response
def publish_response(self, response):
nodes = dict((node.uri, node.content) for uri, node in six.iteritems(response))
cache.set_many(nodes)
return response
def delete_response(self, response):
cache.delete_many(response.keys())
return response
|
class CachePipe(BasePipe):
def get_request(self, request):
pass
def get_response(self, response):
pass
def publish_response(self, response):
pass
def delete_response(self, response):
pass
| 5 | 0 | 10 | 2 | 7 | 1 | 2 | 0.1 | 1 | 2 | 0 | 0 | 4 | 0 | 4 | 5 | 44 | 12 | 29 | 15 | 24 | 3 | 29 | 15 | 24 | 4 | 2 | 2 | 9 |
1,144 |
5monkeys/content-io
|
5monkeys_content-io/cio/plugins/txt.py
|
cio.plugins.txt.TextPlugin
|
class TextPlugin(BasePlugin):
ext = 'txt'
|
class TextPlugin(BasePlugin):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 10 | 3 | 1 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,145 |
5monkeys/content-io
|
5monkeys_content-io/cio/plugins/md.py
|
cio.plugins.md.MarkdownPlugin
|
class MarkdownPlugin(TextPlugin):
ext = 'md'
def render(self, data):
import markdown
if data:
extensions = self.settings.get('EXTENSIONS', [])
return markdown.markdown(data, extensions=extensions)
|
class MarkdownPlugin(TextPlugin):
def render(self, data):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 11 | 9 | 2 | 7 | 5 | 4 | 0 | 7 | 5 | 4 | 2 | 3 | 1 | 2 |
1,146 |
5monkeys/content-io
|
5monkeys_content-io/cio/plugins/exceptions.py
|
cio.plugins.exceptions.UnknownPlugin
|
class UnknownPlugin(Exception):
pass
|
class UnknownPlugin(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 |
1,147 |
5monkeys/content-io
|
5monkeys_content-io/cio/plugins/base.py
|
cio.plugins.base.BasePlugin
|
class BasePlugin(object):
ext = None
@property
def settings(self):
return settings.get(self.ext.upper(), {})
def load(self, content):
"""
Return plugin data for content string
"""
return content
def load_node(self, node):
"""
Return plugin data and modify for raw node
"""
return self.load(node.content)
def save(self, data):
"""
Persist external plugin resources and return content string for plugin data
"""
return data
def save_node(self, node):
"""
Perform action on node, persist external plugin resources and return content string for plugin data
"""
node.content = self.save(node.content)
return node
def publish_node(self, node):
"""
Perform actions on publish and return node to persist
"""
return node
def delete(self, data):
"""
Delete external plugin resources
"""
pass
def delete_node(self, node):
"""
Delete external plugin resources
"""
self.delete(node.content)
def render(self, data):
"""
Render plugin
"""
return data
def render_node(self, node, data):
"""
Prepares node for render and returns rendered content
"""
return self.render(data)
|
class BasePlugin(object):
@property
def settings(self):
pass
def load(self, content):
'''
Return plugin data for content string
'''
pass
def load_node(self, node):
'''
Return plugin data and modify for raw node
'''
pass
def save(self, data):
'''
Persist external plugin resources and return content string for plugin data
'''
pass
def save_node(self, node):
'''
Perform action on node, persist external plugin resources and return content string for plugin data
'''
pass
def publish_node(self, node):
'''
Perform actions on publish and return node to persist
'''
pass
def delete(self, data):
'''
Delete external plugin resources
'''
pass
def delete_node(self, node):
'''
Delete external plugin resources
'''
pass
def render(self, data):
'''
Render plugin
'''
pass
def render_node(self, node, data):
'''
Prepares node for render and returns rendered content
'''
pass
| 12 | 9 | 5 | 0 | 2 | 3 | 1 | 1.13 | 1 | 0 | 0 | 3 | 10 | 0 | 10 | 10 | 62 | 11 | 24 | 13 | 12 | 27 | 23 | 12 | 12 | 1 | 1 | 0 | 10 |
1,148 |
5monkeys/content-io
|
5monkeys_content-io/cio/plugins/__init__.py
|
cio.plugins.PluginLibrary
|
class PluginLibrary(object):
def __init__(self):
self._plugins = {}
settings.watch(self.load)
def __iter__(self):
return six.iterkeys(self.plugins)
@property
def plugins(self):
if not self._plugins:
self.load()
return self._plugins
def load(self):
self._plugins = {}
for plugin_path in settings.PLUGINS:
self.register(plugin_path)
def register(self, plugin):
if isinstance(plugin, six.string_types):
try:
plugin_class = import_class(plugin)
self.register(plugin_class)
except ImportError as e:
raise ImportError('Could not import content-io plugin "%s" (Is it on sys.path?): %s' % (plugin, e))
else:
self._plugins[plugin.ext] = plugin()
def get(self, ext):
if ext not in self.plugins:
raise UnknownPlugin
return self.plugins[ext]
def resolve(self, uri):
uri = URI(uri)
return self.get(uri.ext)
|
class PluginLibrary(object):
def __init__(self):
pass
def __iter__(self):
pass
@property
def plugins(self):
pass
def load(self):
pass
def register(self, plugin):
pass
def get(self, ext):
pass
def resolve(self, uri):
pass
| 9 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 3 | 2 | 0 | 7 | 1 | 7 | 7 | 38 | 7 | 31 | 13 | 22 | 0 | 29 | 11 | 21 | 3 | 1 | 2 | 12 |
1,149 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/pipes/storage.py
|
cio.pipeline.pipes.storage.StoragePipe
|
class StoragePipe(BasePipe):
def get_request(self, request):
response = {}
stored_nodes = storage.get_many(request.keys())
for uri, stored_node in six.iteritems(stored_nodes):
node = response[node.uri] = request.pop(uri)
self.materialize_node(node, **stored_node)
return response
def get_response(self, response):
if response:
# Redirect nodes without extension (non-persisted) to default
for node in response.values():
if not node.uri.ext:
node.uri = node.uri.clone(ext=settings.URI_DEFAULT_EXT)
return response
def set_request(self, request):
for node in request.values():
stored_node, _ = storage.set(node.uri, node.content, **node.meta)
uri = stored_node['uri']
node.uri = uri
node.meta = stored_node['meta']
def delete_request(self, request):
deleted_nodes = storage.delete_many(request.keys())
for uri, deleted_node in six.iteritems(deleted_nodes):
node = request[uri]
deleted_node['content'] = None # Set content to None to signal node has been deleted
self.materialize_node(node, **deleted_node)
def publish_request(self, request):
for uri, node in list(request.items()):
try:
published_node = storage.publish(uri, **node.meta)
except NodeDoesNotExist:
request.pop(uri)
else:
node = request[uri]
self.materialize_node(node, **published_node)
|
class StoragePipe(BasePipe):
def get_request(self, request):
pass
def get_response(self, response):
pass
def set_request(self, request):
pass
def delete_request(self, request):
pass
def publish_request(self, request):
pass
| 6 | 0 | 8 | 1 | 7 | 0 | 3 | 0.06 | 1 | 2 | 1 | 0 | 5 | 0 | 5 | 6 | 45 | 9 | 35 | 19 | 29 | 2 | 35 | 19 | 29 | 4 | 2 | 3 | 13 |
1,150 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/pipes/storage.py
|
cio.pipeline.pipes.storage.NamespaceFallbackPipe
|
class NamespaceFallbackPipe(BasePipe):
def get_request(self, request):
response = {}
fallback_uris = {}
# Build fallback URI map
for uri, node in six.iteritems(request):
# if node.uri != node.initial_uri:
namespaces = getattr(node.env, uri.scheme)[1:]
if namespaces:
uris = [uri.clone(namespace=namespace) for namespace in namespaces]
fallback_uris[node.uri] = uris
# Fetch nodes from storage, each fallback level slice at a time
while fallback_uris:
level_uris = dict((fallback.pop(0), uri) for uri, fallback in six.iteritems(fallback_uris))
stored_nodes = storage.get_many(level_uris.keys())
# Set node fallback content and add to response
for uri, stored_node in six.iteritems(stored_nodes):
requested_uri = level_uris[uri]
node = response[node.uri] = request.pop(requested_uri)
self.materialize_node(node, **stored_node)
# Remove exhausted uris that has run out of fallback namespaces
for uri, fallback in list(fallback_uris.items()):
if not fallback:
fallback_uris.pop(uri)
return response
|
class NamespaceFallbackPipe(BasePipe):
def get_request(self, request):
pass
| 2 | 0 | 29 | 5 | 19 | 5 | 7 | 0.25 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 2 | 31 | 6 | 20 | 11 | 18 | 5 | 20 | 11 | 18 | 7 | 2 | 3 | 7 |
1,151 |
5monkeys/content-io
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_content-io/tests/test_storage.py
|
tests.test_storage.StorageTest.test_bogus_backend.BogusStorage
|
class BogusStorage(CacheBackend, StorageBackend):
pass
|
class BogusStorage(CacheBackend, StorageBackend):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
1,152 |
5monkeys/content-io
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_content-io/cio/utils/uri.py
|
cio.utils.uri.URI.Invalid
|
class Invalid(Exception):
pass
|
class Invalid(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 |
1,153 |
5monkeys/content-io
|
5monkeys_content-io/cio/utils/formatters.py
|
cio.utils.formatters.ContentFormatter
|
class ContentFormatter(Formatter):
"""
ContentFormatter uses string formatting as a template engine,
not raising key/index/value errors, and keeps braces and variable-like parts in place.
"""
def get_value(self, key, args, kwargs):
try:
return super(ContentFormatter, self).get_value(key, args, kwargs)
except (IndexError, KeyError):
if (PY26 or six.PY3) and key == u'\0':
# PY26: Handle of non-indexed variable -> Turn null byte into {}
return type(key)(u'{}')
else:
# PY27: Not a context variable -> Keep braces
return self._brace_key(key)
def convert_field(self, value, conversion):
if conversion and isinstance(value, six.string_types) and value[0] == u'{' and value[-1] == u'}':
# Value is wrapped with braces and therefore not a context variable -> Keep conversion as value
return self._inject_conversion(value, conversion)
else:
return super(ContentFormatter, self).convert_field(value, conversion)
def format_field(self, value, format_spec):
try:
return super(ContentFormatter, self).format_field(value, format_spec)
except ValueError:
# Unable to format value and therefore not a context variable -> Keep format_spec as value
return self._inject_format_spec(value, format_spec)
def parse(self, format_string):
if PY26 or six.PY3:
# PY26 does not support non-indexed variables -> Place null byte for later removal
# PY3 does not like mixing non-indexed and indexed variables to we disable them here too.
format_string = format_string.replace('{}', '{\0}')
parsed_bits = super(ContentFormatter, self).parse(format_string)
# Double braces are treated as escaped -> re-duplicate when parsed
return self._escape(parsed_bits)
def get_field(self, field_name, args, kwargs):
return super(ContentFormatter, self).get_field(field_name, args, kwargs)
def _brace_key(self, key):
"""
key: 'x' -> '{x}'
"""
if isinstance(key, six.integer_types):
t = str
key = t(key)
else:
t = type(key)
return t(u'{') + key + t(u'}')
def _inject_conversion(self, value, conversion):
"""
value: '{x}', conversion: 's' -> '{x!s}'
"""
t = type(value)
return value[:-1] + t(u'!') + conversion + t(u'}')
def _inject_format_spec(self, value, format_spec):
"""
value: '{x}', format_spec: 'f' -> '{x:f}'
"""
t = type(value)
return value[:-1] + t(u':') + format_spec + t(u'}')
def _escape(self, bits):
"""
value: 'foobar {' -> 'foobar {{'
value: 'x}' -> 'x}}'
"""
# for value, field_name, format_spec, conversion in bits:
while True:
try:
value, field_name, format_spec, conversion = next(bits)
if value:
end = value[-1]
if end in (u'{', u'}'):
value += end
yield value, field_name, format_spec, conversion
except StopIteration:
break
|
class ContentFormatter(Formatter):
'''
ContentFormatter uses string formatting as a template engine,
not raising key/index/value errors, and keeps braces and variable-like parts in place.
'''
def get_value(self, key, args, kwargs):
pass
def convert_field(self, value, conversion):
pass
def format_field(self, value, format_spec):
pass
def parse(self, format_string):
pass
def get_field(self, field_name, args, kwargs):
pass
def _brace_key(self, key):
'''
key: 'x' -> '{x}'
'''
pass
def _inject_conversion(self, value, conversion):
'''
value: '{x}', conversion: 's' -> '{x!s}'
'''
pass
def _inject_format_spec(self, value, format_spec):
'''
value: '{x}', format_spec: 'f' -> '{x:f}'
'''
pass
def _escape(self, bits):
'''
value: 'foobar {' -> 'foobar {{'
value: 'x}' -> 'x}}'
'''
pass
| 10 | 5 | 8 | 0 | 5 | 2 | 2 | 0.5 | 1 | 7 | 0 | 0 | 9 | 0 | 9 | 18 | 86 | 11 | 50 | 16 | 40 | 25 | 47 | 16 | 37 | 5 | 1 | 4 | 19 |
1,154 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/pipes/plugin.py
|
cio.pipeline.pipes.plugin.PluginPipe
|
class PluginPipe(BasePipe):
def render_response(self, response):
for node in response.values():
try:
plugin = plugins.resolve(node.uri)
except UnknownPlugin:
raise ImproperlyConfigured('Unknown plugin "%s" or improperly configured pipeline for node "%s".' % (
node.uri.ext,
node.uri
))
else:
data = plugin.load_node(node)
node.content = plugin.render_node(node, data)
return response
def get_response(self, response):
return self.render_response(response)
def set_request(self, request):
for node in request.values():
try:
plugin = plugins.resolve(node.uri)
except UnknownPlugin:
pass
# TODO: Should we maybe raise here?
else:
node = plugin.save_node(node)
def set_response(self, response):
return self.render_response(response)
def publish_request(self, request):
for uri, node in list(request.items()):
try:
plugin = plugins.resolve(uri)
except UnknownPlugin:
pass
# TODO: Should we maybe raise here?
else:
node = plugin.publish_node(node)
def publish_response(self, response):
return self.render_response(response)
def delete_response(self, response):
for node in response.values():
try:
plugin = plugins.resolve(node.uri)
if node.content is not empty:
plugin.delete_node(node)
except UnknownPlugin:
pass
# TODO: Should we maybe raise here?
return response
|
class PluginPipe(BasePipe):
def render_response(self, response):
pass
def get_response(self, response):
pass
def set_request(self, request):
pass
def set_response(self, response):
pass
def publish_request(self, request):
pass
def publish_response(self, response):
pass
def delete_response(self, response):
pass
| 8 | 0 | 7 | 0 | 6 | 0 | 2 | 0.07 | 1 | 3 | 2 | 0 | 7 | 0 | 7 | 8 | 57 | 9 | 45 | 17 | 37 | 3 | 42 | 17 | 34 | 4 | 2 | 3 | 16 |
1,155 |
5monkeys/content-io
|
5monkeys_content-io/cio/pipeline/pipes/meta.py
|
cio.pipeline.pipes.meta.MetaPipe
|
class MetaPipe(BasePipe):
def set_request(self, request):
for node in request.values():
node.meta['modified_at'] = self._utc_timestamp()
def publish_request(self, request):
for node in request.values():
node.meta['published_at'] = self._utc_timestamp()
def _utc_timestamp(self):
return int(mktime(datetime.utcnow().timetuple()))
|
class MetaPipe(BasePipe):
def set_request(self, request):
pass
def publish_request(self, request):
pass
def _utc_timestamp(self):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 4 | 12 | 3 | 9 | 6 | 5 | 0 | 9 | 6 | 5 | 2 | 2 | 1 | 5 |
1,156 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.UUIDModel
|
class UUIDModel(BananasUUIDModel, BananasModel):
text = models.CharField(max_length=255)
parent = models.ForeignKey("UUIDModel", null=True, on_delete=models.CASCADE)
|
class UUIDModel(BananasUUIDModel, BananasModel):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
1,157 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.URLSecretModel
|
class URLSecretModel(BananasModel):
# num_bytes=25 forces the base64 algorithm to pad
secret = URLSecretField(num_bytes=25, min_bytes=25)
|
class URLSecretModel(BananasModel):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 2 | 2 | 1 | 1 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,158 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.Simple
|
class Simple(BananasModel):
name = models.CharField(max_length=255)
objects = SimpleManager()
|
class Simple(BananasModel):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
1,159 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.SpecialModelAdmin
|
class SpecialModelAdmin(admin.ModelAdminView):
pass
|
class SpecialModelAdmin(admin.ModelAdminView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
1,160 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/models.py
|
example.models.Monkey
|
class Monkey(TimeStampedModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def get_absolute_url(self):
return 'https://www.5monkeys.se/'
|
class Monkey(TimeStampedModel):
def get_absolute_url(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
1,161 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/admin.py
|
tests.admin.SimpleAdminView
|
class SimpleAdminView(admin.AdminView):
permissions = [
("can_do_special_stuff", "Can do special stuff"),
]
tools = [
("Special Action", "admin:tests_simple_special", "can_do_special_stuff"),
admin.ViewTool(
"Even more special action",
"https://example.org",
html_class="addlink",
),
]
def get_urls(self) -> List[URLPattern]:
return [
re_path(
r"^custom/$",
self.admin_view(self.custom_view),
name="tests_simple_custom",
),
re_path(
r"^special/$",
self.admin_view(
self.special_permission_view, perm="can_do_special_stuff"
),
name="tests_simple_special",
),
]
def get(self, request: HttpRequest) -> HttpResponse:
return self.render("simple.html", {"context": "get"})
def custom_view(self, request: HttpRequest) -> HttpResponse:
assert self.has_access() # For coverage...
return self.render("simple.html", {"context": "custom"})
def special_permission_view(self, request: HttpRequest) -> HttpResponse:
return self.render("simple.html", {"context": "special"})
|
class SimpleAdminView(admin.AdminView):
def get_urls(self) -> List[URLPattern]:
pass
def get_urls(self) -> List[URLPattern]:
pass
def custom_view(self, request: HttpRequest) -> HttpResponse:
pass
def special_permission_view(self, request: HttpRequest) -> HttpResponse:
pass
| 5 | 0 | 6 | 0 | 6 | 0 | 1 | 0.03 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 14 | 38 | 4 | 34 | 7 | 29 | 1 | 12 | 7 | 7 | 1 | 2 | 0 | 4 |
1,162 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.SimpleManager
|
class SimpleManager(ModelDictManagerMixin, Manager):
pass
|
class SimpleManager(ModelDictManagerMixin, Manager):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
1,163 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/test_db_url.py
|
tests.test_db_url.DBURLTest
|
class DBURLTest(TestCase):
def test_sqlite_memory(self):
conf = url.database_conf_from_url("sqlite://")
self.assertDictEqual(
conf,
{
"ENGINE": "django.db.backends.sqlite3",
"NAME": "",
"USER": None,
"HOST": None,
"PORT": None,
"PARAMS": {},
"SCHEMA": None,
"PASSWORD": None,
},
)
def test_db_url(self):
conf = url.database_conf_from_url(
"pgsql://joar:[email protected]:4242/tweets/tweetschema?hello=world"
)
self.assertDictEqual(
conf,
{
"ENGINE": "django.db.backends.postgresql_psycopg2",
"HOST": "5monkeys.se",
"NAME": "tweets",
"PARAMS": {"hello": "world"},
"PASSWORD": "hunter2",
"PORT": 4242,
"SCHEMA": "tweetschema",
"USER": "joar",
},
)
def test_alias(self):
self.assertEqual(repr(url.Alias(target="x")), '<Alias to "x">')
def test_register(self):
url.register_engine("abc", "a.b.c")
conf = url.database_conf_from_url("abc://5monkeys.se")
self.maxDiff = None
self.assertDictEqual(
conf,
{
"ENGINE": "a.b.c",
"HOST": "5monkeys.se",
"NAME": "",
"PARAMS": {},
"PASSWORD": None,
"PORT": None,
"SCHEMA": None,
"USER": None,
},
)
def test_resolve(self):
url.register_engine("abc", "a.b.c")
self.assertRaises(KeyError, url.resolve, cursor={}, key="xyz")
def test_get_engine(self):
self.assertRaisesMessage(
KeyError,
"postgres has no sub-engines",
url.get_engine,
"postgres+psycopg2+postgis",
)
url.register_engine("a", ["b"])
self.assertRaisesRegex(ValueError, r"^django-bananas\.url", url.get_engine, "a")
url.register_engine("a", ["a", {"b": "c"}])
self.assertEqual(url.get_engine("a+b"), "c")
def test_parse(self):
self.assertRaises(ValueError, url.parse_path, None)
self.assertRaisesRegex(
Exception, "^Your url is", url.parse_database_url, "sqlite://:memory:"
)
def test_db_url_with_slashes(self):
name = quote("/var/db/tweets.sqlite", safe="")
conf = url.database_conf_from_url(f"sqlite3:///{name}")
self.assertDictEqual(
conf,
{
"ENGINE": "django.db.backends.sqlite3",
"NAME": "/var/db/tweets.sqlite",
"USER": None,
"HOST": None,
"PORT": None,
"PARAMS": {},
"SCHEMA": None,
"PASSWORD": None,
},
)
|
class DBURLTest(TestCase):
def test_sqlite_memory(self):
pass
def test_db_url(self):
pass
def test_alias(self):
pass
def test_register(self):
pass
def test_resolve(self):
pass
def test_get_engine(self):
pass
def test_parse(self):
pass
def test_db_url_with_slashes(self):
pass
| 9 | 0 | 11 | 0 | 11 | 0 | 1 | 0 | 1 | 4 | 1 | 0 | 8 | 1 | 8 | 8 | 97 | 10 | 87 | 15 | 78 | 0 | 30 | 15 | 21 | 1 | 1 | 0 | 8 |
1,164 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/test_models.py
|
tests.test_models.TimeStampedModelTest
|
class TimeStampedModelTest(TestCase):
def test_date_modified(self):
parent = Parent.objects.create(name="foo")
self.assertIsNotNone(parent.date_created)
self.assertIsNotNone(parent.date_modified)
pre_date_modified = parent.date_modified
parent.name = "bar"
parent.save()
parent.refresh_from_db()
self.assertNotEqual(parent.date_modified, pre_date_modified)
self.assertEqual(parent.name, "bar")
pre_date_modified = parent.date_modified
parent.name = "baz"
parent.save(update_fields=["name"])
parent.refresh_from_db()
self.assertNotEqual(parent.date_modified, pre_date_modified)
self.assertEqual(parent.name, "baz")
parent.save(update_fields={"name"})
parent.save(update_fields=("name",))
|
class TimeStampedModelTest(TestCase):
def test_date_modified(self):
pass
| 2 | 0 | 21 | 3 | 18 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 22 | 3 | 19 | 4 | 17 | 0 | 19 | 4 | 17 | 1 | 1 | 0 | 1 |
1,165 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/test_models.py
|
tests.test_models.QuerySetTest
|
class QuerySetTest(TestCase):
def setUp(self):
self.simple = Simple.objects.create(name="S")
self.parent = Parent.objects.create(name="A")
self.child = Child.objects.create(name="B", parent=self.parent)
self.other_child = Child.objects.create(name="C", parent=self.parent)
def test_modeldict(self):
d = ModelDict(foo="bar", baz__ham="spam")
self.assertIn("foo", d, 'should have key "foo"')
self.assertNotIn("baz", d, 'should not have key "baz"')
self.assertRaises(AttributeError, d.__getattr__, "x")
self.assertTrue(hasattr(d, "foo"), 'should not have real attr "foo"')
self.assertEqual(d.foo, "bar")
self.assertEqual(d.baz__ham, "spam")
self.assertIsInstance(d.baz, ModelDict, "should lazy resolve sub dict")
def test_modeldict_from_model(self):
d = ModelDict.from_model(self.child, "id", "parent__id", "parent__name")
self.assertDictEqual(
d, {"id": self.child.id, "parent__id": self.parent.id, "parent__name": "A"}
)
self.assertTrue(d.parent)
_child = Child.objects.create(name="B")
d = ModelDict.from_model(_child, "id", "parent__id", "parent__name")
self.assertDictEqual(
d,
{
"id": _child.id,
"parent": None,
},
)
_node_parent = Node.objects.create(name="A", parent=None)
_node_child = Node.objects.create(name="B", parent=_node_parent)
_node_grandchild = Node.objects.create(name="C", parent=_node_child)
d = ModelDict.from_model(
_node_grandchild,
test__id="parent__parent__id",
test__name="parent__parent__name",
)
self.assertDictEqual(
d,
{
"test__id": self.parent.id,
"test__name": "A",
},
)
self.assertDictEqual(
d.test,
{
"id": self.parent.id,
"name": "A",
},
)
_node_child.parent = None
_node_child.save()
d = ModelDict.from_model(
_node_grandchild,
test__id="parent__parent__id",
test__name="parent__parent__name",
)
self.assertDictEqual(
d,
{
"test__id": None,
"test__name": None,
},
)
d = ModelDict.from_model(self.child)
self.assertEqual(len(d), 5)
def test_wrong_path(self):
self.assertRaises(
AttributeError, lambda: ModelDict.from_model(self.child, "does__not__exist")
)
def test_attribute_error(self):
self.assertRaises(
ValueError, ModelDict.from_model, self.parent, test="attribute_error"
)
def test_dicts(self):
self.assertTrue(hasattr(Parent.objects, "dicts"))
simple = Simple.objects.all().dicts("name").first() # type: ignore[attr-defined]
self.assertEqual(simple.name, self.simple.name)
simple = Simple.objects.dicts("name").first()
self.assertEqual(simple.name, self.simple.name)
child = Child.objects.dicts("name", "parent__name").first()
assert child
self.assertEqual(child.name, self.child.name)
self.assertNotIn("parent", child)
self.assertEqual(child.parent.name, self.parent.name)
def test_dicts_rename(self):
child = Child.objects.dicts("parent__name", alias="name").first()
assert child
self.assertEqual(child.alias, self.child.name)
self.assertEqual(child.parent.name, self.parent.name)
# Test that renamed fields on reverse relation fields
# will actually return all possible results
expected_dicts: List[Dict] = [
{"child_name": self.child.name},
{"child_name": self.other_child.name},
]
self.assertListEqual(
list(Parent.objects.filter(name="A").dicts(child_name="child__name")),
expected_dicts,
)
# Test renaming a field with another that's not renamed
expected_dicts = [
{"id": self.parent.pk, "child_name": self.child.name},
{"id": self.parent.pk, "child_name": self.other_child.name},
]
self.assertListEqual(
list(Parent.objects.filter(name="A").dicts("id", child_name="child__name")),
expected_dicts,
)
# Test multiple renamed fileds together
expected_dicts = [
{"id": self.child.pk, "child_name": self.child.name},
{"id": self.other_child.pk, "child_name": self.other_child.name},
]
self.assertListEqual(
list(
Parent.objects.filter(name="A").dicts(
id="child__id", child_name="child__name"
)
),
expected_dicts,
)
# Test multiple renamed fileds together with another that's not
expected_dicts = [
{
"id": self.parent.pk,
"child_id": self.child.pk,
"child_name": self.child.name,
},
{
"id": self.parent.pk,
"child_id": self.other_child.pk,
"child_name": self.other_child.name,
},
]
self.assertListEqual(
list(
Parent.objects.filter(name="A").dicts(
"id", child_id="child__id", child_name="child__name"
)
),
expected_dicts,
)
def test_uuid_model(self):
first = UUIDModel.objects.create(text="first")
second = UUIDModel.objects.create(text="second", parent=first)
self.assertEqual(UUIDModel.objects.get(parent=first), second)
self.assertEqual(UUIDModel.objects.get(parent__pk=first.pk), second)
def test_secret_field(self):
model = SecretModel.objects.create()
field = SecretModel._meta.get_field("secret")
field_length = field.get_field_length(field.num_bytes)
self.assertEqual(len(model.secret), field_length)
field.auto = False
self.assertEqual(len(field.pre_save(model, False)), field_length)
self.assertRaisesMessage(
ValidationError,
"SecretField.get_random_bytes returned None",
field._check_random_bytes,
None,
)
self.assertRaisesMessage(
ValidationError,
"Too few random bytes received from get_random_bytes. "
"Number of bytes=3, min_length=32",
field._check_random_bytes,
"123",
)
def test_url_secret_field_field_length(self):
model = URLSecretModel.objects.create()
field = URLSecretModel._meta.get_field("secret")
field_length = field.get_field_length(field.num_bytes)
# secret value may be shorter
self.assertLessEqual(len(model.secret), field_length)
def test_url_secret_field_is_safe(self):
model = URLSecretModel.objects.create()
self.assertRegex(model.secret, r"^[A-Za-z0-9._-]+$")
def test_nested(self):
md = ModelDict()
md._nested = {"x": 1} # type: ignore[dict-item]
self.assertEqual(md.x, 1)
def test_expand(self):
md = ModelDict(on=False, monkey__name="Pato", monkey__banana=True)
md.expand()
self.assertEqual(md, {"on": False, "monkey": {"name": "Pato", "banana": True}})
|
class QuerySetTest(TestCase):
def setUp(self):
pass
def test_modeldict(self):
pass
def test_modeldict_from_model(self):
pass
def test_wrong_path(self):
pass
def test_attribute_error(self):
pass
def test_dicts(self):
pass
def test_dicts_rename(self):
pass
def test_uuid_model(self):
pass
def test_secret_field(self):
pass
def test_url_secret_field_field_length(self):
pass
def test_url_secret_field_is_safe(self):
pass
def test_nested(self):
pass
def test_expand(self):
pass
| 14 | 0 | 16 | 2 | 14 | 1 | 1 | 0.04 | 1 | 11 | 8 | 0 | 13 | 4 | 13 | 13 | 227 | 40 | 181 | 39 | 167 | 8 | 92 | 39 | 78 | 1 | 1 | 0 | 13 |
1,166 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/i18n.py
|
bananas.admin.i18n.RawTranslationCatalog
|
class RawTranslationCatalog(JavaScriptCatalog):
domain = "django"
def render_to_response(self, context: Dict[str, Any], **response_kwargs: Any) -> Dict[str, Any]: # type: ignore[override]
return context
|
class RawTranslationCatalog(JavaScriptCatalog):
def render_to_response(self, context: Dict[str, Any], **response_kwargs: Any) -> Dict[str, Any]:
pass
| 2 | 0 | 2 | 0 | 2 | 1 | 1 | 0.25 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 1 | 4 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 0 | 1 |
1,167 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/admin_api.py
|
tests.drf.admin_api.HamSerializer
|
class HamSerializer(serializers.Serializer):
spam = serializers.CharField()
|
class HamSerializer(serializers.Serializer):
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 |
1,168 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/extension.py
|
bananas.admin.extension.ViewTool
|
class ViewTool:
def __init__(
self, text: str, link: str, perm: Optional[str] = None, **attrs: Any
) -> None:
self.text = text
self._link = link
self.perm = perm
html_class = attrs.pop("html_class", None)
if html_class is not None:
attrs.setdefault("class", html_class)
self._attrs = attrs
@property
def attrs(self) -> SafeText:
return mark_safe(" ".join(f"{k}={v}" for k, v in self._attrs.items()))
@property
def link(self) -> str:
if "/" not in self._link:
return reverse(self._link)
return self._link
|
class ViewTool:
def __init__(
self, text: str, link: str, perm: Optional[str] = None, **attrs: Any
) -> None:
pass
@property
def attrs(self) -> SafeText:
pass
@property
def link(self) -> str:
pass
| 6 | 0 | 6 | 0 | 5 | 0 | 2 | 0 | 0 | 2 | 0 | 0 | 3 | 4 | 3 | 3 | 22 | 3 | 19 | 13 | 11 | 0 | 15 | 9 | 11 | 2 | 0 | 1 | 5 |
1,169 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/extension.py
|
bananas.admin.extension.ExtendedAdminSite
|
class ExtendedAdminSite(AdminSite):
enable_nav_sidebar = False
default_settings: ClassVar[Dict[str, Any]] = {
"INHERIT_REGISTERED_MODELS": env.get_bool(
"DJANGO_ADMIN_INHERIT_REGISTERED_MODELS", True
),
"SITE_TITLE": env.get("DJANGO_ADMIN_SITE_TITLE", AdminSite.site_title),
"SITE_HEADER": env.get("DJANGO_ADMIN_SITE_HEADER", "admin"),
"SITE_VERSION": env.get("DJANGO_ADMIN_SITE_VERSION", django.__version__),
"INDEX_TITLE": env.get("DJANGO_ADMIN_INDEX_TITLE", AdminSite.index_title),
"PRIMARY_COLOR": env.get("DJANGO_ADMIN_PRIMARY_COLOR", "#34A77B"),
"SECONDARY_COLOR": env.get("DJANGO_ADMIN_SECONDARY_COLOR", "#20AA76"),
"LOGO": env.get("DJANGO_ADMIN_LOGO", "admin/bananas/img/django.svg"),
"LOGO_ALIGN": env.get("DJANGO_ADMIN_LOGO_ALIGN", "middle"),
"LOGO_STYLE": env.get("DJANGO_ADMIN_LOGO_STYLE"),
}
settings: Dict[str, Any]
def __init__(self, name: str = "admin") -> None:
super().__init__(name=name)
self.settings = dict(self.default_settings)
self.settings.update(getattr(django_settings, "ADMIN", {}))
self.site_title = self.settings["SITE_TITLE"]
self.site_header = self.settings["SITE_HEADER"]
self.index_title = self.settings["INDEX_TITLE"]
def each_context(self, request: HttpRequest) -> Dict[str, Any]:
context = super().each_context(request)
context.update(settings=self.settings)
return context
@property
def urls(self) -> Tuple[List[Union[URLResolver, URLPattern]], str, str]:
if self.settings["INHERIT_REGISTERED_MODELS"]:
for model, admin in list(django_admin_site._registry.items()):
# django_admin_site.unregister(model)
self._registry[model] = admin.__class__(model, self)
return self.get_urls(), "admin", self.name
|
class ExtendedAdminSite(AdminSite):
def __init__(self, name: str = "admin") -> None:
pass
def each_context(self, request: HttpRequest) -> Dict[str, Any]:
pass
@property
def urls(self) -> Tuple[List[Union[URLResolver, URLPattern]], str, str]:
pass
| 5 | 0 | 6 | 0 | 5 | 0 | 2 | 0.09 | 1 | 5 | 0 | 0 | 3 | 4 | 3 | 3 | 39 | 4 | 34 | 13 | 29 | 3 | 20 | 12 | 16 | 3 | 1 | 2 | 5 |
1,170 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/extension.py
|
bananas.admin.extension.AdminView
|
class AdminView(View):
tools: ClassVar[
Optional[List[Union[Tuple[str, str], Tuple[str, str, str], ViewTool]]]
] = None
action: ClassVar[Optional[str]] = None
admin: ClassVar[Optional[ModelAdminView]] = None
label: str
verbose_name: str
request: WSGIRequest
def dispatch(
self, request: HttpRequest, *args: Any, **kwargs: Any
) -> HttpResponseBase:
# Try to fetch set action first.
# This should be the view name for custom views
action = self.action
if action is None:
return super().dispatch(request, *args, **kwargs)
handler: Callable[..., HttpResponseBase] = getattr(self, action)
return handler(request, *args, **kwargs)
def get_urls(self) -> List[URLPattern]:
"""Should return a list of urls
Views should be wrapped in `self.admin_view` if the view isn't
supposed to be accessible for non admin users.
Omitting this can cause threading issues.
Example:
return [
url(r'^custom/$',
self.admin_view(self.custom_view))
]
"""
return []
def get_tools(
self,
) -> Optional[List[Union[Tuple[str, str], Tuple[str, str, str], ViewTool]]]:
# Override point, self.request is available.
return self.tools
def get_view_tools(self) -> List[ViewTool]:
tools = []
all_tools = self.get_tools()
if all_tools:
for tool in all_tools:
if isinstance(tool, (list, tuple)):
perm = None
# Mypy doesn't change type on a len(...) call
# See: https://github.com/python/mypy/issues/1178
if len(tool) == 3:
tool, perm = tool[:-1], tool[-1]
text, link = tool
tool = ViewTool(text, link, perm=perm)
else:
# Assume ViewTool
perm = tool.perm
if perm and not self.has_permission(perm):
continue
tools.append(tool)
return tools
def admin_view(
self,
view: Callable[..., HttpResponseBase],
perm: Optional[str] = None,
**initkwargs: Any,
) -> Callable[..., HttpResponseBase]:
assert self.admin is not None
view = self.__class__.as_view(
action=view.__name__, admin=self.admin, **initkwargs
)
return self.admin.admin_view(view, perm=perm)
def get_permission(self, perm: str) -> str:
assert self.admin is not None
return self.admin.get_permission(perm)
def has_permission(self, perm: str) -> bool:
perm = self.get_permission(perm)
return self.request.user.has_perm(perm)
def has_access(self) -> bool:
assert self.admin is not None
return self.has_permission(self.admin.access_permission)
def get_context(self, **extra: Any) -> Dict[str, Any]:
assert self.admin is not None
return self.admin.get_context(
self.request, view_tools=self.get_view_tools(), **extra
)
def render(
self, template: str, context: Optional[Dict[str, Any]] = None
) -> HttpResponse:
extra = context or {}
return render(self.request, template, self.get_context(**extra))
|
class AdminView(View):
def dispatch(
self, request: HttpRequest, *args: Any, **kwargs: Any
) -> HttpResponseBase:
pass
def get_urls(self) -> List[URLPattern]:
'''Should return a list of urls
Views should be wrapped in `self.admin_view` if the view isn't
supposed to be accessible for non admin users.
Omitting this can cause threading issues.
Example:
return [
url(r'^custom/$',
self.admin_view(self.custom_view))
]
'''
pass
def get_tools(
self,
) -> Optional[List[Union[Tuple[str, str], Tuple[str, str, str], ViewTool]]]:
pass
def get_view_tools(self) -> List[ViewTool]:
pass
def admin_view(
self,
view: Callable[..., HttpResponseBase],
perm: Optional[str] = None,
**initkwargs: Any,
) -> Callable[..., HttpResponseBase]:
pass
def get_permission(self, perm: str) -> str:
pass
def has_permission(self, perm: str) -> bool:
pass
def has_access(self) -> bool:
pass
def get_context(self, **extra: Any) -> Dict[str, Any]:
pass
def render(
self, template: str, context: Optional[Dict[str, Any]] = None
) -> HttpResponse:
pass
| 11 | 1 | 8 | 1 | 6 | 2 | 2 | 0.23 | 1 | 7 | 1 | 7 | 10 | 0 | 10 | 10 | 102 | 16 | 70 | 33 | 48 | 16 | 52 | 22 | 41 | 6 | 1 | 4 | 16 |
1,171 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.BananasAdminAPI
|
class BananasAdminAPI(BananasAPI, viewsets.GenericViewSet):
pass
|
class BananasAdminAPI(BananasAPI, viewsets.GenericViewSet):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 5 | 0 | 0 | 0 | 4 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
1,172 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/test_models.py
|
tests.test_models.EnvTest
|
class EnvTest(TestCase):
def test_parse_bool(self):
self.assertTrue(environment.parse_bool("True"))
self.assertTrue(environment.parse_bool("true"))
self.assertTrue(environment.parse_bool("TRUE"))
self.assertTrue(environment.parse_bool("yes"))
self.assertTrue(environment.parse_bool("1"))
self.assertFalse(environment.parse_bool("False"))
self.assertFalse(environment.parse_bool("0"))
self.assertRaises(ValueError, environment.parse_bool, "foo")
def test_parse_int(self):
self.assertEqual(environment.parse_int("123"), 123)
self.assertEqual(environment.parse_int("0644"), 420)
self.assertEqual(environment.parse_int("0o644"), 420)
self.assertEqual(environment.parse_int("0"), 0)
def test_parse_tuple(self):
self.assertTupleEqual(environment.parse_tuple("a"), ("a",))
self.assertTupleEqual(environment.parse_tuple(" a,b, c "), ("a", "b", "c"))
def test_parse_list(self):
self.assertListEqual(environment.parse_list("a, b, c"), ["a", "b", "c"])
def test_parse_set(self):
self.assertSetEqual(environment.parse_set("b, a, c"), {"a", "b", "c"})
def test_env_wrapper(self):
self.assertEqual(env.get("foo", "bar"), "bar")
self.assertEqual(env.get("foo", "bar"), "bar")
self.assertIsNone(env.get_bool("foobar"))
self.assertFalse(env.get_bool("foobar", False))
environ["foobar"] = "True"
self.assertTrue(env.get_bool("foobar", False))
environ["foobar"] = "Ture"
self.assertIsNone(env.get_bool("foobar"))
self.assertFalse(env.get_bool("foobar", False))
environ["foobar"] = "123"
self.assertEqual(env.get_int("foobar"), 123)
environ["foobar"] = "a, b, c"
tuple_result = env.get_tuple("foobar")
assert tuple_result is not None
self.assertTupleEqual(tuple_result, ("a", "b", "c"))
environ["foobar"] = "a, b, c"
list_result = env.get_list("foobar")
assert list_result is not None
self.assertListEqual(list_result, ["a", "b", "c"])
environ["foobar"] = "a, b, c"
set_result = env.get_set("foobar")
assert set_result is not None
self.assertSetEqual(set_result, {"a", "b", "c"})
self.assertEqual(env.get("foobar"), "a, b, c")
self.assertEqual(env["foobar"], "a, b, c")
|
class EnvTest(TestCase):
def test_parse_bool(self):
pass
def test_parse_int(self):
pass
def test_parse_tuple(self):
pass
def test_parse_list(self):
pass
def test_parse_set(self):
pass
def test_env_wrapper(self):
pass
| 7 | 0 | 9 | 1 | 8 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 6 | 0 | 6 | 6 | 60 | 12 | 48 | 10 | 41 | 0 | 48 | 10 | 41 | 1 | 1 | 0 | 6 |
1,173 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.SecretModel
|
class SecretModel(BananasModel):
secret = SecretField()
|
class SecretModel(BananasModel):
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 | 2 | 0 | 0 |
1,174 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_fenced_api.py
|
tests.drf.test_fenced_api.TestAllowIfUnmodifiedSince
|
class TestAllowIfUnmodifiedSince(APITestCase):
url = partial(reverse, "if-unmodified-detail")
def test_returns_bad_request_for_missing_header(self):
item = Parent.objects.create()
response = self.client.put(self.url(args=(item.pk,)), data={"name": "Great!"})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data["detail"], "Header missing in request: If-Unmodified-Since"
)
def test_returns_bad_request_for_invalid_header(self):
item = Parent.objects.create()
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_UNMODIFIED_SINCE="",
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data["detail"],
"Malformed header in request: If-Unmodified-Since",
)
def test_returns_precondition_failed_for_expired_token(self):
item = Parent.objects.create()
assert item.date_modified
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_UNMODIFIED_SINCE=http_date(item.date_modified.timestamp() - 1),
)
self.assertEqual(response.status_code, status.HTTP_412_PRECONDITION_FAILED)
self.assertEqual(
response.data["detail"],
"The resource does not fulfill the given preconditions",
)
def test_allows_request_for_valid_token(self):
item = Parent.objects.create()
assert item.date_modified
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_UNMODIFIED_SINCE=http_date(item.date_modified.timestamp()),
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertDictEqual(response.data, {"name": "Great!"})
|
class TestAllowIfUnmodifiedSince(APITestCase):
def test_returns_bad_request_for_missing_header(self):
pass
def test_returns_bad_request_for_invalid_header(self):
pass
def test_returns_precondition_failed_for_expired_token(self):
pass
def test_allows_request_for_valid_token(self):
pass
| 5 | 0 | 11 | 0 | 11 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 4 | 0 | 4 | 4 | 48 | 4 | 44 | 14 | 39 | 0 | 24 | 14 | 19 | 1 | 1 | 0 | 4 |
1,175 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/fenced_api.py
|
tests.drf.fenced_api.AllowIfUnmodifiedSinceAPI
|
class AllowIfUnmodifiedSinceAPI(FencedUpdateModelMixin, GenericViewSet):
fence = allow_if_unmodified_since()
serializer_class = SimpleSerializer
queryset = Parent.objects.all()
|
class AllowIfUnmodifiedSinceAPI(FencedUpdateModelMixin, GenericViewSet):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 5 | 0 | 0 |
1,176 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/drf/errors.py
|
bananas.drf.errors.BadRequest
|
class BadRequest(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "Validation failed"
default_code = "bad_request"
|
class BadRequest(APIException):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
1,177 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestHeaderEtagParser
|
class TestHeaderEtagParser(TestCase):
def test_can_parse_multiple_etags(self):
request = FakeRequest.fake(headers={"If-Match": '"a", "b"'})
self.assertSetEqual(header_etag_parser("If-Match")(request), {"a", "b"})
def test_can_parse_single_etag(self):
request = FakeRequest.fake(headers={"If-Match": '"a"'})
self.assertSetEqual(header_etag_parser("If-Match")(request), {"a"})
def test_raises_bad_request_error_for_missing_header(self):
request = FakeRequest.fake()
parser = header_etag_parser("If-Match")
with self.assertRaises(BadRequest) as exc_info:
parser(request)
assert isinstance(exc_info.exception.detail, ErrorDetail)
self.assertEqual(exc_info.exception.detail.code, "missing_header")
def test_raises_bad_request_for_invalid_header(self):
request = FakeRequest.fake(headers={"If-Match": ""})
parser = header_etag_parser("If-Match")
with self.assertRaises(BadRequest) as exc_info:
parser(request)
assert isinstance(exc_info.exception.detail, ErrorDetail)
self.assertEqual(exc_info.exception.detail.code, "invalid_header")
|
class TestHeaderEtagParser(TestCase):
def test_can_parse_multiple_etags(self):
pass
def test_can_parse_single_etag(self):
pass
def test_raises_bad_request_error_for_missing_header(self):
pass
def test_raises_bad_request_for_invalid_header(self):
pass
| 5 | 0 | 6 | 1 | 5 | 0 | 1 | 0 | 1 | 2 | 2 | 0 | 4 | 0 | 4 | 76 | 26 | 5 | 21 | 13 | 16 | 0 | 21 | 11 | 16 | 1 | 2 | 1 | 4 |
1,178 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestParseDateModified
|
class TestParseDateModified(TestCase):
def test_replaces_microsecond(self):
class A(TimeStampedModel):
date_modified = datetime.datetime( # type: ignore[assignment]
2021, 1, 14, 17, 30, 1, 1, tzinfo=datetime.timezone.utc
)
self.assertEqual(
parse_date_modified(A()),
datetime.datetime(2021, 1, 14, 17, 30, 1, tzinfo=datetime.timezone.utc),
)
def test_can_get_none(self):
class A(TimeStampedModel):
date_modified = None # type: ignore[assignment]
self.assertIsNone(parse_date_modified(A()))
|
class TestParseDateModified(TestCase):
def test_replaces_microsecond(self):
pass
class A(TimeStampedModel):
def test_can_get_none(self):
pass
class A(TimeStampedModel):
| 5 | 0 | 8 | 1 | 7 | 1 | 1 | 0.14 | 1 | 4 | 2 | 0 | 2 | 0 | 2 | 74 | 17 | 3 | 14 | 7 | 9 | 2 | 9 | 7 | 4 | 1 | 2 | 0 | 2 |
1,179 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_utils.py
|
tests.drf.test_utils.TestParseHeaderDatetime
|
class TestParseHeaderDatetime(TestCase):
def test_raises_missing_header(self):
request = FakeRequest.fake()
with self.assertRaises(MissingHeader):
parse_header_datetime(request, "missing")
def test_raises_invalid_header(self):
request = FakeRequest.fake(headers={"invalid": "not a date"})
with self.assertRaises(InvalidHeader):
parse_header_datetime(request, "invalid")
def test_can_parse_datetime(self):
dt = datetime.datetime(2021, 1, 14, 17, 30, 1, tzinfo=datetime.timezone.utc)
request = FakeRequest.fake(headers={"valid": http_date(dt.timestamp())})
self.assertEqual(dt, parse_header_datetime(request, "valid"))
|
class TestParseHeaderDatetime(TestCase):
def test_raises_missing_header(self):
pass
def test_raises_invalid_header(self):
pass
def test_can_parse_datetime(self):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 5 | 3 | 0 | 3 | 0 | 3 | 75 | 15 | 2 | 13 | 8 | 9 | 0 | 13 | 8 | 9 | 1 | 2 | 1 | 3 |
1,180 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/test_secrets.py
|
tests.test_secrets.SecretsTest
|
class SecretsTest(TestCase):
def setUp(self):
secrets_dir = str(Path(__file__).resolve().parent / "files")
self.env = EnvironmentVarGuard()
self.env.set(secrets.BANANAS_SECRETS_DIR_ENV_KEY, secrets_dir)
def test_get_existing_secret(self):
with self.env:
secret = secrets.get_secret("hemlis")
self.assertEqual(secret, "HEMLIS\n")
def test_get_non_existing_secret_with_no_default(self):
with self.env:
secret = secrets.get_secret("doesnotexist")
self.assertIsNone(secret)
def test_get_non_existing_secret_with_default(self):
default = "defaultvalue"
with self.env:
secret = secrets.get_secret("doesnotexist", default)
self.assertEqual(secret, default)
|
class SecretsTest(TestCase):
def setUp(self):
pass
def test_get_existing_secret(self):
pass
def test_get_non_existing_secret_with_no_default(self):
pass
def test_get_non_existing_secret_with_default(self):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 3 | 0 | 0 | 4 | 1 | 4 | 4 | 21 | 3 | 18 | 11 | 13 | 0 | 18 | 11 | 13 | 1 | 1 | 1 | 4 |
1,181 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_utils.py
|
tests.drf.test_utils.TestParseHeaderEtags
|
class TestParseHeaderEtags(TestCase):
def test_raises_missing_header(self):
request = FakeRequest.fake()
with self.assertRaises(MissingHeader):
parse_header_etags(request, "missing")
def test_raises_invalid_header(self):
request = FakeRequest.fake(headers={"invalid": ""})
with self.assertRaises(InvalidHeader):
parse_header_etags(request, "invalid")
def test_can_parse_single_etag(self):
request = FakeRequest.fake(headers={"tag": '"value"'})
self.assertSetEqual(parse_header_etags(request, "tag"), {"value"})
def test_can_parse_many_tags(self):
request = FakeRequest.fake(headers={"tag": '"a", "b"'})
self.assertSetEqual(parse_header_etags(request, "tag"), {"a", "b"})
|
class TestParseHeaderEtags(TestCase):
def test_raises_missing_header(self):
pass
def test_raises_invalid_header(self):
pass
def test_can_parse_single_etag(self):
pass
def test_can_parse_many_tags(self):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 3 | 3 | 0 | 4 | 0 | 4 | 76 | 18 | 3 | 15 | 9 | 10 | 0 | 15 | 9 | 10 | 1 | 2 | 1 | 4 |
1,182 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.Child
|
class Child(TimeStampedModel, BananasModel):
name = models.CharField(max_length=255)
parent = models.ForeignKey(Parent, null=True, on_delete=models.CASCADE)
objects = ChildManager()
|
class Child(TimeStampedModel, BananasModel):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
1,183 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/fenced_api.py
|
tests.drf.fenced_api.AllowIfMatchAPI
|
class AllowIfMatchAPI(FencedUpdateModelMixin, GenericViewSet):
fence = allow_if_match(operator.attrgetter("version"))
serializer_class = SimpleSerializer
def get_queryset(self) -> "QuerySet[Parent]":
return Parent.objects.all()
|
class AllowIfMatchAPI(FencedUpdateModelMixin, GenericViewSet):
def get_queryset(self) -> "QuerySet[Parent]":
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 1 | 26 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 5 | 0 | 1 |
1,184 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.Node
|
class Node(TimeStampedModel, BananasModel):
name = models.CharField(max_length=255)
parent = models.ForeignKey("self", null=True, on_delete=models.CASCADE)
objects = NodeManager()
|
class Node(TimeStampedModel, BananasModel):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
1,185 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestHeaderDateParser
|
class TestHeaderDateParser(TestCase):
def test_raises_bad_request_for_header_error(self):
get_header = header_date_parser("header")
with self.assertRaises(BadRequest) as exc_info:
get_header(FakeRequest.fake())
assert isinstance(exc_info.exception.detail, ErrorDetail)
self.assertEqual(exc_info.exception.detail.code, "missing_header")
def test_can_get_parsed_header_datetime(self):
dt = datetime.datetime(2021, 1, 14, 17, 30, 1, tzinfo=datetime.timezone.utc)
request = FakeRequest.fake(headers={"header": http_date(dt.timestamp())})
parsed = header_date_parser("header")(request)
self.assertEqual(parsed, dt)
|
class TestHeaderDateParser(TestCase):
def test_raises_bad_request_for_header_error(self):
pass
def test_can_get_parsed_header_datetime(self):
pass
| 3 | 0 | 6 | 1 | 6 | 0 | 1 | 0 | 1 | 4 | 2 | 0 | 2 | 0 | 2 | 74 | 14 | 2 | 12 | 8 | 9 | 0 | 12 | 7 | 9 | 1 | 2 | 1 | 2 |
1,186 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestFence
|
class TestFence(TestCase):
openapi_parameter = openapi.Parameter(
in_=openapi.IN_HEADER,
name="foo",
type=openapi.TYPE_STRING,
)
def test_check_propagates_error_from_get_token(self):
error = RuntimeError()
def get_token(_request):
raise error
def get_version(_instance):
return "a"
fence = Fence(
get_token=get_token,
compare=operator.eq,
get_version=get_version,
openapi_parameter=self.openapi_parameter,
)
with self.assertRaises(RuntimeError) as exc_info:
fence.check(FakeRequest.fake(), "a")
self.assertIs(exc_info.exception, error)
def test_check_propagates_error_from_get_version(self):
error = RuntimeError()
def get_token(_request):
return "a"
def get_version(_instance):
raise error
fence = Fence(
get_token=get_token,
compare=operator.eq,
get_version=get_version,
openapi_parameter=self.openapi_parameter,
)
with self.assertRaises(RuntimeError) as exc_info:
fence.check(FakeRequest.fake(), "a")
self.assertIs(exc_info.exception, error)
def test_check_returns_true_for_valid_token(self):
def get_token(_request):
return "a"
def get_version(_instance):
return "a"
fence = Fence(
get_token=get_token,
compare=operator.eq,
get_version=get_version,
openapi_parameter=self.openapi_parameter,
)
self.assertIs(fence.check(FakeRequest.fake(), "a"), True)
def test_check_returns_false_for_invalid_token(self):
def get_token(_request):
return "a"
def get_version(_instance):
return "b"
fence = Fence(
get_token=get_token,
compare=operator.eq,
get_version=get_version,
openapi_parameter=self.openapi_parameter,
)
self.assertIs(fence.check(FakeRequest.fake(), "a"), False)
def test_check_returns_true_for_missing_version(self):
def get_token(_request):
return "a"
def get_version(_instance):
return None
fence = Fence(
get_token=get_token,
compare=operator.eq,
get_version=get_version,
openapi_parameter=self.openapi_parameter,
)
self.assertIs(fence.check(FakeRequest.fake(), "a"), True)
|
class TestFence(TestCase):
def test_check_propagates_error_from_get_token(self):
pass
def get_token(_request):
pass
def get_version(_instance):
pass
def test_check_propagates_error_from_get_version(self):
pass
def get_token(_request):
pass
def get_version(_instance):
pass
def test_check_returns_true_for_valid_token(self):
pass
def get_token(_request):
pass
def get_version(_instance):
pass
def test_check_returns_false_for_invalid_token(self):
pass
def get_token(_request):
pass
def get_version(_instance):
pass
def test_check_returns_true_for_missing_version(self):
pass
def get_token(_request):
pass
def get_version(_instance):
pass
| 16 | 0 | 7 | 1 | 6 | 0 | 1 | 0 | 1 | 3 | 2 | 0 | 5 | 0 | 5 | 77 | 96 | 24 | 72 | 26 | 56 | 0 | 43 | 24 | 27 | 1 | 2 | 1 | 15 |
1,187 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestAsSet
|
class TestAsSet(TestCase):
def test_returns_single_item_set(self):
def fn(x: int) -> int:
return x
result = as_set(fn)(1)
self.assertIsInstance(result, frozenset)
assert result is not None
self.assertSetEqual(result, {1})
def test_passes_through_none(self):
def fn(_: int) -> None:
return None
self.assertIsNone(as_set(fn)(1))
|
class TestAsSet(TestCase):
def test_returns_single_item_set(self):
pass
def fn(x: int) -> int:
pass
def test_passes_through_none(self):
pass
def fn(x: int) -> int:
pass
| 5 | 0 | 4 | 1 | 4 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 74 | 15 | 3 | 12 | 6 | 7 | 0 | 12 | 6 | 7 | 1 | 2 | 0 | 4 |
1,188 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_fenced_api.py
|
tests.drf.test_fenced_api.TestAllowIfMatch
|
class TestAllowIfMatch(APITestCase):
url = partial(reverse, "if-match-detail")
def test_returns_bad_request_for_missing_header(self):
item = Parent.objects.create()
response = self.client.put(self.url(args=(item.pk,)), data={"name": "Great!"})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["detail"], "Header missing in request: If-Match")
def test_returns_bad_request_for_invalid_header(self):
item = Parent.objects.create()
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_MATCH="",
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data["detail"], "Malformed header in request: If-Match"
)
def test_returns_precondition_failed_for_mismatching_token_set(self):
item = Parent.objects.create()
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_MATCH='"abc123", "abc321", "abc123"',
)
self.assertEqual(response.status_code, status.HTTP_412_PRECONDITION_FAILED)
self.assertEqual(
response.data["detail"],
"The resource does not fulfill the given preconditions",
)
def test_returns_precondition_failed_for_mismatching_single_token(self):
item = Parent.objects.create()
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_MATCH='"abc123"',
)
self.assertEqual(response.status_code, status.HTTP_412_PRECONDITION_FAILED)
self.assertEqual(
response.data["detail"],
"The resource does not fulfill the given preconditions",
)
def test_allows_request_for_single_valid_token(self):
item = Parent.objects.create()
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_MATCH=item.version,
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertDictEqual(response.data, {"name": "Great!"})
def test_allows_request_for_set_with_matching_token(self):
item = Parent.objects.create()
response = self.client.put(
self.url(args=(item.pk,)),
data={"name": "Great!"},
HTTP_IF_MATCH=f'"{item.version}", "abc123"',
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertDictEqual(response.data, {"name": "Great!"})
|
class TestAllowIfMatch(APITestCase):
def test_returns_bad_request_for_missing_header(self):
pass
def test_returns_bad_request_for_invalid_header(self):
pass
def test_returns_precondition_failed_for_mismatching_token_set(self):
pass
def test_returns_precondition_failed_for_mismatching_single_token(self):
pass
def test_allows_request_for_single_valid_token(self):
pass
def test_allows_request_for_set_with_matching_token(self):
pass
| 7 | 0 | 10 | 0 | 10 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 6 | 0 | 6 | 6 | 66 | 6 | 60 | 20 | 53 | 0 | 32 | 20 | 25 | 1 | 1 | 0 | 6 |
1,189 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/test_admin.py
|
tests.drf.test_admin.TestAPI
|
class TestAPI(TestCase):
user: ClassVar[User]
@classmethod
def setUpTestData(cls):
super().setUpTestData()
call_command("syncpermissions")
cls.user = User.objects.create_user(
username="user", password="test", is_staff=True
)
def assertAuthorized(self):
url = reverse("admin:index")
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def assertNotAuthorized(self):
url = reverse("admin:index")
response = self.client.get(url)
self.assertEqual(response.status_code, 302) # Redirect to login
def test_unautorized_schema(self):
url = reverse("bananas:v1.0:schema", kwargs={"format": ".json"})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
data = response.json()
self.assertIn("/bananas/login/", data["paths"])
action = data["paths"]["/bananas/login/"]["post"]
self.assertEqual(action["operationId"], "bananas.login:create")
self.assertEqual(action["summary"], "Log in")
self.assertNotIn("navigation", action["tags"])
def test_autorized_schema(self):
self.client.force_login(self.user)
url = reverse("bananas:v1.0:schema", kwargs={"format": ".json"})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.check_valid_schema(response.json())
def check_valid_schema(self, data):
self.assertNotIn("/bananas/login/", data["paths"])
self.assertIn("/bananas/logout/", data["paths"])
action = data["paths"]["/bananas/logout/"]["post"]
self.assertEqual(action["operationId"], "bananas.logout:create")
self.assertEqual(action["summary"], "Log out")
self.assertNotIn("navigation", action["tags"])
action = data["paths"]["/tests/ham/"]["get"]
self.assertIn("crud", action["tags"])
self.assertNotIn("navigation", action["tags"])
action = data["paths"]["/bananas/me/"]["get"]
self.assertNotIn("navigation", action["tags"])
action = data["paths"]["/tests/foo/"]["get"]
self.assertNotIn("crud", action["tags"])
self.assertIn("navigation", action["tags"])
bar_endpoint = data["paths"]["/tests/foo/bar/"]
self.assertEqual(bar_endpoint["get"]["operationId"], "tests.foo:bar")
self.assertNotIn("navigation", bar_endpoint["get"]["tags"])
baz_endpoint = data["paths"]["/tests/foo/baz/"]
self.assertEqual(baz_endpoint["get"]["operationId"], "tests.foo:baz.read")
self.assertEqual(baz_endpoint["post"]["operationId"], "tests.foo:baz.create")
self.assertIn("navigation", baz_endpoint["get"]["tags"])
def test_login(self):
user = self.user
url = reverse("bananas:v1.0:bananas.login-list")
# Fail
response = self.client.post(
url, data={"username": user.username, "password": "fail"}
)
self.assertEqual(response.status_code, 400)
# Success
response = self.client.post(
url, data={"username": user.username, "password": "test"}
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["username"], user.username)
self.assertAuthorized()
def test_logout(self):
self.client.force_login(self.user)
url = reverse("bananas:v1.0:bananas.logout-list")
response = self.client.post(url)
self.assertEqual(response.status_code, 204)
self.assertNotAuthorized()
def test_me(self):
user = self.user
self.client.force_login(user)
perm = Permission.objects.all().first()
assert perm is not None
group = Group.objects.create(name="spam")
user.user_permissions.add(perm)
user.groups.add(group)
url = reverse("bananas:v1.0:bananas.me-list")
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
data = response.json()
self.assertEqual(data["username"], user.username)
self.assertIn("spam", data["groups"])
self.assertGreater(len(data["permissions"]), 0)
def test_change_password(self):
user = self.user
self.client.force_login(user)
url = reverse("bananas:v1.0:bananas.change_password-list")
response = self.client.post(
url,
data={
"old_password": "foo",
"new_password1": "foo",
"new_password2": "foo",
},
)
self.assertEqual(response.status_code, 400)
response = self.client.post(
url,
data={
"old_password": "test",
"new_password1": "foo",
"new_password2": "bar",
},
)
self.assertEqual(response.status_code, 400)
response = self.client.post(
url,
data={
"old_password": "test",
"new_password1": "foobar123",
"new_password2": "foobar123",
},
)
self.assertEqual(response.status_code, 204)
self.client.logout()
self.client.login(username=user.username, password="test")
self.assertNotAuthorized()
self.client.login(username=user.username, password="foobar123")
self.assertAuthorized()
def test_tags_decorated_action(self):
self.client.force_login(self.user)
url = reverse("bananas:v1.0:tests.foo-bar")
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
data = response.json()
self.assertEqual(data["bar"], True)
|
class TestAPI(TestCase):
@classmethod
def setUpTestData(cls):
pass
def assertAuthorized(self):
pass
def assertNotAuthorized(self):
pass
def test_unautorized_schema(self):
pass
def test_autorized_schema(self):
pass
def check_valid_schema(self, data):
pass
def test_login(self):
pass
def test_logout(self):
pass
def test_me(self):
pass
def test_change_password(self):
pass
def test_tags_decorated_action(self):
pass
| 13 | 0 | 13 | 2 | 12 | 0 | 1 | 0.02 | 1 | 1 | 0 | 0 | 10 | 0 | 11 | 11 | 162 | 28 | 132 | 43 | 119 | 3 | 104 | 42 | 92 | 1 | 1 | 0 | 11 |
1,190 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/separate_api.py
|
tests.drf.separate_api.SomeThingAPI
|
class SomeThingAPI(ViewSet):
def list(self, request: Request) -> Response: # type: ignore[empty-body]
pass
|
class SomeThingAPI(ViewSet):
def list(self, request: Request) -> Response:
pass
| 2 | 0 | 2 | 0 | 2 | 1 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 3 | 0 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
1,191 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/drf/request.py
|
tests.drf.request.FakeRequest
|
class FakeRequest:
def __init__(self, headers: Optional[Mapping[str, str]] = None) -> None:
self.headers = headers or {}
@classmethod
def fake(cls, *args: Any, **kwargs: Any) -> Request:
return cast(Request, cls(*args, **kwargs))
|
class FakeRequest:
def __init__(self, headers: Optional[Mapping[str, str]] = None) -> None:
pass
@classmethod
def fake(cls, *args: Any, **kwargs: Any) -> Request:
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | 1 | 1 | 2 | 2 | 7 | 1 | 6 | 5 | 2 | 0 | 5 | 4 | 2 | 1 | 0 | 0 | 2 |
1,192 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/models.py
|
tests.models.Parent
|
class Parent(TimeStampedModel, BananasModel):
name = models.CharField(max_length=255)
objects = ParentManager()
@property
def attribute_error(self) -> NoReturn:
raise AttributeError()
@property
def version(self) -> str:
return str(self.pk) + ":" + str(self.date_modified)
|
class Parent(TimeStampedModel, BananasModel):
@property
def attribute_error(self) -> NoReturn:
pass
@property
def version(self) -> str:
pass
| 5 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 2 | 2 | 0 | 0 | 2 | 0 | 2 | 3 | 11 | 2 | 9 | 7 | 4 | 0 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
1,193 |
5monkeys/django-bananas
|
5monkeys_django-bananas/tests/test_models.py
|
tests.test_models.SettingsTest
|
class SettingsTest(TestCase):
def test_module(self):
environ.pop("DJANGO_ADMINS", None)
environ.update(
{
"DJANGO_DEBUG": "true",
"DJANGO_INTERNAL_IPS": "127.0.0.1, 10.0.0.1",
"DJANGO_FILE_UPLOAD_DIRECTORY_PERMISSIONS": "0o644",
"DJANGO_SECRET_KEY": "123",
}
)
from . import settings_example as settings
self.assertEqual(global_settings.DEBUG, False)
self.assertEqual(settings.DEBUG, True)
self.assertListEqual(settings.INTERNAL_IPS, ["127.0.0.1", "10.0.0.1"]) # type: ignore[attr-defined]
self.assertIsNone(global_settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS)
self.assertEqual(settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS, 420) # type: ignore[attr-defined]
def test_get_settings(self):
environ["DJANGO_ADMINS"] = "foobar"
self.assertRaises(ValueError, environment.get_settings)
del environ["DJANGO_ADMINS"]
def test_unsupported_settings_type(self):
environ["DJANGO_DATABASES"] = "foobar"
self.assertRaises(NotImplementedError, environment.get_settings)
del environ["DJANGO_DATABASES"]
|
class SettingsTest(TestCase):
def test_module(self):
pass
def test_get_settings(self):
pass
def test_unsupported_settings_type(self):
pass
| 4 | 0 | 9 | 1 | 8 | 1 | 1 | 0.08 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 3 | 29 | 4 | 25 | 5 | 20 | 2 | 18 | 5 | 13 | 1 | 1 | 0 | 3 |
1,194 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/url.py
|
bananas.url.Alias
|
class Alias:
"""
An alias object used to resolve aliases for engine names.
"""
def __init__(self, target: str) -> None:
self.target = target
def __repr__(self) -> str:
return f'<Alias to "{self.target}">'
|
class Alias:
'''
An alias object used to resolve aliases for engine names.
'''
def __init__(self, target: str) -> None:
pass
def __repr__(self) -> str:
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.6 | 0 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 10 | 2 | 5 | 4 | 2 | 3 | 5 | 4 | 2 | 1 | 0 | 0 | 2 |
1,195 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/drf/fencing.py
|
bananas.drf.fencing.FenceAwareSwaggerAutoSchema
|
class FenceAwareSwaggerAutoSchema(BananasSwaggerSchema):
update_methods = ("PUT", "PATCH")
def add_manual_parameters(
self, parameters: List[openapi.Parameter]
) -> List[openapi.Parameter]:
parameters = super().add_manual_parameters(parameters)
if (
isinstance(self.view, FencedUpdateModelMixin)
and self.method in self.update_methods
):
return [*parameters, self.view.fence.openapi_parameter]
return parameters
|
class FenceAwareSwaggerAutoSchema(BananasSwaggerSchema):
def add_manual_parameters(
self, parameters: List[openapi.Parameter]
) -> List[openapi.Parameter]:
pass
| 2 | 0 | 10 | 0 | 10 | 0 | 2 | 0 | 1 | 2 | 1 | 0 | 1 | 1 | 1 | 6 | 13 | 1 | 12 | 6 | 8 | 0 | 7 | 3 | 5 | 2 | 2 | 1 | 2 |
1,196 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.LogoutAPI
|
class LogoutAPI(BananasAPI, viewsets.ViewSet):
name = _("Log out") # type: ignore[assignment]
basename = "logout"
class Admin:
verbose_name_plural = None
@schema(responses={204: ""})
def create(self, request: Request) -> Response:
"""
Log out django staff user
"""
auth_logout(request)
return Response(status=status.HTTP_204_NO_CONTENT)
|
class LogoutAPI(BananasAPI, viewsets.ViewSet):
class Admin:
@schema(responses={204: ""})
def create(self, request: Request) -> Response:
'''
Log out django staff user
'''
pass
| 4 | 1 | 6 | 0 | 3 | 3 | 1 | 0.44 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 14 | 2 | 9 | 7 | 5 | 4 | 8 | 6 | 5 | 1 | 1 | 0 | 1 |
1,197 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.LogoutAPI.Admin
|
class Admin:
verbose_name_plural = None
|
class Admin:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
1,198 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.MeAPI
|
class MeAPI(BananasAdminAPI):
serializer_class = UserSerializer
class Admin:
exclude_tags: ClassVar[List[str]] = ["navigation"]
@schema(responses={200: UserSerializer})
def list(self, request: Request) -> Response:
"""
Retrieve logged in user info
"""
serializer = self.get_serializer(request.user)
return Response(serializer.data, status=status.HTTP_200_OK)
|
class MeAPI(BananasAdminAPI):
class Admin:
@schema(responses={200: UserSerializer})
def list(self, request: Request) -> Response:
'''
Retrieve logged in user info
'''
pass
| 4 | 1 | 6 | 0 | 3 | 3 | 1 | 0.38 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 13 | 2 | 8 | 7 | 4 | 3 | 7 | 6 | 4 | 1 | 2 | 0 | 1 |
1,199 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.TranslationAPI
|
class TranslationAPI(BananasAdminAPI):
name = _("Translation catalog") # type: ignore[assignment]
basename = "i18n"
permission_classes = (AllowAny,)
class Admin:
exclude_tags: ClassVar[List[str]] = ["navigation"]
@schema(responses={200: ""})
def list(self, request: Request) -> Response:
"""
Retrieve the translation catalog.
"""
return Response(RawTranslationCatalog().get(request))
|
class TranslationAPI(BananasAdminAPI):
class Admin:
@schema(responses={200: ""})
def list(self, request: Request) -> Response:
'''
Retrieve the translation catalog.
'''
pass
| 4 | 1 | 5 | 0 | 2 | 3 | 1 | 0.44 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 5 | 14 | 2 | 9 | 8 | 5 | 4 | 8 | 7 | 5 | 1 | 2 | 0 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.