Skip to content

Commit

Permalink
Add slice support to sequence types.
Browse files Browse the repository at this point in the history
Fix #4.
  • Loading branch information
uranusjr committed Aug 26, 2018
1 parent b6bf052 commit 588a375
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 1 deletion.
3 changes: 3 additions & 0 deletions news/4.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Add slicing support to `DataViewSequence`. It is not possible to get, set, or
delete a slice from it. For `__getitem__`, the return value’s type would match
the sliced `DataViewSequence`.
7 changes: 6 additions & 1 deletion src/plette/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def __getitem__(self, key):
return self.item_class(self._data[key])

def __setitem__(self, key, value):
if isinstance(value, self.item_class):
if isinstance(value, DataView):
value = value._data
self._data[key] = value

Expand Down Expand Up @@ -133,3 +133,8 @@ def validate(cls, data):

def __iter__(self):
return (self.item_class(d) for d in self._data)

def __getitem__(self, key):
if isinstance(key, slice):
return type(self)(self._data[key])
return super(DataViewSequence, self).__getitem__(key)
70 changes: 70 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,73 @@ def test_meta():
],
})
assert m.hash.name == "sha256"


@pytest.fixture()
def sources():
return models.SourceCollection([
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": True,
},
{
"name": "devpi",
"url": "http://127.0.0.1:$DEVPI_PORT/simple",
"verify_ssl": True,
},
])


def test_get_slice(sources):
sliced = sources[:1]
assert isinstance(sliced, models.SourceCollection)
assert len(sliced) == 1
assert sliced[0] == models.Source({
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": True,
})


def test_set_slice(sources):
sources[1:] = [
{
"name": "localpi-4433",
"url": "https://127.0.0.1:4433/simple",
"verify_ssl": False,
},
{
"name": "localpi-8000",
"url": "http://127.0.0.1:8000/simple",
"verify_ssl": True,
},
]
assert sources._data == [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": True,
},
{
"name": "localpi-4433",
"url": "https://127.0.0.1:4433/simple",
"verify_ssl": False,
},
{
"name": "localpi-8000",
"url": "http://127.0.0.1:8000/simple",
"verify_ssl": True,
},
]


def test_del_slice(sources):
del sources[:1]
assert sources._data == [
{
"name": "devpi",
"url": "http://127.0.0.1:$DEVPI_PORT/simple",
"verify_ssl": True,
},
]

0 comments on commit 588a375

Please sign in to comment.