Skip to content

Commit

Permalink
Test (and fix!) sort
Browse files Browse the repository at this point in the history
  • Loading branch information
Arthur Axel 'fREW' Schmidt committed Feb 28, 2016
1 parent 478fe01 commit a2239e4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 19 deletions.
32 changes: 13 additions & 19 deletions feedpipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,32 +175,26 @@ def reverse(self):

return self

def _default_sorter(a, b):
if 'updated' in a:
left = a.updated
elif 'published' in a:
left = a.published
def _default_key(e):
if e.updated:
return e.updated.text
elif e.published:
return e.published.text

if 'updated' in b:
right = b.updated
elif 'published' in b:
right = b.published

return left < right

def sort(self, sorter=_default_sorter):
def sort(self, cmp=None, key=_default_key, reverse=True):
"""
Sorts the entries in the FeedPipe. Returns self for chaining.
fp.sort(lambda a, b: a.title < b.title)
fp.sort(key='title')
Arguments:
sorter -- callback taking two parameters; conforms to the interface
defined by
[list.sort](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists)'s
cmp. Default is to sort by updated/published.
cmp, key, and reverse; matches the interface of [the sorter
builtin](https://docs.python.org/2/library/functions.html#sorted).
key defaults to updated/published and reverse defaults to True, so
that the default sort is newest at the beginning.
"""
self.entries.sort(cmp=sorter)

self.entries.sort(cmp=cmp, key=key, reverse=reverse)

return self

Expand Down
18 changes: 18 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,5 +106,23 @@ def test_head(self):
self.assertEqual(a.entries[1].title.text, 'UCSPI')
self.assertEqual(fp.count(), 2)

def test_sort(self):
feed = open('tests/eg.xml').read()

fp = FeedPipe().cat([feed]).sort(key=lambda e: e.title.text,
reverse=False)
a = fp.as_atom_obj()
self.assertEqual(a.entries[0].title.text,
'Announcing cgid')
self.assertEqual(a.entries[1].title.text,
'Checking sudoers with visudo in SaltStack')

fp.sort()
a = fp.as_atom_obj()
self.assertEqual(a.entries[0].title.text,
'Migrating My Blog from Linode to CloudFront')
self.assertEqual(a.entries[1].title.text,
'UCSPI')

if __name__ == '__main__':
unittest.main()

0 comments on commit a2239e4

Please sign in to comment.