desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Init forms for Add and Edit'
| def _init_forms(self):
| super(BaseCRUDView, self)._init_forms()
conv = GeneralModelConverter(self.datamodel)
if (not self.add_form):
self.add_form = conv.create_form(self.label_columns, self.add_columns, self.description_columns, self.validators_columns, self.add_form_extra_fields, self.add_form_query_rel_fields)
if (n... |
'Init Titles if not defined'
| def _init_titles(self):
| super(BaseCRUDView, self)._init_titles()
class_name = self.datamodel.model_name
if (not self.list_title):
self.list_title = ('List ' + self._prettify_name(class_name))
if (not self.add_title):
self.add_title = ('Add ' + self._prettify_name(class_name))
if (not self.edit_title):... |
'Init Properties'
| def _init_properties(self):
| super(BaseCRUDView, self)._init_properties()
self.related_views = (self.related_views or [])
self._related_views = (self._related_views or [])
self.description_columns = (self.description_columns or {})
self.validators_columns = (self.validators_columns or {})
self.formatters_columns = (self.for... |
':return:
Returns a dict with \'related_views\' key with a list of
Model View widgets'
| def _get_related_views_widgets(self, item, orders=None, pages=None, page_sizes=None, widgets=None, **args):
| widgets = (widgets or {})
widgets['related_views'] = []
for view in self._related_views:
if orders.get(view.__class__.__name__):
(order_column, order_direction) = orders.get(view.__class__.__name__)
else:
(order_column, order_direction) = ('', '')
widgets['rel... |
':return:
Returns a Model View widget'
| def _get_view_widget(self, **kwargs):
| return self._get_list_widget(**kwargs).get('list')
|
'get joined base filter and current active filter for query'
| def _get_list_widget(self, filters, actions=None, order_column='', order_direction='', page=None, page_size=None, widgets=None, **args):
| widgets = (widgets or {})
actions = (actions or self.actions)
page_size = (page_size or self.page_size)
if ((not order_column) and self.base_order):
(order_column, order_direction) = self.base_order
joined_filters = filters.get_joined_filters(self._base_filters)
(count, lst) = self.datam... |
'Will return a list with views that need to be initialized.
Normally related_views from ModelView'
| def get_uninit_inner_views(self):
| return self.related_views
|
'Get the list of related ModelViews after they have been initialized'
| def get_init_inner_views(self):
| return self._related_views
|
'list function logic, override to implement different logic
returns list and search widget'
| def _list(self):
| if get_order_args().get(self.__class__.__name__):
(order_column, order_direction) = get_order_args().get(self.__class__.__name__)
else:
(order_column, order_direction) = ('', '')
page = get_page_args().get(self.__class__.__name__)
page_size = get_page_size_args().get(self.__class__.__nam... |
'show function logic, override to implement different logic
returns show and related list widget'
| def _show(self, pk):
| pages = get_page_args()
page_sizes = get_page_size_args()
orders = get_order_args()
item = self.datamodel.get(pk, self._base_filters)
if (not item):
abort(404)
widgets = self._get_show_widget(pk, item)
self.update_redirect()
return self._get_related_views_widgets(item, orders=ord... |
'Add function logic, override to implement different logic
returns add widget or None'
| def _add(self):
| is_valid_form = True
get_filter_args(self._filters)
exclude_cols = self._filters.get_relation_cols()
form = self.add_form.refresh()
if (request.method == 'POST'):
self._fill_form_exclude_cols(exclude_cols, form)
if form.validate():
item = self.datamodel.obj()
... |
'Edit function logic, override to implement different logic
returns Edit widget and related list or None'
| def _edit(self, pk):
| is_valid_form = True
pages = get_page_args()
page_sizes = get_page_size_args()
orders = get_order_args()
get_filter_args(self._filters)
exclude_cols = self._filters.get_relation_cols()
item = self.datamodel.get(pk, self._base_filters)
if (not item):
abort(404)
pk = self.datam... |
'Delete function logic, override to implement different logic
deletes the record with primary_key = pk
:param pk:
record primary key to delete'
| def _delete(self, pk):
| item = self.datamodel.get(pk, self._base_filters)
if (not item):
abort(404)
try:
self.pre_delete(item)
except Exception as e:
flash(str(e), 'danger')
else:
if self.datamodel.delete(item):
self.post_delete(item)
flash(*self.datamodel.message)
... |
'fill the form with the suppressed cols, generated from exclude_cols'
| def _fill_form_exclude_cols(self, exclude_cols, form):
| for filter_key in exclude_cols:
filter_value = self._filters.get_filter_value(filter_key)
rel_obj = self.datamodel.get_related_obj(filter_key, filter_value)
if hasattr(form, filter_key):
field = getattr(form, filter_key)
field.data = rel_obj
|
'Override this, this method is called before the update takes place.
If an exception is raised by this method,
the message is shown to the user and the update operation is
aborted. Because of this behavior, it can be used as a way to
implement more complex logic around updates. For instance
allowing only the original c... | def pre_update(self, item):
| pass
|
'Override this, will be called after update'
| def post_update(self, item):
| pass
|
'Override this, will be called before add.
If an exception is raised by this method,
the message is shown to the user and the add operation is aborted.'
| def pre_add(self, item):
| pass
|
'Override this, will be called after update'
| def post_add(self, item):
| pass
|
'Override this, will be called before delete
If an exception is raised by this method,
the message is shown to the user and the delete operation is
aborted. Because of this behavior, it can be used as a way to
implement more complex logic around deletes. For instance
allowing only the original creator of the object to ... | def pre_delete(self, item):
| pass
|
'Override this, will be called after delete'
| def post_delete(self, item):
| pass
|
':return:
Returns a widget'
| def _get_view_widget(self, **kwargs):
| return self._get_chart_widget(**kwargs).get('chart')
|
'intantiates the processing class (Direct or Grouped) and returns it.'
| def get_group_by_class(self, definition):
| group_by = definition['group']
series = definition['series']
if ('formatter' in definition):
formatter = {group_by: definition['formatter']}
else:
formatter = {}
return self.ProcessClass([group_by], series, formatter)
|
'returns the keys from direct_columns
Used in template, so that user can choose from options'
| def get_group_by_columns(self):
| return list(self.direct_columns.keys())
|
'Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>=\'asc\'|\'desc\''
| @app_template_filter('link_order')
def link_order_filter(self, column, modelview_name):
| new_args = request.view_args.copy()
args = request.args.copy()
if (('_oc_' + modelview_name) in args):
args[('_oc_' + modelview_name)] = column
if (args.get(('_od_' + modelview_name)) == 'asc'):
args[('_od_' + modelview_name)] = 'desc'
else:
args[('_od_' + mod... |
'Arguments are passed like: page_<VIEW_NAME>=<PAGE_NUMBER>'
| @app_template_filter('link_page')
def link_page_filter(self, page, modelview_name):
| new_args = request.view_args.copy()
args = request.args.copy()
args[('page_' + modelview_name)] = page
return url_for(request.endpoint, **dict((list(new_args.items()) + list(args.to_dict().items()))))
|
'Arguments are passed like: psize_<VIEW_NAME>=<PAGE_NUMBER>'
| @app_template_filter('link_page_size')
def link_page_size_filter(self, page_size, modelview_name):
| new_args = request.view_args.copy()
args = request.args.copy()
args[('psize_' + modelview_name)] = page_size
return url_for(request.endpoint, **dict((list(new_args.items()) + list(args.to_dict().items()))))
|
'Creates a WTForm field for many to one related fields,
will use a Select box based on a query. Will only
work with SQLAlchemy interface.'
| def _convert_many_to_one(self, col_name, label, description, lst_validators, filter_rel_fields, form_props):
| query_func = self._get_related_query_func(col_name, filter_rel_fields)
get_pk_func = self._get_related_pk_func(col_name)
extra_classes = None
allow_blank = True
if (not self.datamodel.is_nullable(col_name)):
lst_validators.append(validators.DataRequired())
allow_blank = False
els... |
'Converts a model to a form given
:param label_columns:
A dictionary with the column\'s labels.
:param inc_columns:
A list with the columns to include
:param description_columns:
A dictionary with a description for cols.
:param validators_columns:
A dictionary with WTForms validators ex::
validators={\'personal_email\'... | def create_form(self, label_columns=None, inc_columns=None, description_columns=None, validators_columns=None, extra_fields=None, filter_rel_fields=None):
| label_columns = (label_columns or {})
inc_columns = (inc_columns or [])
description_columns = (description_columns or {})
validators_columns = (validators_columns or {})
extra_fields = (extra_fields or {})
form_props = {}
for col_name in inc_columns:
if (col_name in extra_fields):
... |
'Completes a dict with the CRUD urls of the API.
:param api_urls: A dict with the urls {\'<FUNCTION>\':\'<URL>\',...}
:return: A dict with the CRUD urls of the base API.'
| def _get_api_urls(self, api_urls=None):
| view_name = self.__class__.__name__
api_urls = (api_urls or {})
api_urls['read'] = url_for((view_name + '.api_read'))
api_urls['delete'] = url_for((view_name + '.api_delete'), pk='')
api_urls['create'] = url_for((view_name + '.api_create'))
api_urls['update'] = url_for((view_name + '.api_update'... |
''
| @expose_api(name='read', url='/api/read', methods=['GET'])
@has_access_api
@permission_name('list')
def api_read(self):
| if get_order_args().get(self.__class__.__name__):
(order_column, order_direction) = get_order_args().get(self.__class__.__name__)
else:
(order_column, order_direction) = ('', '')
page = get_page_args().get(self.__class__.__name__)
page_size = get_page_size_args().get(self.__class__.__nam... |
'Returns a json-able dict for show'
| def show_item_dict(self, item):
| d = {}
for col in self.show_columns:
v = getattr(item, col)
if (not isinstance(v, (int, float, string_types))):
v = str(v)
d[col] = v
return d
|
''
| @expose_api(name='get', url='/api/get/<pk>', methods=['GET'])
@has_access_api
@permission_name('show')
def api_get(self, pk):
| item = self.datamodel.get(pk, self._base_filters)
if (not item):
abort(404)
ret_json = jsonify(pk=pk, label_columns=self._label_columns_json(), include_columns=self.show_columns, modelview_name=self.__class__.__name__, result=self.show_item_dict(item))
response = make_response(ret_json, 200)
... |
'Returns list of (pk, object) nice to use on select2.
Use only for related columns.
Always filters with add_form_query_rel_fields, and accepts extra filters
on endpoint arguments.
:param col_name: The related column name
:return: JSON response'
| @expose_api(name='column_add', url='/api/column/add/<col_name>', methods=['GET'])
@has_access_api
@permission_name('add')
def api_column_add(self, col_name):
| filter_rel_fields = None
if self.add_form_query_rel_fields:
filter_rel_fields = self.add_form_query_rel_fields.get(col_name)
ret_json = self._get_related_column_data(col_name, filter_rel_fields)
response = make_response(ret_json, 200)
response.headers['Content-Type'] = 'application/json'
... |
'Returns list of (pk, object) nice to use on select2.
Use only for related columns.
Always filters with edit_form_query_rel_fields, and accepts extra filters
on endpoint arguments.
:param col_name: The related column name
:return: JSON response'
| @expose_api(name='column_edit', url='/api/column/edit/<col_name>', methods=['GET'])
@has_access_api
@permission_name('edit')
def api_column_edit(self, col_name):
| filter_rel_fields = None
if self.edit_form_query_rel_fields:
filter_rel_fields = self.edit_form_query_rel_fields
ret_json = self._get_related_column_data(col_name, filter_rel_fields)
response = make_response(ret_json, 200)
response.headers['Content-Type'] = 'application/json'
return resp... |
''
| @expose_api(name='readvalues', url='/api/readvalues', methods=['GET'])
@has_access_api
@permission_name('list')
def api_readvalues(self):
| if get_order_args().get(self.__class__.__name__):
(order_column, order_direction) = get_order_args().get(self.__class__.__name__)
else:
(order_column, order_direction) = ('', '')
get_filter_args(self._filters)
joined_filters = self._filters.get_joined_filters(self._base_filters)
(cou... |
'Override this function to control the redirect after add endpoint is called.'
| def post_add_redirect(self):
| return redirect(self.get_redirect())
|
'Override this function to control the redirect after edit endpoint is called.'
| def post_edit_redirect(self):
| return redirect(self.get_redirect())
|
'Override this function to control the redirect after edit endpoint is called.'
| def post_delete_redirect(self):
| return redirect(self.get_redirect())
|
'Action method to handle actions from a show view'
| @expose('/action/<string:name>/<pk>', methods=['GET'])
def action(self, name, pk):
| if self.appbuilder.sm.has_access(name, self.__class__.__name__):
action = self.actions.get(name)
return action.func(self.datamodel.get(pk))
else:
flash(as_unicode(FLAMSG_ERR_SEC_ACCESS_DENIED), 'danger')
return redirect('.')
|
'Action method to handle multiple records selected from a list view'
| @expose('/action_post', methods=['POST'])
def action_post(self):
| name = request.form['action']
pks = request.form.getlist('rowid')
if self.appbuilder.sm.has_access(name, self.__class__.__name__):
action = self.actions.get(name)
items = [self.datamodel.get(pk) for pk in pks]
return action.func(items)
else:
flash(as_unicode(FLAMSG_ERR_SE... |
'Allows attaching stateless information to the class using the
flask session dict'
| @classmethod
def set_key(cls, k, v):
| k = ((cls.__name__ + '__') + k)
session[k] = v
|
'Matching get method for ``set_key``'
| @classmethod
def get_key(cls, k, default=None):
| k = ((cls.__name__ + '__') + k)
if (k in session):
return session[k]
else:
return default
|
'Matching get method for ``set_key``'
| @classmethod
def del_key(cls, k):
| k = ((cls.__name__ + '__') + k)
session.pop(k)
|
'get joined base filter and current active filter for query'
| def _get_list_widget(self, **args):
| widgets = super(CompactCRUDMixin, self)._get_list_widget(**args)
session_form_widget = self.get_key('session_form_widget', None)
form_widget = None
if (session_form_widget == 'add'):
form_widget = self._add().get('add')
elif (session_form_widget == 'edit'):
pk = self.get_key('session... |
'Saves an image File
:param data: FileStorage from Flask form upload field
:param filename: Filename with full path'
| def save_file(self, data, filename, size=None, thumbnail_size=None):
| max_size = (size or self.max_size)
thumbnail_size = (thumbnail_size or self.thumbnail_size)
if (data and isinstance(data, FileStorage)):
try:
self.image = Image.open(data)
except Exception as e:
raise ValidationError(('Invalid image: %s' % e))
path = self.ge... |
'Resizes the image
:param image: The image object
:param size: size is PIL tuple (width, heigth, force) ex: (200,100,True)'
| def resize(self, image, size):
| (width, height, force) = size
if ((image.size[0] > width) or (image.size[1] > height)):
if force:
return ImageOps.fit(self.image, (width, height), Image.ANTIALIAS)
else:
thumb = self.image.copy()
thumb.thumbnail((width, height), Image.ANTIALIAS)
re... |
'Finds a menu item by name and returns it.
:param name:
The menu item name.'
| def find(self, name, menu=None):
| menu = (menu or self.menu)
for i in menu:
if (i.name == name):
return i
elif i.childs:
ret_item = self.find(name, menu=i.childs)
if ret_item:
return ret_item
|
'Take the values from allalbums/alltracks (based on the ReleaseID) and
swap it into the album & track tables'
| @cherrypy.expose
def switchAlbum(self, AlbumID, ReleaseID):
| from headphones import albumswitcher
albumswitcher.switch(AlbumID, ReleaseID)
raise cherrypy.HTTPRedirect(('albumPage?AlbumID=%s' % AlbumID))
|
'Logs in user'
| def login(self):
| loginpage = 'http://rutracker.org/forum/login.php'
post_params = {'login_username': headphones.CONFIG.RUTRACKER_USER, 'login_password': headphones.CONFIG.RUTRACKER_PASSWORD, 'login': '\xc2\xf5\xee\xe4'}
logger.info('Attempting to log in to rutracker...')
try:
r = self.session.post... |
'Return the search url'
| def searchurl(self, artist, album, year, format):
| searchterm = ''
if (artist != 'Various Artists'):
searchterm = artist
searchterm = (searchterm + ' ')
searchterm = (searchterm + album)
searchterm = (searchterm + ' ')
searchterm = (searchterm + year)
if (format == 'lossless'):
format = '+lossless'
self.m... |
'Parse the search results and return valid torrent list'
| def search(self, searchurl):
| try:
headers = {'Referer': self.search_referer}
r = self.session.get(url=searchurl, headers=headers, timeout=self.timeout)
soup = BeautifulSoup(r.content, 'html5lib')
if (not self.still_logged_in(soup)):
self.login()
r = self.session.get(url=searchurl, timeout... |
'return the .torrent data'
| def get_torrent_data(self, url):
| torrent_id = dict([part.split('=') for part in urlparse(url)[4].split('&')])['t']
downloadurl = ('http://rutracker.org/forum/dl.php?t=' + torrent_id)
cookie = {'bb_dl': torrent_id}
try:
headers = {'Referer': url}
r = self.session.post(url=downloadurl, cookies=cookie, headers=headers, tim... |
'Returns true if Hidden Track exists.'
| def htoa(self):
| if (int(self.tracks[1]['index'][1][(-5):(-3)]) >= HTOA_LENGTH_TRIGGER):
return True
return False
|
'Returns track break points. Identical as CUETools\' cuebreakpoints, with the exception of my standards for HTOA.'
| def breakpoints(self):
| content = ''
for t in range(len(self.tracks)):
if ((t == 1) and (not self.htoa())):
content += ''
elif (t >= 1):
t_index = self.tracks[t]['index']
content += t_index[1]
if (t < (len(self.tracks) - 1)):
content += '\n'
return con... |
'Check MetaFile for containing all data'
| def complete(self):
| self.__init__(self.path)
for l in self.rawcontent.splitlines():
if re.search('^[0-9A-Za-z]+? DCTB $', l):
return False
return True
|
'Returns tracks count'
| def count_tracks(self):
| return (len(self.content['tracks']) - self.content['tracks'].count(None))
|
'Initialize the config with values from a file'
| def __init__(self, config_file):
| self._config_file = config_file
self._config = ConfigObj(self._config_file, encoding='utf-8')
for key in _CONFIG_DEFINITIONS.keys():
self.check_setting(key)
self.ENCODER_MULTICORE_COUNT = max(0, self.ENCODER_MULTICORE_COUNT)
self._upgrade()
|
'Check if INI section exists, if not create it'
| def check_section(self, section):
| if (section not in self._config):
self._config[section] = {}
return True
else:
return False
|
'Cast any value in the config to the right type or use the default'
| def check_setting(self, key):
| (key, definition_type, section, ini_key, default) = self._define(key)
self.check_section(section)
try:
my_val = definition_type(self._config[section][ini_key])
except Exception:
my_val = definition_type(default)
self._config[section][ini_key] = my_val
return my_val
|
'Make a copy of the stored config and write it to the configured file'
| def write(self):
| new_config = ConfigObj(encoding='UTF-8')
new_config.filename = self._config_file
for (key, subkeys) in self._config.items():
if (key not in new_config):
new_config[key] = {}
for (subkey, value) in subkeys.items():
new_config[key][subkey] = value
for key in _CONFIG... |
'Return the extra newznab tuples'
| def get_extra_newznabs(self):
| extra_newznabs = list(itertools.izip(*[itertools.islice(self.EXTRA_NEWZNABS, i, None, 3) for i in range(3)]))
return extra_newznabs
|
'Forget about the configured extra newznabs'
| def clear_extra_newznabs(self):
| self.EXTRA_NEWZNABS = []
|
'Add a new extra newznab'
| def add_extra_newznab(self, newznab):
| extra_newznabs = self.EXTRA_NEWZNABS
for item in newznab:
extra_newznabs.append(item)
self.EXTRA_NEWZNABS = extra_newznabs
|
'Return the extra torznab tuples'
| def get_extra_torznabs(self):
| extra_torznabs = list(itertools.izip(*[itertools.islice(self.EXTRA_TORZNABS, i, None, 3) for i in range(3)]))
return extra_torznabs
|
'Forget about the configured extra torznabs'
| def clear_extra_torznabs(self):
| self.EXTRA_TORZNABS = []
|
'Add a new extra torznab'
| def add_extra_torznab(self, torznab):
| extra_torznabs = self.EXTRA_TORZNABS
for item in torznab:
extra_torznabs.append(item)
self.EXTRA_TORZNABS = extra_torznabs
|
'Returns something from the ini unless it is a real property
of the configuration object or is not all caps.'
| def __getattr__(self, name):
| if (not re.match('[A-Z_]+$', name)):
return super(Config, self).__getattr__(name)
else:
return self.check_setting(name)
|
'Maps all-caps properties to ini values unless they exist on the
configuration object.'
| def __setattr__(self, name, value):
| if (not re.match('[A-Z_]+$', name)):
super(Config, self).__setattr__(name, value)
return value
else:
(key, definition_type, section, ini_key, default) = self._define(name)
self._config[section][ini_key] = definition_type(value)
return self._config[section][ini_key]
|
'Given a big bunch of key value pairs, apply them to the ini.'
| def process_kwargs(self, kwargs):
| for (name, value) in kwargs.items():
(key, definition_type, section, ini_key, default) = self._define(name)
self._config[section][ini_key] = definition_type(value)
|
'Bring old configs up to date'
| def _upgrade(self):
| if (self.CONFIG_VERSION == '2'):
if self.ENCODERFOLDER:
self.ENCODER_PATH = os.path.join(self.ENCODERFOLDER, self.ENCODER)
self.CONFIG_VERSION = '3'
if (self.CONFIG_VERSION == '3'):
if self.BLACKHOLE:
self.NZB_DOWNLOADER = 2
self.CONFIG_VERSION = '4'
i... |
'pathrender: pattern parsing'
| def test_parsing(self):
| pattern = Pattern(u'{$Disc.}$Track - $Artist - $Title{ [$Year]}')
expected = [_pr._OptionalBlock([_pr._Replacement(u'$Disc'), _pr._LiteralText(u'.')]), _pr._Replacement(u'$Track'), _pr._LiteralText(u' - '), _pr._Replacement(u'$Artist'), _pr._LiteralText(u' - '), _pr._Replacement(u'$Ti... |
'pathrender: pattern parsing with warnings'
| def test_parsing_warnings(self):
| pattern = Pattern(u'{$Disc.}$Track - $Artist - $Title{ [$Year]')
self.assertEqual(set([Warnings.UNCLOSED_OPTIONAL]), pattern.warnings)
pattern = Pattern(u"{$Disc.}$Track - $Artist - $Title{ [$Year]'}")
self.assertEqual(set([Warnings.UNCLOSED_ESCAPE, Warnings.UNCLOSED_OPTION... |
'pathrender: _Replacement variable substitution'
| def test_replacement(self):
| r = _pr._Replacement(u'$Title')
subst = {'$Title': 'foo', '$Track': 'bar'}
res = r.render(subst)
self.assertEqual(res, u'foo', 'check valid replacement')
subst = {}
res = r.render(subst)
self.assertEqual(res, u'$Title', 'check missing replacement')
subst = {'$Title': None}
... |
'pathrender: _Literal text rendering'
| def test_literal(self):
| l = _pr._LiteralText(u'foo')
subst = {'$foo': 'bar'}
res = l.render(subst)
self.assertEqual(res, 'foo')
|
'pathrender: _OptionalBlock element processing'
| def test_optional(self):
| o = _pr._OptionalBlock([_pr._Replacement(u'$Title'), _pr._LiteralText(u'.foobar')])
subst = {'$Title': 'foo', '$Track': 'bar'}
res = o.render(subst)
self.assertEqual(res, u'foo.foobar', 'check non-empty replacement')
subst = {'$Title': ''}
res = o.render(subst)
self.assertEqual(res, ''... |
'MetadataDict: case-insensitive lookup'
| def test_metadata_dict_ci(self):
| expected = u'na\xefve'
key_var = '$TitlE'
m = MetadataDict({key_var.lower(): u'na\xefve'})
self.assertFalse(('$track' in m))
self.assertTrue(('$tITLe' in m), "cross-case lookup with 'in'")
self.assertEqual(m[key_var], expected, 'cross-case lookup success')
self.assertEqual(m[k... |
'MetadataDice: case-preserving lookup'
| def test_metadata_dict_cs(self):
| expected_var = u'Na\xefVe'
key_var = '$TitlE'
m = MetadataDict({key_var.lower(): expected_var.lower(), key_var: expected_var})
self.assertFalse(('$track' in m))
self.assertTrue(('$tITLe' in m), "cross-case lookup with 'in'")
self.assertEqual(m[key_var.lower()], expected_var.lower(), 'ca... |
'metadata: check dictionary intersect function validity'
| def test_dict_intersect(self):
| d1 = {'one': 'one', 'two': 'two', 'three': 'zonk'}
d2 = {'two': 'two', 'three': 'three'}
expected = {'two': 'two'}
self.assertItemsEqual(expected, _md._intersect(d1, d2), 'check dictionary intersection is common part indeed')
del d1['two']
expected = {}
self.assertItemsEqua... |
'AlbumMetadataBuilder: check validity'
| def test_album_metadata_builder(self):
| mb = _md.AlbumMetadataBuilder()
f1 = _MockMediaFile('artist', 'album', 2000, 1, 'track1', 'Ant-Zen')
mb.add_media_file(f1)
f2 = _MockMediaFile('artist', 'album', 2000, 2, 'track2', 'Ant-Zen')
mb.add_media_file(f2)
md = mb.build()
expected = {_md.Vars.ARTIST_LOWER: 'artist', _md.Vars.ALBUM_LO... |
'metadata: check populating metadata from database row'
| def test_populate_from_row(self):
| row = _MockDatabaseRow({'ArtistName': 'artist', 'AlbumTitle': 'album', 'ReleaseDate': datetime.date(2004, 11, 28), 'Variation': 5, 'WrongTyped': complex(1, (-1))})
md = _md.MetadataDict()
_md._row_to_dict(row, md)
expected = {'$ArtistName': 'artist', '$AlbumTitle': 'album', '$ReleaseDate': '2004-11-28',... |
'metadata: check handling of None metadata values'
| def test_album_metadata_with_None(self):
| row = _MockDatabaseRow({'ArtistName': 'artist', 'AlbumTitle': 'Album', 'Type': None, 'ReleaseDate': None})
mb = _md.AlbumMetadataBuilder()
f1 = _MockMediaFile('artist', None, None, None, None, None)
mb.add_media_file(f1)
f2 = _MockMediaFile('artist', None, None, 2, 'track2', None)
mb.add_media_f... |
'Returns a tuple containing (status, quality)'
| @staticmethod
def splitCompositeStatus(status):
| for x in sorted(Quality.qualityStrings.keys(), reverse=True):
if (status > (x * 100)):
return ((status - (x * 100)), x)
return (Quality.NONE, status)
|
'Format this _PatternElement into string using provided substitution dictionary.'
| def render(self, replacement):
| raise NotImplementedError()
|
':type other: _OptionalBlock'
| def __eq__(self, other):
| return (isinstance(other, _OptionalBlock) and (self._scope == other._scope))
|
'Execute path rendering/substitution based on replacement dictionary.'
| def __call__(self, replacement):
| return u''.join((p.render(replacement) for p in self._pattern))
|
'Getter for warnings property.'
| def _get_warnings(self):
| return self._warnings
|
'create headphones.SoftChroot'
| def test_create(self):
| cf = SoftChroot('/tmp/')
self.assertIsInstance(cf, SoftChroot)
self.assertTrue(cf.isEnabled())
self.assertEqual(cf.getRoot(), '/tmp/')
|
'create DISABLED SoftChroot'
| @TestArgs(None, '', ' ')
def test_create_disabled(self, empty_path):
| cf = SoftChroot(empty_path)
self.assertIsInstance(cf, SoftChroot)
self.assertFalse(cf.isEnabled())
self.assertIsNone(cf.getRoot())
|
'create SoftChroot on non existent dir'
| def test_create_on_not_exists_dir(self):
| path = os.path.join('/tmp', 'notexist', 'asdf', '11', '12', 'np', 'itsssss')
cf = None
with self.assertRaises(SoftChrootError) as exc:
cf = SoftChroot(path)
self.assertIsNone(cf)
self.assertRegexpMatches(str(exc.exception), 'No such directory')
self.assertRegexpMatches(str(exc.exce... |
'create SoftChroot on file, not a directory'
| @mock.patch('headphones.softchroot.os', wrap=os, name='OsMock')
def test_create_on_file(self, os_mock):
| path = os.path.join('/tmp', 'notexist', 'asdf', '11', '12', 'np', 'itsssss')
os_mock.path.sep = os.path.sep
os_mock.path.isdir.side_effect = (lambda x: (x != path))
cf = None
with self.assertRaises(SoftChrootError) as exc:
cf = SoftChroot(path)
self.assertIsNone(cf)
self.assertTrue(o... |
'apply SoftChroot'
| @TestArgs((None, None), ('', ''), (' ', ' '), ('/tmp/', '/'), ('/tmp/asdf', '/asdf'))
def test_apply(self, p, e):
| sc = SoftChroot('/tmp/')
a = sc.apply(p)
self.assertEqual(a, e)
|
'apply SoftChroot to paths outside of the chroot'
| @TestArgs('/', '/nonch/path/asdf', 'tmp/asdf')
def test_apply_out_of_root(self, p):
| sc = SoftChroot('/tmp/')
a = sc.apply(p)
self.assertEqual(a, '/')
|
'revoke SoftChroot'
| @TestArgs((None, None), ('', ''), (' ', ' '), ('/', '/tmp/'), ('/asdf', '/tmp/asdf'), ('/asdf/', '/tmp/asdf/'), ('localdir/adf', '/tmp/localdir/adf'), ('localdir/adf/', '/tmp/localdir/adf/'))
def test_revoke(self, p, e):
| sc = SoftChroot('/tmp/')
a = sc.revoke(p)
self.assertEqual(a, e)
|
'disabled SoftChroot should not change args on apply and revoke'
| @TestArgs(None, '', ' ', '/tmp', '/tmp/', '/tmp/asdf', '/tmp/localdir/adf', 'localdir/adf', 'localdir/adf/')
def test_actions_on_disabled(self, p):
| sc = SoftChroot(None)
a = sc.apply(p)
self.assertEqual(a, p)
r = sc.revoke(p)
self.assertEqual(r, p)
|
'Config : creating'
| def test_constructor(self):
| cf = headphones.config.Config('/tmp/notexist')
self.assertIsInstance(cf, headphones.config.Config)
|
'Config : check_section'
| @TestArgs(('General', False), ('Email', False), ('some_new_section_never_defined', True), ('another_new_section_never_defined', True))
def test_check_section(self, section_name, expected_return):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
res = c.check_section(section_name)
res2 = c.check_section(section_name)
self.assertEqual(res, expected_return)
self.assertFalse(res2)
|
'Config: check_setting , basic cases'
| @TestArgs(('api_enabled', 0, int), ('Api_Key', '', str))
def test_check_setting(self, setting_name, expected_return, expected_instance):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
res = c.check_setting(setting_name)
res2 = c.check_setting(setting_name)
self.assertIsInstance(res, expected_instance)
self.assertEqual(res, expected_return)
self.assertEqual(res, res2)
|
'Config: check_setting should raise on unknown'
| @TestArgs('', 'This_IsNew_Name')
def test_check_setting_raise_on_unknown_settings(self, setting_name):
| path = '/tmp/notexist'
exc_regex = re.compile(setting_name, re.IGNORECASE)
c = headphones.config.Config(path)
with self.assertRaisesRegexp(KeyError, exc_regex):
c.check_setting(setting_name)
pass
|
'Config: check_setting shoud raise on None name'
| @TestArgs(None)
def test_check_setting_raise_on_none(self, setting_name):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
with self.assertRaises(AttributeError):
c.check_setting(setting_name)
pass
|
'Config : write'
| def test_write(self):
| path = '/tmp/notexist'
old_conf_mock = self._setUpConfigMock(MagicMock(), {'a': {}})
option_name_not_from_definitions = 'some_invalid_option_with_super_uniq1_name'
option_name_not_from_definitions_value = 1
old_conf_mock['asdf'] = {option_name_not_from_definitions: option_name_not_from_definitions_v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.