From 7f94e49bc0cdde49d7a3d278bd839849be68f1ea Mon Sep 17 00:00:00 2001 From: John-Mark Gurney Date: Wed, 24 Aug 2022 16:02:14 -0700 Subject: [PATCH] move badfiles to class, encoding is ONLY UTF-8 per BEP-3 https://www.bittorrent.org/beps/bep_0003.html --- __init__.py | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/__init__.py b/__init__.py index e646c0d..9fb922e 100644 --- a/__init__.py +++ b/__init__.py @@ -11,12 +11,14 @@ import sys import tempfile import unittest +_encoding = 'utf-8' + class Storage: - def __init__(self, rootpath, files, piecelen, encoding='us-ascii'): + + def __init__(self, rootpath, files, piecelen): self._rootpath = pathlib.Path(rootpath) self._files = files self._piecelen = piecelen - self._encoding = encoding self._buildindex() @@ -31,7 +33,7 @@ class Storage: for curfile in self._files: fname = pathlib.PurePath( - *(x.decode(self._encoding) for x in + *(x.decode(_encoding) for x in curfile['path'])) curfilepath = self._rootpath / fname @@ -90,15 +92,9 @@ def validate(torrent, basedir): basedir = pathlib.Path(basedir) - try: - encoding = torrent['encoding'].decode('us-ascii') - except KeyError: - encoding = 'us-ascii' + torrentdir = basedir / info['name'].decode(_encoding) - torrentdir = basedir / info['name'].decode(encoding) - - stor = Storage(torrentdir, info['files'], info['piece length'], - encoding) + stor = Storage(torrentdir, info['files'], info['piece length']) pieces = info['pieces'] piecescnt = len(pieces) // 20 @@ -124,6 +120,8 @@ def validate(torrent, basedir): class _TestCases(unittest.TestCase): dirname = 'somedir' + + # file contents for somedir.torrent origfiledata = { 'filea.txt': b'foo\n', 'fileb.txt': b'bar\n', @@ -133,6 +131,13 @@ class _TestCases(unittest.TestCase): 'filef/filef.txt': b'\n', } + # some munging to make some files bad + badfiles = { + 'filea.txt': b'', + 'filec.txt': b'\x00\x00\x00\x00a\n', + 'filee.txt': b'no', + } + def setUp(self): d = pathlib.Path(tempfile.mkdtemp()).resolve() @@ -196,13 +201,7 @@ class _TestCases(unittest.TestCase): missingfiles = self.origfiledata.copy() - badfiles = { - 'filea.txt': b'', - 'filec.txt': b'\x00\x00\x00\x00a\n', - 'filee.txt': b'no', - } - - missingfiles.update(badfiles) + missingfiles.update(self.badfiles) sd = self.basetempdir / self.dirname sd.mkdir() @@ -212,6 +211,6 @@ class _TestCases(unittest.TestCase): val, inval = validate(self.torrent, self.basetempdir) self.assertEqual(set(val), { sd / x for x in - missingfiles.keys() if x not in badfiles }) + missingfiles.keys() if x not in self.badfiles }) self.assertEqual(set(inval), { sd / x for x in - badfiles.keys() }) + self.badfiles.keys() })