Skip to content

Commit

Permalink
Merge 32cc831 into 99e40cf
Browse files Browse the repository at this point in the history
  • Loading branch information
Milan Falešník committed Feb 6, 2018
2 parents 99e40cf + 32cc831 commit b572c37
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
34 changes: 30 additions & 4 deletions src/widgetastic/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,15 +547,23 @@ def crop_string_middle(s, length=32, cropper='...'):
return s[:half] + cropper + s[-half - 1:]


class partial_match(object): # noqa
"""Use this to wrap values to be selected using partial matching in various objects.
class FillValueWrapper(object):
"""Base class for fill value wrapping. Subclass to create your own for special treatment.
It proxies all ``get`` operations to the underlying ``item``.
It also proxies ``dir`` so you get the exactly same result of :py:func:`dir` as if you did it
on the wrapped object.
If ``None`` is passed as the item, it is passed through so
:py:meth:`widgetastic.widget.View.fill` can skip the field
"""
def __new__(cls, item):
if item is None:
return None
return super(FillValueWrapper, cls).__new__(cls)

def __init__(self, item):
self.item = item

Expand All @@ -567,12 +575,30 @@ def __getattr__(self, attr):

def __setattr__(self, attr, value):
if attr == 'item':
super(partial_match, self).__setattr__(attr, value)
super(FillValueWrapper, self).__setattr__(attr, value)
else:
setattr(self.item, attr, value)

def __repr__(self):
return 'partial_match({!r})'.format(self.item)
return '{}({!r})'.format(type(self).__name__, self.item)


class PartialMatch(FillValueWrapper):
"""Use this to wrap values to be selected using partial matching in various objects.
Example may be a ``<select>``. This will select the first item in the select containing "bat":
.. code-block:: python
some_view.fill({
'foo': 'bar',
'baz': PartialMatch('bat')
})
"""


# Backwards compatibility
partial_match = PartialMatch


class Ignore(object):
Expand Down
12 changes: 10 additions & 2 deletions testing/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import pytest

from widgetastic.utils import nested_getattr, partial_match
from widgetastic.utils import PartialMatch, nested_getattr, partial_match


def test_nested_getattr_wrong_type():
Expand Down Expand Up @@ -34,10 +34,18 @@ class bar(object): # noqa

def test_partial_match_wrapping():
value = ' foobar '
wrapped = partial_match(value)
wrapped = PartialMatch(value)

assert dir(wrapped) == dir(value)

assert wrapped.item is value

assert wrapped.strip() == value.strip()


def test_partial_match_none():
assert PartialMatch(None) is None


def test_partial_match_is_partialmatch():
assert partial_match is PartialMatch

0 comments on commit b572c37

Please sign in to comment.