From 42d62ac09742f2df528b193c67b475842b94e363 Mon Sep 17 00:00:00 2001 From: John-Mark Gurney Date: Sat, 27 Aug 2022 17:32:24 -0700 Subject: [PATCH] create a more simple validate function, fix test to be more complete --- ui/medashare/btv/__init__.py | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/ui/medashare/btv/__init__.py b/ui/medashare/btv/__init__.py index 02176d6..6c12f32 100644 --- a/ui/medashare/btv/__init__.py +++ b/ui/medashare/btv/__init__.py @@ -13,7 +13,7 @@ import unittest _encoding = 'utf-8' -__all__ = [ 'validate' ] +__all__ = [ 'validate', 'validate_file' ] class Storage: '''A class to help read pieces of a torrent. @@ -117,6 +117,18 @@ class Storage: fp.seek(i['offset']) fun(fp.read(i['size'])) +def validate_file(fname): + fname = pathlib.Path(fname) + + with open(fname, 'rb') as fp: + torrent = bencode.bdecode(fp.read()) + + dirname = list(fname.parent.rglob(torrent['info']['name'].decode(_encoding)))[0] + + tordir = dirname.parent + + return validate(torrent, tordir) + def validate(torrent, basedir): '''Take a decode torrent file, where it was stored in basedir, verify the torrent. Returns a pair of set, the first is all the @@ -175,13 +187,13 @@ class _TestCases(unittest.TestCase): def setUp(self): d = pathlib.Path(tempfile.mkdtemp()).resolve() + self.basetempdir = d + tor = importlib.resources.files(__name__) tor = tor / 'fixtures' / 'somedir.torrent' with tor.open('rb') as fp: self.torrent = bencode.bdecode(fp.read()) - self.basetempdir = d - self.oldcwd = os.getcwd() os.chdir(d) @@ -201,12 +213,19 @@ class _TestCases(unittest.TestCase): fp.write(v) def test_completeverif(self): - sd = self.basetempdir / self.dirname + tf = self.basetempdir / 'a.torrent' + with open(tf, 'wb') as fp: + fp.write(bencode.bencode(self.torrent)) + + sd = self.basetempdir / 'anotherdir' / self.dirname + sd.parent.mkdir() sd.mkdir() self.make_files(sd, self.origfiledata) - validate(self.torrent, self.basetempdir) + good, bad = validate_file(tf) + + self.assertFalse(bad) # that utf-8 encoded names work @@ -221,7 +240,9 @@ class _TestCases(unittest.TestCase): with tor.open('rb') as fp: torrent = bencode.bdecode(fp.read()) - validate(torrent, self.basetempdir) + good, bad = validate(torrent, self.basetempdir) + + self.assertFalse(bad) def test_verification(self): # Testing for "missing" files