Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve tests, code formatting, tests in pipeline #5

Merged
merged 13 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ on:
branches:
- feature/*
- main
pull_request:
branches:
- main

jobs:
tests:
Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ If you need support for Python 2.x versions then you can get legacy versions [he

## NZBGet Versions

- stable v23 [v2.0](https://github.com/nzbgetcom/Extension-ExtendedUnrar/releases/tag/v2.0)
- legacy v22 [v1.0](https://github.com/nzbgetcom/Extension-ExtendedUnrar/releases/tag/v1.0)

# ExtendedUnrar
Expand Down
107 changes: 65 additions & 42 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Expand All @@ -25,70 +25,93 @@
import subprocess
import time

sys.stdout.reconfigure(encoding="utf-8")

# Exit codes used by NZBGet
POSTPROCESS_SUCCESS=93
POSTPROCESS_ERROR=94
POSTPROCESS_NONE=95
POSTPROCESS_SUCCESS = 93
POSTPROCESS_ERROR = 94
POSTPROCESS_NONE = 95


# Check if the script is called from nzbget 18.0 or later
if not 'NZBOP_EXTENSIONS' in os.environ:
print('[ERROR] This script requires NZBGet v18.0 or later')
if not "NZBOP_EXTENSIONS" in os.environ:
print("[ERROR] This script requires NZBGet v18.0 or later")
sys.exit(POSTPROCESS_ERROR)

print('[INFO] Script successfully started - python ' + str(sys.version_info))
print("[INFO] Script successfully started - python " + str(sys.version_info))
sys.stdout.flush()

# Check nzbget.conf options
required_options = ('NZBOP_UNRARCMD', 'NZBPO_UNRARPATH', 'NZBPO_WAITTIME', 'NZBPO_DELETELEFTOVER')
required_options = (
"NZBOP_UNRARCMD",
"NZBPO_UNRARPATH",
"NZBPO_WAITTIME",
"NZBPO_DELETELEFTOVER",
)
for optname in required_options:
if (not optname in os.environ):
print('[ERROR] Option %s is missing in NZBGet configuration. Please check script settings' % optname[6:])
if not optname in os.environ:
print(
"[ERROR] Option %s is missing in NZBGet configuration. Please check script settings"
% optname[6:]
)
sys.exit(POSTPROCESS_ERROR)

# If NZBGet Unpack setting isn't enabled, this script cannot work properly
if os.environ['NZBOP_UNPACK'] != 'yes':
if os.environ["NZBOP_UNPACK"] != "yes":
print('[ERROR] You must enable option "Unpack" in NZBGet configuration, exiting')
sys.exit(POSTPROCESS_ERROR)

unrarpath=os.environ['NZBPO_UNRARPATH']
waittime=os.environ['NZBPO_WAITTIME']
deleteleftover=os.environ['NZBPO_DELETELEFTOVER']
unrarpath = os.environ["NZBPO_UNRARPATH"]
waittime = os.environ["NZBPO_WAITTIME"]
deleteleftover = os.environ["NZBPO_DELETELEFTOVER"]

if unrarpath == '':
print('[DETAIL] UnrarPath setting is blank. Using default NZBGet UnrarCmd setting')
unrarpath=os.environ['NZBOP_UNRARCMD']
if unrarpath == "":
print("[DETAIL] UnrarPath setting is blank. Using default NZBGet UnrarCmd setting")
unrarpath = os.environ["NZBOP_UNRARCMD"]

# Check TOTALSTATUS
if os.environ['NZBPP_TOTALSTATUS'] != 'SUCCESS':
print('[WARNING] NZBGet download TOTALSTATUS is not SUCCESS, exiting')
if os.environ["NZBPP_TOTALSTATUS"] != "SUCCESS":
print("[WARNING] NZBGet download TOTALSTATUS is not SUCCESS, exiting")
sys.exit(POSTPROCESS_NONE)

# Check if destination directory exists (important for reprocessing of history items)
if not os.path.isdir(os.environ['NZBPP_DIRECTORY']):
print('[WARNING] Destination directory ' + os.environ['NZBPP_DIRECTORY'] + ' does not exist, exiting')
if not os.path.isdir(os.environ["NZBPP_DIRECTORY"]):
print(
"[WARNING] Destination directory "
+ os.environ["NZBPP_DIRECTORY"]
+ " does not exist, exiting"
)
sys.exit(POSTPROCESS_NONE)

# Sleep (maybe)
if os.environ['NZBOP_UNPACKCLEANUPDISK'] == 'yes':
print('[DETAIL] Sleeping ' + waittime + ' seconds to give NZBGet time to finish UnpackCleanupDisk action')
if os.environ["NZBOP_UNPACKCLEANUPDISK"] == "yes":
print(
"[DETAIL] Sleeping "
+ waittime
+ " seconds to give NZBGet time to finish UnpackCleanupDisk action"
)
time.sleep(int(float(waittime)))

# Traverse download files to check for un-extracted rar files
print('[DETAIL] Searching for rar/RAR files')
print("[DETAIL] Searching for rar/RAR files")

sys.stdout.flush()


def get_full_path(dir, filename):
return os.path.join(dir, filename)


def if_rar(filePath):
_, fileExtension = os.path.splitext(filePath)
return fileExtension in ['.rar', '.RAR']
return fileExtension in [".rar", ".RAR"]


status = 0
extract = 0
extracted = []
working_dir = os.environ['NZBPP_DIRECTORY']
working_dir = os.environ["NZBPP_DIRECTORY"]


def unrar_recursively():
global extract
Expand All @@ -101,44 +124,44 @@ def unrar_recursively():
if len(rars) == 0:
extract = 1
return

for file in rars:
print('[INFO] Extracting %s' % file)
print("[INFO] Extracting %s" % file)
sys.stdout.flush()
# You can adjust the unrar options here if you need. The defaults are:
# e (extract without paths), -idp (no extract progress), -ai (ignore attributes), -o- (don't overwrite)
# e (extract without paths), -idp (no extract progress), -ai (ignore attributes), -o- (don't overwrite)
unrar = unrarpath + ' e -idp -ai -o- "' + file + '" "' + working_dir + '"'
try:
retcode = subprocess.call(unrar, shell=True)
retcode = subprocess.call(unrar)
if retcode == 0 or retcode == 10:
print('[INFO] Extract Successful')
print("[INFO] Extract Successful")
extracted.append(file)
extract = 1
else:
print('[ERROR] Extract failed, Returncode %d' % retcode)
print("[ERROR] Extract failed, Returncode %d" % retcode)
status = 1
return
except OSError as e:
print('[ERROR] Execution of unrar command failed: %s' % e)
print('[ERROR] Unable to extract %s' % file)
print("[ERROR] Execution of unrar command failed: %s" % e)
print("[ERROR] Unable to extract %s" % file)
status = 1
return
unrar_recursively()


unrar_recursively()

sys.stdout.flush()

if extract == 1 and deleteleftover == 'yes':
print('[INFO] Deleting leftover rar files')
if extract == 1 and deleteleftover == "yes":
print("[INFO] Deleting leftover rar files")
for file in extracted:
print('[INFO] Deleting %s' % file)
print("[INFO] Deleting %s" % file)
try:
os.remove(file)
except OSError as e:
print('[ERROR] Delete failed: %s' % e)
print('[ERROR] Unable to delete %s' % file)
print("[ERROR] Delete failed: %s" % e)
print("[ERROR] Unable to delete %s" % file)
status = 1

if status == 0:
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"homepage": "https://github.com/nzbgetcom/Extension-ExtendedUnrar",
"kind": "POST-PROCESSING",
"displayName": "Extended Unrar",
"version": "2.0.0",
"version": "2.1",
"author": "thorli",
"license": "GNU",
"about": "Unrars nested rar files.",
Expand Down
Binary file added test_data/test1.rar
Binary file not shown.
Binary file modified test_data/test2.rar
Binary file not shown.
Binary file added test_data/test3.rar
Binary file not shown.
150 changes: 83 additions & 67 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with the program. If not, see <http://www.gnu.org/licenses/>.
# along with the program. If not, see <https://www.gnu.org/licenses/>.
#

import sys
Expand All @@ -24,81 +24,97 @@
import shutil
import json

SUCCESS=93
NONE=95
ERROR=94
sys.stdout.reconfigure(encoding="utf-8")

unrar = os.environ.get('unrar', 'unrar')
SUCCESS = 93
NONE = 95
ERROR = 94

unrar = "../UnRAR.exe"

root = dirname(__file__)
test_data_dir = root + '/test_data/'
tmp_dir = root + '/tmp/'
test_rar = 'test2.rar'
result_file = tmp_dir + 'test.txt'
test_data_dir = root + "/test_data/"
tmp_dir = root + "/tmp/"
test_rars = ["test1.rar", "test2.rar", "test3.rar"]
result_files = [tmp_dir + "test1.txt", tmp_dir + "test2.txt", tmp_dir + "test3.txt"]


host = "127.0.0.1"
username = "TestUser"
password = "TestPassword"
port = "6789"

host = '127.0.0.1'
username = 'TestUser'
password = 'TestPassword'
port = '6789'

def get_python():
if os.name == 'nt':
return 'python'
return 'python3'
def get_python():
if os.name == "nt":
return "python"
return "python3"


def run_script():
sys.stdout.flush()
proc = subprocess.Popen([get_python(), root + '/main.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ.copy())
out, err = proc.communicate()
proc.pid
ret_code = proc.returncode
return (out.decode(), int(ret_code), err.decode())
sys.stdout.flush()
proc = subprocess.Popen(
[get_python(), root + "/main.py"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=os.environ.copy(),
)
out, err = proc.communicate()
proc.pid
ret_code = proc.returncode
return (out.decode(), int(ret_code), err.decode())


def set_defaults_env():
# NZBGet global options
os.environ['NZBNA_EVENT'] = 'FILE_DOWNLOADED'
os.environ['NZBPP_DIRECTORY'] = tmp_dir
os.environ['NZBOP_ARTICLECACHE'] = '8'
os.environ['NZBPO_PASSACTION'] = 'PASSACTION'
os.environ['NZBOP_CONTROLPORT'] = port
os.environ['NZBOP_CONTROLIP'] = host
os.environ['NZBOP_CONTROLUSERNAME'] = username
os.environ['NZBOP_CONTROLPASSWORD'] = password
os.environ['NZBPR_PASSWORDDETECTOR_HASPASSWORD'] = 'no'
os.environ['NZBOP_EXTENSIONS'] = ''
os.environ['NZBOP_UNPACK'] = 'yes'
os.environ['NZBPP_TOTALSTATUS'] = 'SUCCESS'

# script options
os.environ['NZBNA_CATEGORY'] = 'Movies'
os.environ['NZBNA_DIRECTORY'] = tmp_dir
os.environ['NZBNA_NZBNAME'] = 'TestNZB'
os.environ['NZBPR_FAKEDETECTOR_SORTED'] = 'yes'
os.environ['NZBOP_TEMPDIR'] = tmp_dir
os.environ['NZBOP_UNRARCMD'] = unrar
os.environ['NZBPO_UNRARPATH'] = ''
os.environ['NZBPO_WAITTIME'] = '0'
os.environ['NZBPO_DELETELEFTOVER'] = 'no'
os.environ['NZBOP_UNPACKCLEANUPDISK'] = 'no'
# NZBGet global options
os.environ["NZBNA_EVENT"] = "FILE_DOWNLOADED"
os.environ["NZBPP_DIRECTORY"] = tmp_dir
os.environ["NZBOP_ARTICLECACHE"] = "8"
os.environ["NZBPO_PASSACTION"] = "PASSACTION"
os.environ["NZBOP_CONTROLPORT"] = port
os.environ["NZBOP_CONTROLIP"] = host
os.environ["NZBOP_CONTROLUSERNAME"] = username
os.environ["NZBOP_CONTROLPASSWORD"] = password
os.environ["NZBPR_PASSWORDDETECTOR_HASPASSWORD"] = "no"
os.environ["NZBOP_EXTENSIONS"] = ""
os.environ["NZBOP_UNPACK"] = "yes"
os.environ["NZBPP_TOTALSTATUS"] = "SUCCESS"

# script options
os.environ["NZBNA_CATEGORY"] = "Movies"
os.environ["NZBNA_DIRECTORY"] = tmp_dir
os.environ["NZBNA_NZBNAME"] = "TestNZB"
os.environ["NZBPR_FAKEDETECTOR_SORTED"] = "yes"
os.environ["NZBOP_TEMPDIR"] = tmp_dir
os.environ["NZBOP_UNRARCMD"] = unrar
os.environ["NZBPO_UNRARPATH"] = ""
os.environ["NZBPO_WAITTIME"] = "0"
os.environ["NZBPO_DELETELEFTOVER"] = "no"
os.environ["NZBOP_UNPACKCLEANUPDISK"] = "no"


class Tests(unittest.TestCase):

def test_unrar(self):
os.mkdir(tmp_dir)
set_defaults_env()
shutil.copyfile(test_data_dir + test_rar, tmp_dir + test_rar)
[_, code, _] = run_script()
self.assertEqual(code, SUCCESS)
self.assertTrue(os.path.exists(result_file))
shutil.rmtree(tmp_dir)

def test_manifest(self):
with open(root + '/manifest.json', encoding='utf-8') as file:
try:
json.loads(file.read())
except ValueError as e:
self.fail('manifest.json is not valid.')


if __name__ == '__main__':
unittest.main()
def test_unrar(self):
os.mkdir(tmp_dir)
set_defaults_env()
for rar in test_rars:
shutil.copyfile(test_data_dir + rar, tmp_dir + rar)
[_, code, _] = run_script()
self.assertEqual(code, SUCCESS)

for file in result_files:
self.assertTrue(os.path.exists(file))

shutil.rmtree(tmp_dir)

def test_manifest(self):
with open(root + "/manifest.json", encoding="utf-8") as file:
try:
json.loads(file.read())
except ValueError as e:
self.fail("manifest.json is not valid.")


if __name__ == "__main__":
unittest.main()
Loading