Skip to content

Commit

Permalink
Merge pull request #287 from Mattwmaster58/numerical
Browse files Browse the repository at this point in the history
fix numeric sorting
  • Loading branch information
vn-ki committed Jul 14, 2018
2 parents 01c7ca7 + ed046d8 commit 8d65ad3
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
16 changes: 15 additions & 1 deletion pytube/query.py
Expand Up @@ -162,9 +162,23 @@ def order_by(self, attribute_name):
:param str attribute_name:
The name of the attribute to sort by.
"""
integer_attr_repr = {}
for stream in self.fmt_streams:
attr = getattr(stream, attribute_name)
if attr is None:
break
num = [char for char in attr if char.isdigit()]
integer_attr_repr[attr] = int(''.join(num)) if num else None

# if every attribute has an integer representation
if integer_attr_repr and all(integer_attr_repr.values()):
def key(s): return integer_attr_repr[getattr(s, attribute_name)]
else:
def key(s): return getattr(s, attribute_name)

fmt_streams = sorted(
self.fmt_streams,
key=lambda s: getattr(s, attribute_name),
key=key
)
return StreamQuery(fmt_streams)

Expand Down
25 changes: 24 additions & 1 deletion tests/test_query.py
Expand Up @@ -80,21 +80,33 @@ def test_order_by_descending(cipher_signature):
"""Ensure :meth:`~pytube.StreamQuery.desc` sorts the list of
:class:`Stream <Stream>` instances in the reverse order.
"""
# numerical values
itags = [
s.itag for s in cipher_signature.streams
.filter(progressive=True)
.order_by('itag')
.desc()
.all()
]

assert itags == ['43', '36', '22', '18', '17']

# non numerical values
mime_types = [
s.mime_type for s in cipher_signature.streams
.filter(progressive=True)
.order_by('mime_type')
.desc()
.all()
]
assert mime_types == ['video/webm', 'video/mp4',
'video/mp4', 'video/3gpp', 'video/3gpp']


def test_order_by_ascending(cipher_signature):
"""Ensure :meth:`~pytube.StreamQuery.desc` sorts the list of
:class:`Stream <Stream>` instances in ascending order.
"""
# numerical values
itags = [
s.itag for s in cipher_signature.streams
.filter(progressive=True)
Expand All @@ -105,6 +117,17 @@ def test_order_by_ascending(cipher_signature):

assert itags == ['17', '18', '22', '36', '43']

# non numerical values
mime_types = [
s.mime_type for s in cipher_signature.streams
.filter(progressive=True)
.order_by('mime_type')
.asc()
.all()
]
assert mime_types == ['video/3gpp', 'video/3gpp',
'video/mp4', 'video/mp4', 'video/webm']


def test_get_by_itag(cipher_signature):
"""Ensure :meth:`~pytube.StreamQuery.get_by_itag` returns the expected
Expand Down

0 comments on commit 8d65ad3

Please sign in to comment.