1
0
Fork 0
mirror of https://gitlab.com/SIGBUS/nyaa.git synced 2024-06-17 18:43:12 +00:00
nyaa/nyaa/utils.py
Kfir Hadas c466e76471 Fix RFC822 filters + More tests (#257)
* Make rfc822 filters compatible with Windows systems.

.strftime() is relative to the system it's being run on.
UNIX has '%s' for seconds since the EPOCH, Windows doesn't (ValueError).
Solution: use .timestamp() to achieve the same result on both platforms.
This also allows us to drop the float() around it, since it returns a float.

* Start testing filters

* Add placeholders for more tests

* Make 'tests' folder a Python package

Now you can run tests with just `pytest tests`

* Update readme and travis config

* Test timesince()

* Update and organize .gitignore

Deleted: (nothing)
Added: Coverage files, .idea\

* Test filter_truthy, category_name

* Tests for backend.py

* Tests for bencode.py

* Move (empty) test_models.py to tests package

* Tests for utils.py

* Fixes for flattenDict

* Change name to `flatten_dict`
* `newkey` was assigned but never used

* Add a helper class for testing

* Show coverage on Travis

(only Travis for now...)

* Remove IDE

* Use correct assert functions

* Update README.md
2017-07-07 16:14:37 -05:00

62 lines
1.8 KiB
Python

import hashlib
import functools
from collections import OrderedDict
def sha1_hash(input_bytes):
""" Hash given bytes with hashlib.sha1 and return the digest (as bytes) """
return hashlib.sha1(input_bytes).digest()
def sorted_pathdict(input_dict):
""" Sorts a parsed torrent filelist dict by alphabat, directories first """
directories = OrderedDict()
files = OrderedDict()
for key, value in input_dict.items():
if isinstance(value, dict):
directories[key] = sorted_pathdict(value)
else:
files[key] = value
return OrderedDict(sorted(directories.items()) + sorted(files.items()))
def cached_function(f):
sentinel = object()
f._cached_value = sentinel
@functools.wraps(f)
def decorator(*args, **kwargs):
if f._cached_value is sentinel:
print('Evaluating', f, args, kwargs)
f._cached_value = f(*args, **kwargs)
return f._cached_value
return decorator
def flatten_dict(d, result=None):
if result is None:
result = {}
for key in d:
value = d[key]
if isinstance(value, dict):
value1 = {}
for keyIn in value:
value1["/".join([key, keyIn])] = value[keyIn]
flatten_dict(value1, result)
elif isinstance(value, (list, tuple)):
for indexB, element in enumerate(value):
if isinstance(element, dict):
value1 = {}
index = 0
for keyIn in element:
newkey = "/".join([key, keyIn])
value1[newkey] = value[indexB][keyIn]
index += 1
for keyA in value1:
flatten_dict(value1, result)
else:
result[key] = value
return result