id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,800
|
kodi_test.py
|
novoid_Memacs/memacs/tests/kodi_test.py
|
# -*- coding: utf-8 -*-
import os
import unittest
from memacs.kodi import Kodi
class TestKodi(unittest.TestCase):
def setUp(self):
log_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data',
'kodi_audio.log')
argv = []
argv.append("-f")
argv.append(log_file)
argv.append("--fieldnames")
argv.append(
'timestamp,action,position,length,path,album,artist,title,')
argv.append("--timestamp-field")
argv.append("timestamp")
argv.append("--action-field")
argv.append("action")
argv.append("--identification-fields")
argv.append("artist,title")
argv.append("--output-format")
argv.append("{artist} - {title}")
argv.append("--properties")
argv.append("album,artist,title")
self.argv = argv
def test_audio_log(self):
memacs = Kodi(argv=self.argv)
data = memacs.test_get_entries()
# Test Simple Play and Paused
self.assertEqual(
data[0],
"** <2018-10-01 Mon 21:58>--<2018-10-01 Mon 21:59> Clueso - So sehr dabei"
)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2], " :ALBUM: Barfuss")
self.assertEqual(data[3], " :ARTIST: Clueso")
self.assertEqual(data[4], " :TITLE: So sehr dabei")
self.assertEqual(
data[5],
" :ID: 332b5cd71e335d2cf55f681a3a1fc26161465069")
self.assertEqual(data[6], " :END:")
#Test started one track and switched to another
self.assertEqual(
data[7],
"** <2018-10-01 Mon 22:03>--<2018-10-01 Mon 22:08> Clueso - Chicago"
)
self.assertEqual(data[8], " :PROPERTIES:")
self.assertEqual(data[9], " :ALBUM: Barfuss")
self.assertEqual(data[10], " :ARTIST: Clueso")
self.assertEqual(data[11], " :TITLE: Chicago")
self.assertEqual(
data[12],
" :ID: 13b38e428bb4d8c9e55183877096c921bee871e5")
self.assertEqual(data[13], " :END:")
self.assertEqual(
data[14],
"** <2018-10-01 Mon 22:08>--<2018-10-01 Mon 22:15> Clueso - So sehr dabei"
)
self.assertEqual(data[15], " :PROPERTIES:")
self.assertEqual(data[16], " :ALBUM: Barfuss")
self.assertEqual(data[17], " :ARTIST: Clueso")
self.assertEqual(data[18], " :TITLE: So sehr dabei")
self.assertEqual(
data[19],
" :ID: 4ed907d4337faaca7b2fd059072fc5046e80dc11")
self.assertEqual(data[20], " :END:")
# Pause is logged
self.assertEqual(
data[21],
"** <2018-10-01 Mon 22:16>--<2018-10-01 Mon 22:26> Clueso - So sehr dabei"
)
self.assertEqual(data[22], " :PROPERTIES:")
self.assertEqual(data[23], " :ALBUM: Barfuss")
self.assertEqual(data[24], " :ARTIST: Clueso")
self.assertEqual(data[25], " :TITLE: So sehr dabei")
self.assertEqual(
data[26],
" :ID: 9e504573886f483fa8f84fb5a8bc5d9e05be7bab")
self.assertEqual(data[27], " :END:")
def test_audio_log_with_minimal_duration(self):
self.argv.append('--minimal-pause-duration')
self.argv.append('120')
memacs = Kodi(argv=self.argv)
data = memacs.test_get_entries()
# pause is ignored
self.assertEqual(
data[0],
"** <2018-10-01 Mon 21:58>--<2018-10-01 Mon 21:59> Clueso - So sehr dabei"
)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2], " :ALBUM: Barfuss")
self.assertEqual(data[3], " :ARTIST: Clueso")
self.assertEqual(data[4], " :TITLE: So sehr dabei")
self.assertEqual(
data[5],
" :ID: 332b5cd71e335d2cf55f681a3a1fc26161465069")
self.assertEqual(data[6], " :END:")
self.assertEqual(
data[7],
"** <2018-10-01 Mon 22:03>--<2018-10-01 Mon 22:08> Clueso - Chicago"
)
self.assertEqual(data[8], " :PROPERTIES:")
self.assertEqual(data[9], " :ALBUM: Barfuss")
self.assertEqual(data[10], " :ARTIST: Clueso")
self.assertEqual(data[11], " :TITLE: Chicago")
self.assertEqual(
data[12],
" :ID: 13b38e428bb4d8c9e55183877096c921bee871e5")
self.assertEqual(data[13], " :END:")
self.assertEqual(
data[14],
"** <2018-10-01 Mon 22:08>--<2018-10-01 Mon 22:26> Clueso - So sehr dabei"
)
self.assertEqual(data[15], " :PROPERTIES:")
self.assertEqual(data[16], " :ALBUM: Barfuss")
self.assertEqual(data[17], " :ARTIST: Clueso")
self.assertEqual(data[18], " :TITLE: So sehr dabei")
self.assertEqual(
data[19],
" :ID: 9e504573886f483fa8f84fb5a8bc5d9e05be7bab")
self.assertEqual(data[20], " :END:")
| 5,212
|
Python
|
.py
| 122
| 33.04918
| 86
| 0.547047
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,801
|
arbtt_test.py
|
novoid_Memacs/memacs/tests/arbtt_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2011-10-28 15:13:31>
import os
import unittest
from memacs.arbtt import Arbtt
class TestArbtt(unittest.TestCase):
def setUp(self):
self.memacs = Arbtt()
self.sample = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'sample-arbtt.csv'
)
def test_get_sec(self):
self.assertEqual(self.memacs.get_sec('00:15:00'), 900)
def test_get_timestamp(self):
# assuming utc+1 w/o dst :)
self.assertEqual(
self.memacs.get_timestamp('02/05/17 19:00:00'),
'<2017-02-05 Sun 20:00:00>'
)
def test_get_timerange(self):
# assuming utc+1 w/o dst :)
self.assertEqual(
self.memacs.get_timerange('02/05/17 19:00:00', '02/05/17 19:15:00'),
'<2017-02-05 Sun 20:00:00>--<2017-02-05 Sun 20:15:00>'
)
def test_functional(self):
argv = []
argv.append('-s')
argv.append('--intervals=web')
# argv.append('--logfile=%s' % self.log)
# argv.append('--categorizefile=%s' % self.cfg)
argv.append('--csv=%s' % self.sample)
memacs = Arbtt(argv=argv)
data = memacs.test_get_entries()
entry = '** <2017-02-05 Sun 20:00:00>--<2017-02-05 Sun 20:15:00> Web\t:web:'
self.assertEqual(data[0], entry)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2], " :DURATION: 900")
self.assertEqual(data[4], " :END:")
| 1,521
|
Python
|
.py
| 39
| 30.846154
| 84
| 0.573279
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,802
|
simplephonelogs_test.py
|
novoid_Memacs/memacs/tests/simplephonelogs_test.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2018-08-25 15:07:37 vk>
import os
import shutil
import tempfile
import unittest
from memacs.lib.reader import CommonReader
from memacs.simplephonelogs import SimplePhoneLogsMemacs
## FIXXME: (Note) These test are *not* exhaustive unit tests. They only
## show the usage of the methods. Please add "mean" test cases and
## borderline cases!
class PhoneLogsTestCase(unittest.TestCase):
""" Base class for PhoneLogs test cases. """
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.result_file = os.path.join(self.temp_dir, 'result.org')
self.input_file = os.path.join(self.temp_dir, 'input.csv')
def tearDown(self):
shutil.rmtree(self.temp_dir)
def get_result_from_file(self):
"""reads out the resulting file and returns its content
without header lines, main heading, last finish message, and
empty lines"""
result_from_module = CommonReader.get_data_from_file(self.result_file)
result_from_module_without_header_and_last_line = ''
## remove header and last line (which includes execution-specific timing)
for line in result_from_module.split('\n'):
if line.startswith('* successfully parsed ') or \
line.startswith('#') or \
line.startswith('* '):
pass
else:
line = line.rstrip()
result_from_module_without_header_and_last_line += line + '\n'
return result_from_module_without_header_and_last_line.strip()
class TestSimplePhoneLogsBasic(PhoneLogsTestCase):
argv = False
logmodule = False
input_file = False
result_file = False
maxDiff = None ## show also large diff
def setUp(self):
super(TestSimplePhoneLogsBasic, self).setUp()
self.argv = "--suppress-messages --file " + self.input_file + " --output " + self.result_file
def test_boot_without_shutdown(self):
with open(self.input_file, 'w') as inputfile:
inputfile.write('2013-04-05 # 13.39 # boot # 42 # 612\n')
self.logmodule = SimplePhoneLogsMemacs(argv = self.argv.split())
self.logmodule.handle_main()
result = self.get_result_from_file()
self.assertEqual(result, """** <2013-04-05 Fri 13:39> boot
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 42
:UPTIME: 0:10:12
:UPTIME-S: 612
:ID: 0d78f4b2834126ecfc3fcf9cd45e5a077d055f0c
:END:""")
def test_shutdown_with_boot(self):
with open(self.input_file, 'w') as inputfile:
inputfile.write('1970-01-01 # 00.01 # shutdown # 1 # 1\n' +
'2013-04-05 # 13.39 # boot # 42 # 612\n')
self.logmodule = SimplePhoneLogsMemacs(argv = self.argv.split())
self.logmodule.handle_main()
result = self.get_result_from_file()
self.assertEqual(result, """** <1970-01-01 Thu 00:01> shutdown
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 1
:UPTIME: 0:00:01
:UPTIME-S: 1
:ID: ef7327b6c8f6e9de6ae6271d601f96133cd5b524
:END:
** <2013-04-05 Fri 13:39> boot (off for 15800d 13:38:00)
:PROPERTIES:
:IN-BETWEEN: 379213:38:00
:IN-BETWEEN-S: 1365169080
:BATT-LEVEL: 42
:UPTIME: 0:10:12
:UPTIME-S: 612
:ID: ff09a7043203c0d9eeb116779789dc19a992e299
:END:""")
def test_crashrecognition(self):
with open(self.input_file, 'w') as inputfile:
inputfile.write('2013-04-05 # 13.25 # shutdown # 1 # 10\n' +
'2013-04-05 # 13.30 # boot # 2 # 11\n' +
'2013-04-05 # 13.39 # boot # 3 # 12\n')
self.logmodule = SimplePhoneLogsMemacs(argv = self.argv.split())
self.logmodule.handle_main()
result = self.get_result_from_file()
self.assertEqual(result, """** <2013-04-05 Fri 13:25> shutdown
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 1
:UPTIME: 0:00:10
:UPTIME-S: 10
:ID: 5a5fd30fcf0bb105d3fcbf3471d343adb8a1c57d
:END:
** <2013-04-05 Fri 13:30> boot (off for 0:05:00)
:PROPERTIES:
:IN-BETWEEN: 0:05:00
:IN-BETWEEN-S: 300
:BATT-LEVEL: 2
:UPTIME: 0:00:11
:UPTIME-S: 11
:ID: e70436685735120f1e468e1ea155cc370b6d69ad
:END:
** <2013-04-05 Fri 13:39> boot after crash
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 3
:UPTIME: 0:00:12
:UPTIME-S: 12
:ID: dc41b7d0b6b415ff3a3335c1a4ad0e5ce36f5152
:END:""")
class TestSimplePhoneLogsFull(PhoneLogsTestCase):
logmodule = False
def setUp(self):
super(TestSimplePhoneLogsFull, self).setUp()
self.test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'data', 'sample-phonelog.csv'
)
self.argv = "-s -f " + self.test_file + " --output " + self.result_file
self.logmodule = SimplePhoneLogsMemacs(argv = self.argv.split())
self.logmodule.handle_main()
def test_determine_opposite_eventname(self):
self.assertEqual(self.logmodule._determine_opposite_eventname("boot"), 'shutdown')
self.assertEqual(self.logmodule._determine_opposite_eventname('shutdown'), 'boot')
self.assertEqual(self.logmodule._determine_opposite_eventname('foo'), 'foo-end')
self.assertEqual(self.logmodule._determine_opposite_eventname('foo-end'), 'foo')
def test_parser(self):
argv = "-f " + self.test_file + \
" --output " + self.result_file
localmodule = SimplePhoneLogsMemacs(argv = argv.split())
localmodule.handle_main()
result = self.get_result_from_file()
self.assertEqual(result, self.reference_result)
maxDiff = None ## show also large diff
reference_result = """** <2012-11-20 Tue 11:56> boot
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 89
:UPTIME: 1:51:32
:UPTIME-S: 6692
:ID: b63fd30ff638d906ab9e28def69dae29e126ff80
:END:
** <2012-11-20 Tue 11:56> boot
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 89
:UPTIME: 1:51:34
:UPTIME-S: 6694
:ID: f2bc17a65a66f3b63623751cbfd772e75027be6f
:END:
** <2012-11-20 Tue 19:59> shutdown (on for 8:03:00)
:PROPERTIES:
:IN-BETWEEN: 8:03:00
:IN-BETWEEN-S: 28980
:BATT-LEVEL: 72
:UPTIME: 9:54:42
:UPTIME-S: 35682
:ID: 0c462b507e45a07e6cdb5b7339f2ab9d3c29d267
:END:
** <2012-11-20 Tue 21:32> boot (off for 1:33:00)
:PROPERTIES:
:IN-BETWEEN: 1:33:00
:IN-BETWEEN-S: 5580
:BATT-LEVEL: 71
:UPTIME: 0:01:57
:UPTIME-S: 117
:ID: 69733c4f4d9676c6dec41010afd0b55880ff6055
:END:
** <2012-11-20 Tue 23:52> shutdown (on for 2:20:00)
:PROPERTIES:
:IN-BETWEEN: 2:20:00
:IN-BETWEEN-S: 8400
:BATT-LEVEL: 63
:UPTIME: 2:22:04
:UPTIME-S: 8524
:ID: 193f1e38681a8b559ad21c52a7d883cd375c18e6
:END:
** <2012-11-21 Wed 07:23> boot (off for 7:31:00)
:PROPERTIES:
:IN-BETWEEN: 7:31:00
:IN-BETWEEN-S: 27060
:BATT-LEVEL: 100
:UPTIME: 0:01:55
:UPTIME-S: 115
:ID: e869e7cc49d7aca1128ae0d6fc9651c69c5acb28
:END:
** <2012-11-21 Wed 07:52> wifi-home
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 95
:UPTIME: 0:31:19
:UPTIME-S: 1879
:ID: 4ff44273f4c79ea2d36d1eb637b1a1f6087f9a4a
:END:
** <2012-11-21 Wed 08:17> wifi-home-end (home for 0:25:00)
:PROPERTIES:
:IN-BETWEEN: 0:25:00
:IN-BETWEEN-S: 1500
:BATT-LEVEL: 92
:UPTIME: 0:56:18
:UPTIME-S: 3378
:ID: 7c10c6104b0de033661b6e7835d2006b730e624b
:END:
** <2012-11-21 Wed 13:06> boot after crash
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 77
:UPTIME: 0:02:04
:UPTIME-S: 124
:ID: 96e31802e4b176e060e008c0d934ff2e83f1d179
:END:
** <2012-11-21 Wed 21:08> wifi-home (not home for 12:51:00)
:PROPERTIES:
:IN-BETWEEN: 12:51:00
:IN-BETWEEN-S: 46260
:BATT-LEVEL: 50
:UPTIME: 8:03:53
:UPTIME-S: 29033
:ID: 7dacfb9e8480cd19a60e2e3a7c850ec9a73fc2d6
:END:
** <2012-11-22 Thu 00:12> shutdown (on for 16:49:00)
:PROPERTIES:
:IN-BETWEEN: 16:49:00
:IN-BETWEEN-S: 60540
:BATT-LEVEL: 39
:UPTIME: 11:08:09
:UPTIME-S: 40089
:HOURS_RUNTIME_EXTRAPOLATION: 29
:ID: 2d60fb40bfd9fe2da0b819c37246c4ecf6cf6f56
:END:
** <2012-11-29 Thu 08:47> boot (off for 7d 8:35:00)
:PROPERTIES:
:IN-BETWEEN: 176:35:00
:IN-BETWEEN-S: 635700
:BATT-LEVEL: 100
:UPTIME: 0:01:54
:UPTIME-S: 114
:ID: 010ec58776415894e6de09bdea6f179f1c740a15
:END:
** <2012-11-29 Thu 08:48> wifi-home (not home for 8d 0:31:00)
:PROPERTIES:
:IN-BETWEEN: 192:31:00
:IN-BETWEEN-S: 693060
:BATT-LEVEL: 100
:UPTIME: 0:01:58
:UPTIME-S: 118
:ID: e5c44c0116f8a7497389a9e357aa16b5b7a84654
:END:
** <2012-11-29 Thu 09:41> wifi-home-end (home for 0:53:00)
:PROPERTIES:
:IN-BETWEEN: 0:53:00
:IN-BETWEEN-S: 3180
:BATT-LEVEL: 98
:UPTIME: 0:55:17
:UPTIME-S: 3317
:ID: fc97dc08aa615ce3e7761ac98e7764d0bb800484
:END:
** <2012-11-29 Thu 14:46> wifi-office
:PROPERTIES:
:IN-BETWEEN:
:IN-BETWEEN-S:
:BATT-LEVEL: 81
:UPTIME: 6:00:33
:UPTIME-S: 21633
:ID: a49fde06e577f5be565360fb78a11bd46ce9a4bb
:END:
** <2012-11-29 Thu 16:15> wifi-home (not home for 6:34:00)
:PROPERTIES:
:IN-BETWEEN: 6:34:00
:IN-BETWEEN-S: 23640
:BATT-LEVEL: 76
:UPTIME: 7:29:15
:UPTIME-S: 26955
:ID: a14540f83262d71ce1e897f1bb201c59a327dbe4
:END:
** <2012-11-29 Thu 17:04> wifi-home-end (home for 0:49:00)
:PROPERTIES:
:IN-BETWEEN: 0:49:00
:IN-BETWEEN-S: 2940
:BATT-LEVEL: 74
:UPTIME: 8:18:32
:UPTIME-S: 29912
:ID: 59ccab7e44acc68645431eb404d9ee7ba105391f
:END:
** <2012-11-29 Thu 23:31> shutdown (on for 14:44:00)
:PROPERTIES:
:IN-BETWEEN: 14:44:00
:IN-BETWEEN-S: 53040
:BATT-LEVEL: 48
:UPTIME: 14:45:46
:UPTIME-S: 53146
:HOURS_RUNTIME_EXTRAPOLATION: 28
:ID: 5ce419edfe8f0268ce29369bd28160b7345e1c1d
:END:
** <2013-09-10 Tue 07:00> boot (off for 284d 7:29:00)
:PROPERTIES:
:IN-BETWEEN: 6823:29:00
:IN-BETWEEN-S: 24564540
:BATT-LEVEL: 100
:UPTIME: 0:02:10
:UPTIME-S: 130
:ID: 061afa34eb7edb532ea672f68b6f69ce4f7f967c
:END:
** <2013-09-10 Tue 08:23> wifi-office
:PROPERTIES:
:IN-BETWEEN: 6833:37:00
:IN-BETWEEN-S: 24601020
:BATT-LEVEL: 95
:UPTIME: 1:23:16
:UPTIME-S: 4996
:ID: 8e2999bcdd72126460a44ce827d95d004c6083a9
:END:
** <2013-09-10 Tue 12:13> wifi-office-end (office for 3:50:00; today 3:50:00; today total 3:50:00)
:PROPERTIES:
:IN-BETWEEN: 3:50:00
:IN-BETWEEN-S: 13800
:BATT-LEVEL: 87
:UPTIME: 5:13:46
:UPTIME-S: 18826
:OFFICE-SUMMARY: | 2013-09-10 | Tue | 08:23 | 11:30 | 12:00 | 12:13 | | |
:ID: 80fb255f140f0956cde1f82af93e37d6c3206445
:END:
** <2013-09-10 Tue 12:59> wifi-office (not office for 0:46:00)
:PROPERTIES:
:IN-BETWEEN: 0:46:00
:IN-BETWEEN-S: 2760
:BATT-LEVEL: 85
:UPTIME: 6:00:00
:UPTIME-S: 21600
:ID: d9a446d1acd443bd2b3d10df95f77e2805ead615
:END:
** <2013-09-10 Tue 17:46> wifi-office-end (office for 4:47:00; today 8:37:00; today total 9:23:00)
:PROPERTIES:
:IN-BETWEEN: 4:47:00
:IN-BETWEEN-S: 17220
:BATT-LEVEL: 73
:UPTIME: 10:47:06
:UPTIME-S: 38826
:OFFICE-SUMMARY: | 2013-09-10 | Tue | 08:23 | 12:13 | 12:59 | 17:46 | | |
:ID: b88052de1aaa8646fad9de6aa2f01c3e62cc14fe
:END:
** <2013-09-10 Tue 22:10> shutdown (on for 15:10:00)
:PROPERTIES:
:IN-BETWEEN: 15:10:00
:IN-BETWEEN-S: 54600
:BATT-LEVEL: 58
:UPTIME: 15:10:38
:UPTIME-S: 54638
:HOURS_RUNTIME_EXTRAPOLATION: 36
:ID: 8c71c9c8471972b05941d913c74fefc5613576fe
:END:
** <2013-09-11 Wed 12:15> boot (off for 14:05:00)
:PROPERTIES:
:IN-BETWEEN: 14:05:00
:IN-BETWEEN-S: 50700
:BATT-LEVEL: 87
:UPTIME: 5:15:05
:UPTIME-S: 18905
:ID: 8cc417754401bbd143036ad7ff58cef186232e53
:END:
** <2013-09-11 Wed 13:19> wifi-office (not office for 19:33:00)
:PROPERTIES:
:IN-BETWEEN: 19:33:00
:IN-BETWEEN-S: 70380
:BATT-LEVEL: 82
:UPTIME: 6:19:29
:UPTIME-S: 22769
:ID: e0b62e92f6e75a70d3cfdfb1b8ef0964933a7f8d
:END:
** <2013-09-11 Wed 18:55> wifi-office-end (office for 5:36:00; today 5:36:00; today total 5:36:00)
:PROPERTIES:
:IN-BETWEEN: 5:36:00
:IN-BETWEEN-S: 20160
:BATT-LEVEL: 69
:UPTIME: 11:56:01
:UPTIME-S: 42961
:OFFICE-SUMMARY: | 2013-09-11 | Wed | 13:19 | 11:30 | 12:00 | 18:55 | | |
:ID: 10f0f6606f3a92a5b7c599906db39e57cd4719bb
:END:
** <2013-09-11 Wed 19:10> wifi-home (not home for 286d 2:06:00)
:PROPERTIES:
:IN-BETWEEN: 6866:06:00
:IN-BETWEEN-S: 24717960
:BATT-LEVEL: 68
:UPTIME: 12:10:46
:UPTIME-S: 43846
:ID: 694280a75f124200e0faab9537c63a32f35f5838
:END:
** <2013-09-11 Wed 22:55> shutdown (on for 10:40:00)
:PROPERTIES:
:IN-BETWEEN: 10:40:00
:IN-BETWEEN-S: 38400
:BATT-LEVEL: 53
:UPTIME: 15:55:23
:UPTIME-S: 57323
:HOURS_RUNTIME_EXTRAPOLATION: 46
:ID: 2794e95db63f1752156fecb276b8b4fb20877dbb
:END:"""
# Local Variables:
# mode: flyspell
# eval: (ispell-change-dictionary "en_US")
# End:
| 14,394
|
Python
|
.py
| 416
| 29.663462
| 101
| 0.601785
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,803
|
rss_test.py
|
novoid_Memacs/memacs/tests/rss_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2018-08-25 14:44:23 vk>
import os
import unittest
from memacs.rss import RssMemacs
class TestRss(unittest.TestCase):
def setUp(self):
self.test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'data', 'sample-rss.txt'
)
self.argv = "-s -f " + self.test_file
def test_false_appending(self):
try:
memacs = RssMemacs(argv=self.argv.split())
memacs.test_get_entries()
except Exception:
pass
def test_all(self):
memacs = RssMemacs(argv=self.argv.split())
data = memacs.test_get_entries()
# omit the hour from the result because this depends on the current locals:
self.assertTrue(data[0].startswith('** <2009-09-06 Sun '))
self.assertTrue(data[0].endswith(':45> [[http://www.wikipedia.org/][Example entry]]'))
self.assertEqual(
data[2],
" :GUID: unique string per item")
self.assertEqual(
data[3],
' :PUBLISHED: Mon, 06 Sep 2009 16:45:00 +0000'
)
self.assertEqual(
data[4],
" :ID: a0df7d405a7e9822fdd86af04e162663f1dccf11"
)
self.assertEqual(
data[6],
" Here is some text containing an interesting description."
)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[5], " :END:")
| 1,500
|
Python
|
.py
| 41
| 27.536585
| 94
| 0.566598
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,804
|
git_test.py
|
novoid_Memacs/memacs/tests/git_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2011-10-28 15:13:31 aw>
import os
import unittest
from memacs.git import Commit
from memacs.git import GitMemacs
class TestCommit(unittest.TestCase):
def test_ID_empty(self):
c = Commit()
self.assertTrue(c.is_empty())
def test_ID(self):
c = Commit()
c.add_header("author Armin Wieser <armin.wieser" + \
"@example.com> 1324422878 +0100")
c.add_body("i'm the subject")
c.add_body("i'm in the body")
output, properties, note, author, timestamp = c.get_output()
self.assertEqual(output, "Armin Wieser: i'm the subject")
self.assertEqual(note, "i'm in the body\n")
self.assertEqual(author, "Armin Wieser")
self.assertEqual(timestamp, "<2011-12-21 Wed 00:14>")
#for p in unicode(properties).splitlines():
# print "\"" + p + "\\n\""
p = " :PROPERTIES:\n"
p += " :AUTHOR: Armin Wieser <armin.wieser@example.com> " + \
"1324422878 +0100\n"
p += " :ID: 2bcf0df19183b508b7d52e38ee1d811aabd207f5\n"
p += " :END:"
self.assertEqual(str(properties), p)
class TestGitMemacs(unittest.TestCase):
def setUp(self):
self.test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'data', 'git-rev-list-raw.txt'
)
def test_from_file(self):
argv = "-s -f " + self.test_file
memacs = GitMemacs(argv=argv.split())
data = memacs.test_get_entries()
self.assertEqual(
data[0],
"** <2011-11-19 Sat 11:50> Karl Voit:" + \
" corrected cron-info for OS X")
self.assertEqual(
data[1],
" :PROPERTIES:")
self.assertEqual(
data[2],
" :COMMIT: 052ffa660ce1d8b0f9dd8f8fc794222e2463dce1")
self.assertEqual(
data[3],
" :TREE: 0c785721ff806d2570cb7d785adf294b0406609b")
self.assertEqual(
data[4],
" :PARENT: 62f20271b87e8574370f1ded29938dad0313a399")
self.assertEqual(
data[5],
" :AUTHOR: Karl Voit <git@example." + \
"com> 1321699855 +0100")
self.assertEqual(
data[6],
" :COMMITTER: Karl Voit <git@example.com> 1321699855" + \
" +0100")
self.assertEqual(
data[7],
" :ID: e77d956db6f5720f6b30e2d7fd608807c7a75f9f")
self.assertEqual(
data[8],
" :END:")
self.assertEqual(
data[9],
"** <2011-11-19 Sat 11:50> Karl Voit: added RSS " + \
"module description")
self.assertEqual(
data[10],
" :PROPERTIES:")
self.assertEqual(
data[11],
" :COMMIT: 62f20271b87e8574370f1ded29938dad0313a399")
self.assertEqual(
data[12],
" :TREE: 906b8b7e4bfd08850aef8c15b0fc4d5f6e9cc9a7")
self.assertEqual(
data[13],
" :PARENT: 638e81c55daf0a69c78cc3af23a9e451ccea44ab")
self.assertEqual(
data[14],
" :AUTHOR: Karl Voit <git@example.com> 132" + \
"1699830 +0100")
self.assertEqual(
data[15],
" :COMMITTER: Karl Voit <git@example.c" + \
"om> 1321699830 +0100")
self.assertEqual(
data[16],
" :ID: d5f45fc44e23a7f042d56e09ccfe7772614afe97")
self.assertEqual(
data[17],
" :END:")
self.assertEqual(
data[18],
"** <2011-11-02 Wed 22:46> Armin Wieser: add" + \
"ed Orgformate.date()")
self.assertEqual(
data[19],
" :PROPERTIES:")
self.assertEqual(
data[20],
" :COMMIT: 9b4523b2c4542349e8b4ca3ca595701a50b3c315")
self.assertEqual(
data[21],
" :TREE: 2d440e6b42b917e9a69d5283b9d1ed4a77797ee9")
self.assertEqual(
data[22],
" :PARENT: 7ddaa9839611662c5c0dbf2bb2740e362ae4d566")
self.assertEqual(
data[23],
" :AUTHOR: Armin Wieser <armin.wieser@ex" + \
"ample.com> 1320270366 +0100")
self.assertEqual(
data[24],
" :COMMITTER: Armin Wieser <armin.wieser@" + \
"example.com> 1320270366 +0100")
self.assertEqual(
data[25],
" :SIGNED-OFF-BY: Armin Wieser <armin.wieser@example.com>")
self.assertEqual(
data[26],
" :ID: 8c806b9e28cacb7bb540fc921a0bda15b34289ee")
self.assertEqual(
data[27],
" :END:")
self.assertEqual(
data[28],
"** <2011-11-02 Wed 19:58> Armin Wieser: orgf" + \
"ormat added for orgmode-syntax")
self.assertEqual(
data[29],
" :PROPERTIES:")
self.assertEqual(
data[30],
" :COMMIT: 7ddaa9839611662c5c0dbf2bb2740e362ae4d566")
self.assertEqual(
data[31],
" :TREE: 663a7c370b985f3b7e9794dec07f28d4e6ff3936")
self.assertEqual(
data[32],
" :PARENT: f845d8c1f1a4194e3b27b5bf39bac1b30bd095f6")
self.assertEqual(
data[33],
" :AUTHOR: Armin Wieser <armin.wieser@" + \
"example.com> 1320260312 +0100")
self.assertEqual(
data[34],
" :COMMITTER: Armin Wieser <armin.wieser@e" + \
"xample.com> 1320260312 +0100")
self.assertEqual(
data[35],
" :SIGNED-OFF-BY: Armin Wieser <armin.wieser@example.com>")
self.assertEqual(
data[36],
" :ID: 50d3dd0e8c02857c5ceff3c04bff732a2ad67d04")
self.assertEqual(
data[37],
" :END:")
def test_number_entries_all(self):
argv = "-s -f " + self.test_file
memacs = GitMemacs(argv=argv.split())
data = memacs.test_get_entries()
self.assertEqual(len(data), 109) # 109 lines in sum
def test_number_entries_grep(self):
argv = '-s -f ' + self.test_file
argv = argv.split()
argv.append("-g")
argv.append("Armin Wieser")
memacs = GitMemacs(argv=argv)
data = memacs.test_get_entries()
self.assertEqual(len(data), 91) # 91 lines from Armin Wieser
| 6,748
|
Python
|
.py
| 178
| 26.932584
| 75
| 0.522814
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,805
|
battery_test.py
|
novoid_Memacs/memacs/tests/battery_test.py
|
# -*- coding: utf-8 -*-
import os
import unittest
from memacs.battery import Battery
class TestCsv(unittest.TestCase):
def test_battery(self):
path = os.path.dirname(os.path.abspath(__file__))
argv = []
argv.append("-p")
argv.append(os.path.join(path, "data"))
memacs = Battery(argv=argv)
data = memacs.test_get_entries()
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2], " :CYCLE_COUNT: 866")
self.assertEqual(data[3], " :CAPACITY: 97%")
self.assertEqual(data[4], " :STATUS: discharging")
self.assertEqual(data[5], " :CONSUMPTION: 11.9 W")
self.assertEqual(data[7], " :END:")
| 725
|
Python
|
.py
| 18
| 33.222222
| 65
| 0.598854
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,806
|
phonecalls_superbackup_test.py
|
novoid_Memacs/memacs/tests/phonecalls_superbackup_test.py
|
# -*- coding: utf-8 -*-
import os
import unittest
from memacs.phonecalls_superbackup import PhonecallsSuperBackupMemacs
class TestPhonecallsSuperBackup(unittest.TestCase):
def setUp(self):
self._test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data',
'calls_superbackup.xml')
argv = "-s -f " + self._test_file
memacs = PhonecallsSuperBackupMemacs(argv=argv.split())
self.data = memacs.test_get_entries()
def test_all(self):
self.assertEqual(
self.data[0],
"** <2018-09-17 Mon 19:58>-<2018-09-17 Mon 20:02> Phonecall from [[contact:TestPerson1][TestPerson1]]"
)
self.assertEqual(self.data[1], " :PROPERTIES:")
self.assertEqual(self.data[2], " :NUMBER: +49123456789")
self.assertEqual(self.data[3], " :DURATION: 264")
self.assertEqual(self.data[4], " :NAME: TestPerson1")
self.assertEqual(
self.data[5],
" :ID: 4a6f6cb848be3870cd1540afb50185e12fa7a02c")
self.assertEqual(self.data[6], " :END:")
self.assertEqual(
self.data[7],
"** <2018-09-17 Mon 17:24>-<2018-09-17 Mon 17:25> Phonecall from [[contact:TestPerson2][TestPerson2]]"
)
self.assertEqual(self.data[8], " :PROPERTIES:")
self.assertEqual(self.data[9], " :NUMBER: +4912345678910")
self.assertEqual(self.data[10], " :DURATION: 73")
self.assertEqual(self.data[11], " :NAME: TestPerson2")
self.assertEqual(
self.data[12],
" :ID: 09df2166236a87f343523257fbd8f2b5537ea882")
self.assertEqual(self.data[13], " :END:")
| 1,746
|
Python
|
.py
| 37
| 38.27027
| 114
| 0.596244
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,807
|
photos_test.py
|
novoid_Memacs/memacs/tests/photos_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2014-05-03 17:46:44 vk>
import os
import unittest
from memacs.photos import PhotosMemacs
class TestPhotoMemacs(unittest.TestCase):
def test_from_file(self):
test_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data'
)
argv = "-s -f " + test_path
memacs = PhotosMemacs(argv=argv.split())
data = memacs.test_get_entries()
filename = 'fujifilm-finepix40i.jpg'
path = os.path.join(test_path, filename)
self.assertEqual(
data[0],
"** <2000-08-04 Fri 18:22> [[%s][%s]]" % (path, filename)
)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(
data[2],
" :ID: c2833ac1c683dea5b600ac4f303a572d2148e1e7"
)
self.assertEqual(data[3], " :END:")
| 888
|
Python
|
.py
| 25
| 27.52
| 70
| 0.57243
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,808
|
whatsapp_test.py
|
novoid_Memacs/memacs/tests/whatsapp_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2018-09-22 13:57:41 vk>
import os
import unittest
from memacs.whatsapp import WhatsApp
class TestWhatsApp(unittest.TestCase):
def setUp(self):
msgstore = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'msgstore.db'
)
self.argv = []
self.argv.append('-f')
self.argv.append(msgstore)
def test_whatsapp(self):
self.argv.append('--output-format')
self.argv.append('{text}')
memacs = WhatsApp(argv=self.argv)
data = memacs.test_get_entries()
# omit hours from check because of different TZ offset:
self.assertTrue(data[0].startswith('** <2016-10-15 Sat '))
self.assertTrue(data[0].endswith(':18> Hello World!'))
self.assertEqual(data[1], ' :PROPERTIES:')
self.assertEqual(data[2], ' :NUMBER: 00436604444333')
self.assertEqual(data[3], ' :TYPE: INCOMING')
# Karl had to disable the ID check because with different TZ offsets, the ID hash changes:
# self.assertEqual(data[4], ' :ID: 804c40b796f8d71f48c9cd0023d1059e56d54d61')
self.assertEqual(data[5], ' :END:')
| 1,214
|
Python
|
.py
| 27
| 37.555556
| 98
| 0.623939
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,809
|
filenametimestamps_test.py
|
novoid_Memacs/memacs/tests/filenametimestamps_test.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2019-10-09 15:12:44 vk>
import datetime
import os
import shutil
import tempfile
import unittest
from memacs.filenametimestamps import FileNameTimeStamps
class TestFileNameTimeStamps(unittest.TestCase):
def setUp(self):
self._tmp_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self._tmp_dir)
def touch_file(self, basename):
"""
Creates a test file and returns the Org mode link to it
"""
tmpfile = os.path.join(self._tmp_dir, basename)
with open(tmpfile, 'w'):
pass
return '[[file:' + tmpfile + '][' + basename + ']]'
#######################################################################
# NOT tested so far:
# --append
# --columns-header STRING
# --custom-header
# --skip-files-with-no-or-wrong-timestamp
# --add-to-time-stamps -> KNOWN BUG; see https://github.com/novoid/Memacs/issues/92 - disabled tests below!
#######################################################################
def call_omit_drawers(self):
"""
Invokes the filenametimestamp module with basic parameters skipping the drawers
"""
argv = "--suppress-messages --omit-drawers --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
return memacs.test_get_entries()
def test_good_case1(self):
self.assertEqual('** <2019-10-03 Thu 09:55> ' + self.touch_file('2019-10-03T09.55.00 foo.txt'), self.call_omit_drawers()[0])
def test_good_case2(self):
self.assertEqual('** <2019-05-28 Tue>--<2019-07-24 Wed> ' + self.touch_file('2019-05-28--2019-07-24 Test -- scan notes.pdf'), self.call_omit_drawers()[0])
def test_good_timestamp_with_no_second(self):
self.assertEqual('** <2019-10-03 Thu 09:55> ' + self.touch_file('2019-10-03T09.55 foo.txt'), self.call_omit_drawers()[0])
def test_good_datestamp(self):
self.assertEqual('** <2019-10-02 Wed> ' + self.touch_file('2019-10-02 foo.txt'), self.call_omit_drawers()[0])
def test_good_datestamp_with_determining_time_from_file(self):
# FIXXME: caveat: this adds some tiny dependency: if the
# minute changes between the file creation and the check, this
# test fails
today_weekday = datetime.datetime.now().strftime('<%Y-%m-%d %a %H:%M> ') # FIXXME: dependency on current locale: works only with English weekdays
today_day = datetime.datetime.now().strftime('%Y-%m-%d')
self.assertEqual('** ' + today_weekday + self.touch_file(today_day + ' foo.txt'), self.call_omit_drawers()[0])
def test_good_datestamp_without_month(self):
self.assertEqual('** <2019-10-01 Tue> ' + self.touch_file('2019-10 foo.txt'), self.call_omit_drawers()[0])
def test_good_case_with_seconds(self):
self.assertEqual('** <2019-10-03 Thu 09:55> ' + self.touch_file('2019-10-03T09.55.00 foo.txt'), self.call_omit_drawers()[0])
def test_good_case_without_datestamp(self):
self.assertEqual('** ' + self.touch_file('foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_second(self):
# this might be debatable: wrong seconds are wrong but the
# seconds don't appear in the Org mode time stamp so I ignore
# them so far.
self.assertEqual('** <2019-10-01 Tue 09:55> ' + self.touch_file('2019-10-01T09.55.60 foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_minute(self):
# an erroneous minute results in a correct date-stamp only
self.assertEqual('** <2019-10-01 Tue> ' + self.touch_file('2019-10-01T09.60.01 foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_hour(self):
self.assertEqual('** <2019-10-01 Tue> ' + self.touch_file('2019-10-01T24.59.01 foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_day1(self):
self.assertEqual('** ' + self.touch_file('2019-10-00T23.59.59 foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_day2(self):
self.assertEqual('** ' + self.touch_file('2019-10-32T23.59.59 foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_day3(self):
self.assertEqual('** ' + self.touch_file('2019-04-31T23.59.59 foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_month1(self):
self.assertEqual('** ' + self.touch_file('2019-00-30T23.59.59 foo.txt'), self.call_omit_drawers()[0])
def test_wrong_timestamp_in_month2(self):
self.assertEqual('** ' + self.touch_file('2019-13-30T23.59.59 foo.txt'), self.call_omit_drawers()[0])
#######################################################################
# def test_duration_case_dashdash(self):
# self.assertEqual('** <2019-10-03 Thu 09:55>--<2019-10-05 Sat 17:59> ' + self.touch_file('2019-10-03T09.55.00--2019-10-05T17.59.59 foo.txt'), self.call_omit_drawers()[0])
#
# def test_duration_case_dash(self):
# self.assertEqual('** <2019-10-03 Thu 09:55>--<2019-10-05 Sat 17:59> ' + self.touch_file('2019-10-03T09.55.00-2019-10-05T17.59.59 foo.txt'), self.call_omit_drawers()[0])
#
# def test_duration_timestamp_with_no_second_dashdash(self):
# self.assertEqual('** <2019-10-03 Thu 09:55>--<2019-10-05 Sat 17:59> ' + self.touch_file('2019-10-03T09.55--2019-10-05T17.59 foo.txt'), self.call_omit_drawers()[0])
#
# def test_duration_timestamp_with_no_second_dash(self):
# self.assertEqual('** <2019-10-03 Thu 09:55>--<2019-10-05 Sat 17:59> ' + self.touch_file('2019-10-03T09.55-2019-10-05T17.59 foo.txt'), self.call_omit_drawers()[0])
#
# def test_duration_datestamp_dashdash(self):
# self.assertEqual('** <2019-10-02 Wed>--<2019-10-05 Sat> ' + self.touch_file('2019-10-02--2019-10-05 foo.txt'), self.call_omit_drawers()[0])
#
# def test_duration_datestamp_dash(self):
# self.assertEqual('** <2019-10-02 Wed>--<2019-10-05 Sat> ' + self.touch_file('2019-10-02-2019-10-05 foo.txt'), self.call_omit_drawers()[0])
# FIXXME: tests with mixed time- and day-stamps + different order
#######################################################################
def call_force_file_date_extraction(self):
argv = "--force-file-date-extraction --suppress-messages --omit-drawers --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
return memacs.test_get_entries()
def test_force_file_date_extraction(self):
today_weekday = datetime.datetime.now().strftime('<%Y-%m-%d %a %H:%M> ') # FIXXME: dependency on current locale: works only with English weekdays
self.assertEqual('** ' + today_weekday + self.touch_file('2019-10-01T23.59.59 foo.txt'), self.call_force_file_date_extraction()[0])
#######################################################################
def call_skip_file_time_extraction(self):
argv = "--skip-file-time-extraction --suppress-messages --omit-drawers --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
return memacs.test_get_entries()
def test_skip_file_time_extraction(self):
today_weekday = datetime.datetime.now().strftime('<%Y-%m-%d %a> ') # FIXXME: dependency on current locale: works only with English weekdays
today_day = datetime.datetime.now().strftime('%Y-%m-%d')
self.assertEqual('** ' + today_weekday + self.touch_file(today_day + ' foo.txt'), self.call_skip_file_time_extraction()[0])
#######################################################################
def call_inactive_time_stamps(self):
argv = "--inactive-time-stamps --suppress-messages --omit-drawers --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
return memacs.test_get_entries()
def test_inactive_time_stamps_good_case(self):
self.assertEqual('** [2019-10-03 Thu 09:55] ' + self.touch_file('2019-10-03T09.55.00 foo.txt'), self.call_inactive_time_stamps()[0])
def test_inactive_time_stamps_good_timestamp_with_no_second(self):
self.assertEqual('** [2019-10-03 Thu 09:55] ' + self.touch_file('2019-10-03T09.55 foo.txt'), self.call_inactive_time_stamps()[0])
def test_inactive_time_stamps_good_datestamp(self):
self.assertEqual('** [2019-10-02 Wed] ' + self.touch_file('2019-10-02 foo.txt'), self.call_inactive_time_stamps()[0])
def test_inactive_time_stamps_good_datestamp_with_determining_time_from_file(self):
# FIXXME: caveat: this adds some tiny dependency: if the
# minute changes between the file creation and the check, this
# test fails
today_weekday = datetime.datetime.now().strftime('[%Y-%m-%d %a %H:%M] ') # FIXXME: dependency on current locale: works only with English weekdays
today_day = datetime.datetime.now().strftime('%Y-%m-%d')
self.assertEqual('** ' + today_weekday + self.touch_file(today_day + ' foo.txt'), self.call_inactive_time_stamps()[0])
def test_inactive_time_stamps_good_datestamp_without_month(self):
self.assertEqual('** [2019-10-01 Tue] ' + self.touch_file('2019-10 foo.txt'), self.call_inactive_time_stamps()[0])
def test_inactive_time_stamps_good_case_with_seconds(self):
self.assertEqual('** [2019-10-03 Thu 09:55] ' + self.touch_file('2019-10-03T09.55.00 foo.txt'), self.call_inactive_time_stamps()[0])
def test_inactive_time_stamps_good_case_without_datestamp(self):
self.assertEqual('** ' + self.touch_file('foo.txt'), self.call_inactive_time_stamps()[0])
#######################################################################
def call_active_time_stamps(self):
argv = "--suppress-messages --omit-drawers --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
return memacs.test_get_entries()
def test_active_time_stamps_good_case(self):
self.assertEqual('** <2019-10-03 Thu 09:55> ' + self.touch_file('2019-10-03T09.55.00 foo.txt'), self.call_active_time_stamps()[0])
def test_active_time_stamps_good_timestamp_with_no_second(self):
self.assertEqual('** <2019-10-03 Thu 09:55> ' + self.touch_file('2019-10-03T09.55 foo.txt'), self.call_active_time_stamps()[0])
def test_active_time_stamps_good_datestamp(self):
self.assertEqual('** <2019-10-02 Wed> ' + self.touch_file('2019-10-02 foo.txt'), self.call_active_time_stamps()[0])
def test_active_time_stamps_good_datestamp_with_determining_time_from_file(self):
# FIXXME: caveat: this adds some tiny dependency: if the
# minute changes between the file creation and the check, this
# test fails
today_weekday = datetime.datetime.now().strftime('<%Y-%m-%d %a %H:%M> ') # FIXXME: dependency on current locale: works only with English weekdays
today_day = datetime.datetime.now().strftime('%Y-%m-%d')
self.assertEqual('** ' + today_weekday + self.touch_file(today_day + ' foo.txt'), self.call_active_time_stamps()[0])
def test_active_time_stamps_good_datestamp_without_day(self):
self.assertEqual('** <2019-10-01 Tue> ' + self.touch_file('2019-10 foo.txt'), self.call_active_time_stamps()[0])
def test_active_time_stamps_good_case_with_seconds(self):
self.assertEqual('** <2019-10-03 Thu 09:55> ' + self.touch_file('2019-10-03T09.55.00 foo.txt'), self.call_active_time_stamps()[0])
def test_active_time_stamps_good_case_without_datestamp(self):
self.assertEqual('** ' + self.touch_file('foo.txt'), self.call_active_time_stamps()[0])
#######################################################################
# Disabled for now due to a KNOWN BUG: see https://github.com/novoid/Memacs/issues/92 -> FIXXME
# def call_add_to_time_stamps(self):
# argv = "--add-to-time-stamps \"+2\" --suppress-messages --omit-drawers --folder " + self._tmp_dir
# memacs = FileNameTimeStamps(argv=argv.split())
# return memacs.test_get_entries()
#
# def test_add_to_time_stamps_good_case(self):
# self.assertEqual('** <2019-10-03 Thu 11:55> ' + self.touch_file('2019-10-03T09.55.00 foo.txt'), self.call_add_to_time_stamps()[0])
#
# def test_add_to_time_stamps_good_timestamp_with_no_second(self):
# self.assertEqual('** <2019-10-03 Thu 11:55> ' + self.touch_file('2019-10-03T09.55 foo.txt'), self.call_add_to_time_stamps()[0])
#
# def test_add_to_time_stamps_good_datestamp(self):
# self.assertEqual('** <2019-10-02 Wed> ' + self.touch_file('2019-10-02 foo.txt'), self.call_add_to_time_stamps()[0])
#######################################################################
def call_basic(self):
"""
Invokes the filenametimestamp module with basic parameters resulting in drawers with IDs
"""
argv = "--suppress-messages --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
return memacs.test_get_entries()
def test_functional_with_drawer(self):
link = self.touch_file('2011-12-19T23.59.12_test1.txt')
entry = "** <2011-12-19 Mon 23:59> " + link
data = self.call_basic()
self.assertEqual(data[0], entry)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2].strip()[:4], ":ID:")
self.assertEqual(data[3], " :END:")
def test_functional_with_unusual_year_with_drawer(self):
link = self.touch_file('1971-12-30T00.01.01_P1000286.jpg')
entry = "** <1971-12-30 Thu 00:01> " + link
data = self.call_basic()
self.assertEqual(data[0], entry)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2].strip()[:4], ":ID:")
self.assertEqual(data[3], " :END:")
def test_year_out_of_range_with_drawer(self):
link = self.touch_file('1899-12-30T00.00.00_P1000286.jpg')
entry = "** " + link
data = self.call_basic()
self.assertEqual(data[0], entry)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2].strip()[:4], ":ID:")
self.assertEqual(data[3], " :END:")
#######################################################################
# Testing private methods is considered a bad thing to do:
# https://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones/47401015#47401015
# Here, I deliberately decide to test private methods as well
# since their failure would be complicated to test from the
# public methods alone.
# Still, their semantic is that way that they are not part of
# the public method API of the class.
def test__check_datestamp_correctness(self):
argv = "--suppress-messages --omit-drawers --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
self.assertTrue(memacs._FileNameTimeStamps__check_datestamp_correctness('2019-12-31'))
self.assertTrue(memacs._FileNameTimeStamps__check_datestamp_correctness('2000-01-01'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('1999-00-01'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('1999-01-00'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('1999-13-00'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('1999-12-32'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('abc'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness(''))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('1'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('1-2-3'))
self.assertFalse(memacs._FileNameTimeStamps__check_datestamp_correctness('2000-2-3'))
def test__check_timestamp_correctness(self):
argv = "--suppress-messages --omit-drawers --folder " + self._tmp_dir
memacs = FileNameTimeStamps(argv=argv.split())
self.assertTrue(memacs._FileNameTimeStamps__check_timestamp_correctness('00:00'))
self.assertTrue(memacs._FileNameTimeStamps__check_timestamp_correctness('23:59'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('1:2'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('12:2'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('1:23'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness(''))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('abcde'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('ab:cd'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('24:00'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('23:61'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('12.34'))
self.assertFalse(memacs._FileNameTimeStamps__check_timestamp_correctness('a'))
| 17,177
|
Python
|
.py
| 246
| 62.772358
| 178
| 0.641976
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,810
|
example_test.py
|
novoid_Memacs/memacs/tests/example_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2018-08-25 14:16:04 vk>
import unittest
from memacs.example import Foo
class TestFoo(unittest.TestCase):
def setUp(self):
pass
def test_all(self):
argv = "-s"
memacs = Foo(argv=argv.split())
# or when in append mode:
# memacs = Foo(argv=argv.split(), append=True)
data = memacs.test_get_entries()
# generate assertEquals :)
#for d in range(len(data)):
# print "self.assertEqual(\n\tdata[%d],\n\t\"%s\")" % \
# (d, data[d])
self.assertEqual(
data[0],
"** <1970-01-01 Thu 00:00> foo")
self.assertEqual(
data[1],
" :PROPERTIES:")
self.assertEqual(
data[2],
" :ID: e7663db158b7ba301fb23e3dc40347970c7f8a0f")
self.assertEqual(
data[3],
" :END:")
self.assertEqual(
data[4],
"** <1970-01-01 Thu 00:00> bar\t:tag1:tag2:")
self.assertEqual(
data[5],
" :PROPERTIES:")
self.assertEqual(
data[6],
" :DESCRIPTION: foooo")
self.assertEqual(
data[7],
" :FOO-PROPERTY: asdf")
self.assertEqual(
data[8],
" :ID: 97521347348df02dab8bf86fbb6817c0af333a3f")
self.assertEqual(
data[9],
" :END:")
self.assertEqual(
data[10],
" bar notes")
self.assertEqual(
data[11],
" foo notes")
def tearDown(self):
pass
| 1,663
|
Python
|
.py
| 55
| 20.272727
| 73
| 0.482176
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,811
|
ical_test.py
|
novoid_Memacs/memacs/tests/ical_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2016-01-23 18:07:46 vk>
import os
import re
import tempfile
import time
import unittest
from memacs.ical import CalendarMemacs
class TestCalendar(unittest.TestCase):
def test_all(self):
test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'data', 'austrian_holidays_from_google.ics'
)
argv = "-s -cf " + test_file
memacs = CalendarMemacs(argv=argv.split())
data = memacs.test_get_entries()
self.assertEqual(
data[0],
"** <2012-05-28 Mon> Whit Monday")
self.assertEqual(
data[1],
" :PROPERTIES:")
self.assertEqual(
data[2],
" :ID: 8ba5a253410baff870da60487d97976bae948e6d")
self.assertEqual(
data[3],
" :END:")
self.assertEqual(
data[4],
"** <2011-02-14 Mon> Valentine's day")
self.assertEqual(
data[5],
" :PROPERTIES:")
self.assertEqual(
data[6],
" :ID: e5d97f07e8df141cddb101943449afddbc2c4366")
self.assertEqual(
data[7],
" :END:")
self.assertEqual(
data[8],
"** <2010-02-14 Sun> Valentine's day")
self.assertEqual(
data[9],
" :PROPERTIES:")
self.assertEqual(
data[10],
" :ID: 7816a7cfdeebd359c435e5da53dbbe15e0902115")
self.assertEqual(
data[11],
" :END:")
self.assertEqual(
data[12],
"** <2012-02-14 Tue> Valentine's day")
self.assertEqual(
data[13],
" :PROPERTIES:")
self.assertEqual(
data[14],
" :ID: e3e1dfc836f4ddb91be7e396001993dc42dac33d")
self.assertEqual(
data[15],
" :END:")
self.assertEqual(
data[16],
"** <2012-12-26 Wed> St. Stephan's Day")
self.assertEqual(
data[17],
" :PROPERTIES:")
self.assertEqual(
data[18],
" :ID: 5f2df9848d632c475e3cf509251f31359828cd19")
self.assertEqual(
data[19],
" :END:")
self.assertEqual(
data[20],
"** <2010-12-26 Sun> St. Stephan's Day")
self.assertEqual(
data[21],
" :PROPERTIES:")
self.assertEqual(
data[22],
" :ID: e74c056dfdb5ebcbfd8d725eacf5fe2180204705")
self.assertEqual(
data[23],
" :END:")
self.assertEqual(
data[24],
"** <2011-12-26 Mon> St. Stephan's Day")
self.assertEqual(
data[25],
" :PROPERTIES:")
self.assertEqual(
data[26],
" :ID: 646b8200bd6186fc7c75bac6050486544edf9208")
self.assertEqual(
data[27],
" :END:")
self.assertEqual(
data[28],
"** <2011-12-06 Tue> St. Nicholas")
self.assertEqual(
data[29],
" :PROPERTIES:")
self.assertEqual(
data[30],
" :ID: 3beb4ee6504aea9042b8a760a4cfdb82b24cb271")
self.assertEqual(
data[31],
" :END:")
self.assertEqual(
data[32],
"** <2010-12-06 Mon> St. Nicholas")
self.assertEqual(
data[33],
" :PROPERTIES:")
self.assertEqual(
data[34],
" :ID: ee05ddc226cfd7cbde339d25d9983a2e528040a9")
self.assertEqual(
data[35],
" :END:")
self.assertEqual(
data[36],
"** <2012-12-06 Thu> St. Nicholas")
self.assertEqual(
data[37],
" :PROPERTIES:")
self.assertEqual(
data[38],
" :ID: 110237aee7b949c84e1c5614f1f7fb631c9ff942")
self.assertEqual(
data[39],
" :END:")
self.assertEqual(
data[40],
"** <2011-12-31 Sat> New Year's Eve")
self.assertEqual(
data[41],
" :PROPERTIES:")
self.assertEqual(
data[42],
" :ID: 1a571159635d3d651b6af68d20620eade7f8a984")
self.assertEqual(
data[43],
" :END:")
self.assertEqual(
data[44],
"** <2010-12-31 Fri> New Year's Eve")
self.assertEqual(
data[45],
" :PROPERTIES:")
self.assertEqual(
data[46],
" :ID: cc2b9683716ac8d32c381ae9380d0a25f57ae0f5")
self.assertEqual(
data[47],
" :END:")
self.assertEqual(
data[48],
"** <2012-01-01 Sun> New Year")
self.assertEqual(
data[49],
" :PROPERTIES:")
self.assertEqual(
data[50],
" :ID: 0b5b288f6b0322e0fae4beed157989d319b82814")
self.assertEqual(
data[51],
" :END:")
self.assertEqual(
data[52],
"** <2010-01-01 Fri> New Year")
self.assertEqual(
data[53],
" :PROPERTIES:")
self.assertEqual(
data[54],
" :ID: ab434dc5112a7a5c2237131c71ca254f5f99dc05")
self.assertEqual(
data[55],
" :END:")
self.assertEqual(
data[56],
"** <2011-01-01 Sat> New Year")
self.assertEqual(
data[57],
" :PROPERTIES:")
self.assertEqual(
data[58],
" :ID: 869198e6dcfa0bc49fc171f17d50ba49d3fe62a7")
self.assertEqual(
data[59],
" :END:")
self.assertEqual(
data[60],
"** <2010-10-26 Tue> National Holiday")
self.assertEqual(
data[61],
" :PROPERTIES:")
self.assertEqual(
data[62],
" :ID: 3c6042aba5db24b2ed09eedc1b3da56e7e0b601f")
self.assertEqual(
data[63],
" :END:")
self.assertEqual(
data[64],
"** <2012-10-26 Fri> National Holiday")
self.assertEqual(
data[65],
" :PROPERTIES:")
self.assertEqual(
data[66],
" :ID: 601c8de3cea5d678e9919c9d64b1d7655f7843e5")
self.assertEqual(
data[67],
" :END:")
self.assertEqual(
data[68],
"** <2011-10-26 Wed> National Holiday")
self.assertEqual(
data[69],
" :PROPERTIES:")
self.assertEqual(
data[70],
" :ID: 2f61fd1f446d4f384f3caf65a404d50b86f696a4")
self.assertEqual(
data[71],
" :END:")
self.assertEqual(
data[72],
"** <2011-05-01 Sun> Labour Day")
self.assertEqual(
data[73],
" :PROPERTIES:")
self.assertEqual(
data[74],
" :ID: 781eb260ac25af31e97c26890f105ef7fdf03635")
self.assertEqual(
data[75],
" :END:")
self.assertEqual(
data[76],
"** <2010-05-01 Sat> Labour Day")
self.assertEqual(
data[77],
" :PROPERTIES:")
self.assertEqual(
data[78],
" :ID: 70c5b304f299beac1474dd8bef716d47e1cf15a7")
self.assertEqual(
data[79],
" :END:")
self.assertEqual(
data[80],
"** <2012-05-01 Tue> Labour Day")
self.assertEqual(
data[81],
" :PROPERTIES:")
self.assertEqual(
data[82],
" :ID: c3b5e3ed1905b6a8c63847ad5ea12a87108f951f")
self.assertEqual(
data[83],
" :END:")
self.assertEqual(
data[84],
"** <2012-12-08 Sat> Immaculate Conception")
self.assertEqual(
data[85],
" :PROPERTIES:")
self.assertEqual(
data[86],
" :ID: 9b716e3e1d58220b301621c6f027e73667ab7b52")
self.assertEqual(
data[87],
" :END:")
self.assertEqual(
data[88],
"** <2010-12-08 Wed> Immaculate Conception")
self.assertEqual(
data[89],
" :PROPERTIES:")
self.assertEqual(
data[90],
" :ID: b9a77981c516f27a9985223d5af3e578f1d11c3d")
self.assertEqual(
data[91],
" :END:")
self.assertEqual(
data[92],
"** <2011-12-08 Thu> Immaculate Conception")
self.assertEqual(
data[93],
" :PROPERTIES:")
self.assertEqual(
data[94],
" :ID: 4043adda1b297521c55cd06b912de52e1373a999")
self.assertEqual(
data[95],
" :END:")
self.assertEqual(
data[96],
"** <2012-04-06 Fri> Good Friday")
self.assertEqual(
data[97],
" :PROPERTIES:")
self.assertEqual(
data[98],
" :ID: 344c7600e82efb9445e871b931877d051b94b6c9")
self.assertEqual(
data[99],
" :END:")
self.assertEqual(
data[100],
"** <2010-01-06 Wed> Epiphany")
self.assertEqual(
data[101],
" :PROPERTIES:")
self.assertEqual(
data[102],
" :ID: 93ba1d459c22550601fffa38c9204067296a51e1")
self.assertEqual(
data[103],
" :END:")
self.assertEqual(
data[104],
"** <2012-01-06 Fri> Epiphany")
self.assertEqual(
data[105],
" :PROPERTIES:")
self.assertEqual(
data[106],
" :ID: 699f5d8d424735f5593e1d1d44604f529c4fdbb3")
self.assertEqual(
data[107],
" :END:")
self.assertEqual(
data[108],
"** <2011-01-06 Thu> Epiphany")
self.assertEqual(
data[109],
" :PROPERTIES:")
self.assertEqual(
data[110],
" :ID: d48ee26b995cb0c2033077c99788ec6cca5afb66")
self.assertEqual(
data[111],
" :END:")
self.assertEqual(
data[112],
"** <2012-04-09 Mon> Easter Monday")
self.assertEqual(
data[113],
" :PROPERTIES:")
self.assertEqual(
data[114],
" :ID: c69c15ca890a76c6c982f7a998ae4c9ce79ddd45")
self.assertEqual(
data[115],
" :END:")
self.assertEqual(
data[116],
"** <2012-04-08 Sun> Easter")
self.assertEqual(
data[117],
" :PROPERTIES:")
self.assertEqual(
data[118],
" :ID: f0d2b4a8dbcca5208b2aab6755e8cd7c1efe18e5")
self.assertEqual(
data[119],
" :END:")
self.assertEqual(
data[120],
"** <2012-06-07 Thu> Corpus Christi")
self.assertEqual(
data[121],
" :PROPERTIES:")
self.assertEqual(
data[122],
" :ID: 32e659d60f167f7386c8269644c9c920614ce55d")
self.assertEqual(
data[123],
" :END:")
self.assertEqual(
data[124],
"** <2011-12-24 Sat> Christmas Eve")
self.assertEqual(
data[125],
" :PROPERTIES:")
self.assertEqual(
data[126],
" :ID: 949f24fdaa8122916bad02b3548e402b2d2391e7")
self.assertEqual(
data[127],
" :END:")
self.assertEqual(
data[128],
"** <2010-12-24 Fri> Christmas Eve")
self.assertEqual(
data[129],
" :PROPERTIES:")
self.assertEqual(
data[130],
" :ID: 96dfd09ae391c0a4e1ecd00ffbc875e714dcf9c6")
self.assertEqual(
data[131],
" :END:")
self.assertEqual(
data[132],
"** <2012-12-24 Mon> Christmas Eve")
self.assertEqual(
data[133],
" :PROPERTIES:")
self.assertEqual(
data[134],
" :ID: 554ab6eebf09552bccc3264f46000f98a3812ab0")
self.assertEqual(
data[135],
" :END:")
self.assertEqual(
data[136],
"** <2010-12-25 Sat> Christmas")
self.assertEqual(
data[137],
" :PROPERTIES:")
self.assertEqual(
data[138],
" :ID: 9047b4007e15ff0250613e25650aadb1be5ff8a7")
self.assertEqual(
data[139],
" :END:")
self.assertEqual(
data[140],
"** <2011-12-25 Sun> Christmas")
self.assertEqual(
data[141],
" :PROPERTIES:")
self.assertEqual(
data[142],
" :ID: a4e7890b6ce1602706a74fff5a0fc067492dc586")
self.assertEqual(
data[143],
" :END:")
self.assertEqual(
data[144],
"** <2012-12-25 Tue> Christmas")
self.assertEqual(
data[145],
" :PROPERTIES:")
self.assertEqual(
data[146],
" :ID: 6eee35b32d3d3e172e14528e32c02e7bae48e3fc")
self.assertEqual(
data[147],
" :END:")
self.assertEqual(
data[148],
"** <2010-08-15 Sun> Assumption")
self.assertEqual(
data[149],
" :PROPERTIES:")
self.assertEqual(
data[150],
" :ID: be5c5c89e8e8f98ada9548422b3707fff9d41512")
self.assertEqual(
data[151],
" :END:")
self.assertEqual(
data[152],
"** <2012-08-15 Wed> Assumption")
self.assertEqual(
data[153],
" :PROPERTIES:")
self.assertEqual(
data[154],
" :ID: 71156b8c067eabdea667f8696395011414ab967c")
self.assertEqual(
data[155],
" :END:")
self.assertEqual(
data[156],
"** <2011-08-15 Mon> Assumption")
self.assertEqual(
data[157],
" :PROPERTIES:")
self.assertEqual(
data[158],
" :ID: aaf4f5c9ff6a712b701539baa69d3afede23012c")
self.assertEqual(
data[159],
" :END:")
self.assertEqual(
data[160],
"** <2012-05-17 Thu> Ascension Day")
self.assertEqual(
data[161],
" :PROPERTIES:")
self.assertEqual(
data[162],
" :ID: e219abf88617f8796c9fba500e3bb9b829dac14a")
self.assertEqual(
data[163],
" :END:")
self.assertEqual(
data[164],
"** <2011-11-02 Wed> All Souls' Day")
self.assertEqual(
data[165],
" :PROPERTIES:")
self.assertEqual(
data[166],
" :ID: 1dd09748419fc6f7eee66184febf879f6323a2d5")
self.assertEqual(
data[167],
" :END:")
self.assertEqual(
data[168],
"** <2010-11-02 Tue> All Souls' Day")
self.assertEqual(
data[169],
" :PROPERTIES:")
self.assertEqual(
data[170],
" :ID: c7559b4e0501b55eecce604b3939e34683a60fb8")
self.assertEqual(
data[171],
" :END:")
self.assertEqual(
data[172],
"** <2012-11-02 Fri> All Souls' Day")
self.assertEqual(
data[173],
" :PROPERTIES:")
self.assertEqual(
data[174],
" :ID: 581e71732c88e6225a282be86e284002ddd23b97")
self.assertEqual(
data[175],
" :END:")
self.assertEqual(
data[176],
"** <2010-11-01 Mon> All Saints' Day")
self.assertEqual(
data[177],
" :PROPERTIES:")
self.assertEqual(
data[178],
" :ID: 69e6dffd28ba8b5f396fb9ceecf115d0f08a6369")
self.assertEqual(
data[179],
" :END:")
self.assertEqual(
data[180],
"** <2012-11-01 Thu> All Saints' Day")
self.assertEqual(
data[181],
" :PROPERTIES:")
self.assertEqual(
data[182],
" :ID: 554ed843558464e3867d3154d88541a953f23708")
self.assertEqual(
data[183],
" :END:")
self.assertEqual(
data[184],
"** <2011-11-01 Tue> All Saints' Day")
self.assertEqual(
data[185],
" :PROPERTIES:")
self.assertEqual(
data[186],
" :ID: aa06dce749fe46fabe338df8bee04ecdfa0b120a")
self.assertEqual(
data[187],
" :END:")
self.assertEqual(
data[188:194], ['** <2011-08-22 Mon 16:10>--<9999-12-31 Fri> No end time/date',
' :PROPERTIES:',
' :DESCRIPTION: No end time/date',
' :ID: 23c8b62cf2043b91627ffb832fa565fc125f95a3',
' :END:'])
def __build_ical_str(self, dtstart, dtend, extra):
if dtend:
dtend = "DTEND" + dtend + "\n"
return ("BEGIN:VCALENDAR\n"
"VERSION:2.0\n"
"PRODID:manual\n"
+ (extra or "") +
"BEGIN:VEVENT\n"
"CLASS:PUBLIC\n"
"DTSTART" + dtstart + "\n"
+ (dtend or "") +
"UID:whatever.ics\n"
"DTSTAMP:20190127T140400\n"
"DESCRIPTION:whatever\n"
"SUMMARY:whatever\n"
"END:VEVENT\n"
"END:VCALENDAR\n")
# Several variations need to be tested here:
#
# - DATE-TIME:
# - [1] UTC
# - [2] VTIMEZONE-specifed
# - [3] Inline (IANA-style, w/o VTIMEZONE)*
# - Floating:
# - [4] Basic case (truly floating)
# - [5] w/ X-WR-TIMEZONE*
# - [6] No end DATE-TIME
# - DATE:
# - [7] Basic case (differing dates)
# - [8] One-day, all-day event (collapsed to single org timestamp)
# - [9] No end DATE
#
# * = not included in RFC5545, but commonly in use.
def test_date_handling(self):
os.environ['TZ'] = "America/Chicago"
time.tzset()
VTIMEZONE_COMPONENT = ("BEGIN:VTIMEZONE\n"
"TZID:My/Berlin\n"
"TZURL:http://tzurl.org/zoneinfo-outlook/Europe/Berlin\n"
"X-LIC-LOCATION:Europe/Berlin\n"
"BEGIN:DAYLIGHT\n"
"TZOFFSETFROM:+0100\n"
"TZOFFSETTO:+0200\n"
"TZNAME:CEST\n"
"DTSTART:19700329T020000\n"
"RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\n"
"END:DAYLIGHT\n"
"BEGIN:STANDARD\n"
"TZOFFSETFROM:+0200\n"
"TZOFFSETTO:+0100\n"
"TZNAME:CET\n"
"DTSTART:19701025T030000\n"
"RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\n"
"END:STANDARD\n"
"END:VTIMEZONE\n")
cases = [(':20181103T201500Z', ':20181103T211500Z', None, '<2018-11-03 Sat 15:15>--<2018-11-03 Sat 16:15>'), # [1]
(':20181103T201500Z', ':20181103T201500Z', None, '<2018-11-03 Sat 15:15>--<2018-11-03 Sat 15:15>'), # [1] (no collapse)
(';TZID=My/Berlin:20181103T201500', ';TZID=My/Berlin:20181103T211500', VTIMEZONE_COMPONENT, '<2018-11-03 Sat 14:15>--<2018-11-03 Sat 15:15>'), # [2]
(';TZID=Europe/Berlin:20181103T201500:', ';TZID=Europe/Berlin:20181103T211500', None, '<2018-11-03 Sat 14:15>--<2018-11-03 Sat 15:15>'), # [3]
(';TZID=Europe/Berlin:20181103T201500', ';TZID=Europe/Berlin:20181103T211500', 'X-WR-TIMEZONE:America/Denver\n', '<2018-11-03 Sat 14:15>--<2018-11-03 Sat 15:15>'), # [3] (X-WR-TIMEZONE ignored)
(':20181103T201500', ':20181103T211500', None, '<2018-11-03 Sat 20:15>--<2018-11-03 Sat 21:15>'), # [4]
(':20181103T201500', ':20181103T211500', 'X-WR-TIMEZONE:Europe/Berlin\n', '<2018-11-03 Sat 14:15>--<2018-11-03 Sat 15:15>'), # [5]
(':20181103T201500', None, 'X-WR-TIMEZONE:Europe/Berlin\n', '<2018-11-03 Sat 14:15>--<9999-12-31 Fri>'), # [6]
(':20210201', ':20210204', None, '<2021-02-01 Mon>--<2021-02-03 Wed>'), # [7]
(':20210201', ':20210204', 'X-WR-TIMEZONE:Europe/Berlin\n', '<2021-02-01 Mon>--<2021-02-03 Wed>'), # [7] (X-WR-TIMEZONE ignored)
(':20210201', ':20210202', 'X-WR-TIMEZONE:Europe/Berlin\n', '<2021-02-01 Mon>'), # [8]
(':20210201', None, 'X-WR-TIMEZONE:Europe/Berlin\n', '<2021-02-01 Mon>--<9999-12-31 Fri>')] # [9]
for (dtstart, dtend, extra, output) in cases:
with tempfile.NamedTemporaryFile("wt") as tmp:
tmp.write(self.__build_ical_str(dtstart, dtend, extra))
tmp.seek(0)
print("+++ Testing: " + dtstart + " / " + str(dtend) + " / " + str(extra)[:10] + " +++")
argv = "-s -cf " + tmp.name
memacs = CalendarMemacs(argv=argv.split())
data = memacs.test_get_entries()
m = re.search("<.*>", data[0]).group(0)
self.assertEqual(output, m)
| 23,666
|
Python
|
.py
| 664
| 23.11747
| 213
| 0.447775
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,812
|
svn_test.py
|
novoid_Memacs/memacs/tests/svn_test.py
|
# -*- coding: utf-8 -*-
# Time-stamp: <2018-08-26 21:40:32 vk>
import os
import unittest
from memacs.svn import SvnMemacs
class TestSvnMemacs(unittest.TestCase):
def setUp(self):
test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'data', 'svn-log-xml.txt'
)
argv = "-s -f " + test_file
memacs = SvnMemacs(argv=argv.split())
self.data = memacs.test_get_entries()
def test_from_file(self):
data = self.data
# omit the hours when comparing the results since this is depending on the locales:
self.assertTrue(
data[0].startswith('** <2011-10-27 Thu ')
)
self.assertTrue(
data[0].endswith(':50> group-5 (r5): finished ?')
)
self.assertEqual(
data[1],
" :PROPERTIES:")
self.assertEqual(
data[2],
" :REVISION: 5")
self.assertEqual(
data[3],
" :ID: 819908c0cedb0098bf5dd96aa0d213598da45614")
self.assertEqual(
data[4],
" :END:")
# omit the hours when comparing the results since this is depending on the locales:
self.assertTrue(
data[5].startswith('** <2011-10-27 Thu ')
)
self.assertTrue(
data[5].endswith(':18> group-5 (r4): finished 5,')
)
self.assertEqual(
data[6],
" :PROPERTIES:")
self.assertEqual(
data[7],
" :REVISION: 4")
self.assertEqual(
data[8],
" :ID: 629716ff44b206745fdc34c910fe8b0f3d877f85")
self.assertEqual(
data[9],
" :END:")
self.assertEqual(
data[10],
" added package to assignment1.tex for landscaping (see 5.tex)")
# omit the hours when comparing the results since this is depending on the locales:
self.assertTrue(
data[11].startswith('** <2011-10-27 Thu ')
)
self.assertTrue(
data[11].endswith(':38> group-5 (r3): 5b.')
)
self.assertEqual(
data[12],
" :PROPERTIES:")
self.assertEqual(
data[13],
" :REVISION: 3")
self.assertEqual(
data[14],
" :ID: cf204bc9b36ba085275e03b7316ac34a496daf78")
self.assertEqual(
data[15],
" :END:")
# omit the hours when comparing the results since this is depending on the locales:
self.assertTrue(
data[16].startswith('** <2011-10-27 Thu ')
)
self.assertTrue(
data[16].endswith(':41> group-5 (r2): 5.tex')
)
self.assertEqual(
data[17],
" :PROPERTIES:")
self.assertEqual(
data[18],
" :REVISION: 2")
self.assertEqual(
data[19],
" :ID: f45be418de175ccf56e960a6941c9973094ab9e3")
self.assertEqual(
data[20],
" :END:")
# omit the hours when comparing the results since this is depending on the locales:
self.assertTrue(
data[21].startswith('** <2011-10-27 Thu ')
)
self.assertTrue(
data[21].endswith(':44> group-5 (r1): initial files')
)
self.assertEqual(
data[22],
" :PROPERTIES:")
self.assertEqual(
data[23],
" :REVISION: 1")
self.assertEqual(
data[24],
" :ID: 9b7d570e2dc4fb3a009461714358c35cbe24a8fd")
self.assertEqual(
data[25],
" :END:")
| 3,840
|
Python
|
.py
| 114
| 22.675439
| 91
| 0.5
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,813
|
gpx_test.py
|
novoid_Memacs/memacs/tests/gpx_test.py
|
# -*- coding: utf-8 -*-
import os
import unittest
from memacs.gpx import GPX
class TestGPX(unittest.TestCase):
def test_google(self):
sample = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'sample.gpx'
)
argv = []
argv.append('-f')
argv.append(sample)
memacs = GPX(argv=argv)
try:
data = memacs.test_get_entries()
# both addresses are reasonable for the given coordinates and
# OSM seems to return the second one at 2018-08-25 while the
# first one was true when the original author developed this
# test:
self.assertTrue(
data[0] in ['** <2017-04-01 Sat 10:50> Eggenberger Allee 9, 8020 Graz, Austria :network:',
'** <2017-04-01 Sat 10:50> Alte Poststraße 150, 8020 Graz, Austria :network:'])
self.assertEqual(
data[1],
" :PROPERTIES:")
self.assertEqual(
data[2],
" :LATITUDE: 47.0693")
self.assertEqual(
data[3],
" :LONGITUDE: 15.4076001")
self.assertEqual(
data[4],
" :ID: c2dc4f2289d79cff4cf27faa95863f8cb5b8cb21")
self.assertEqual(
data[5],
" :END:")
except RuntimeError as e:
print('skipped test_google because of {}'.format(e))
def test_osm(self):
sample = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'sample.gpx'
)
argv = []
argv.append('-f')
argv.append(sample)
argv.append('-p osm')
memacs = GPX(argv=argv)
data = memacs.test_get_entries()
# both addresses are reasonable for the given coordinates and
# OSM seems to return the second one at 2018-08-25 while the
# first one was true when the original author developed this
# test:
self.assertTrue(
data[0] in ['** <2017-04-01 Sat 10:50> FH Joanneum - Prüffeld, 150, Alte Poststraße, Gries, Graz, Steiermark, 8020, Österreich :network:',
'** <2017-04-01 Sat 10:50> FH Joanneum, 13, Eggenberger Allee, Eggenberg, Graz, Steiermark, 8020, Österreich :network:'])
self.assertEqual(
data[1],
" :PROPERTIES:")
self.assertEqual(
data[2],
" :LATITUDE: 47.0693")
self.assertEqual(
data[3],
" :LONGITUDE: 15.4076001")
self.assertEqual(
data[4],
" :ID: c2dc4f2289d79cff4cf27faa95863f8cb5b8cb21")
self.assertEqual(
data[5],
" :END:")
| 2,827
|
Python
|
.py
| 71
| 28.098592
| 150
| 0.53012
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,814
|
memacs-mbox.py
|
novoid_Memacs/tmp/emails/mbox/works-for-me-hack/memacs-mbox.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import re
import time
import logging
from optparse import OptionParser
# TODO:
# - add command line argument to define link name to real content
# currently: "file:INPUTFILE::ID" is used
# desired: "mylinkname:INPUTFILE::ID" should be used
# additional: add explanation to readme (setq org-link-abbrev-alist)
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2011-09-16"
INVOCATION_TIME = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
# better performance if pre-compiled:
SUBJECT_REGEX = re.compile("Subject: (.*)")
FROM_REGEX = re.compile("From: (.*) <(.*)>")
NEWSGROUPS_REGEX = re.compile("Newsgroups: (.*)")
MESSAGEID_REGEX = re.compile("Message-I(d|D): (.*)")
HEADERSTART_REGEX = re.compile("From (.*) (Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (([12]\d)|( 1| 2| 3| 4| 5| 5| 6| 7| 8| 9|30|31)) (([01]\d)|(20|21|22|23)):([012345]\d):([012345]\d) ([12]\d{3})")
# group 1: email: foo@gmx.at
# group 2: day: Fri
# group 3: month: May
# group 4: day: " 7"
# group 5: -
# group 6: day: " 7"
# group 7: hour: 13
# group 8: hour: 13
# group 9: -
# group 10: minutes: 54
# group 11: seconds: 15
# group 12: year: 2010
# From foo@gmx.at Fri May 7 13:54:15 2010
# From foo@bar-Voit.at Wed May 19 09:58:08 2010
# From foo@gmx.at Tue May 18 12:03:01 2010
# From foo@htu.tugraz.at Thu May 6 08:16:54 2010
# From foo@student.tugraz.at Fri May 21 16:01:09 2010
# From foo@bank.at Wed May 5 20:15:27 2010
# dd = " 1"..31: (([12]\d)|( 1| 2| 3| 4| 5| 5| 6| 7| 8| 9|30|31))
# hh = 01..24: (([01]\d)|(20|21|22|23))
# mm = 00..59: ([012345]\d)
# ss = 00..59: ([012345]\d)
# yyyy = 1000...2999: ([12]\d{3})
USAGE = "\n\
"+sys.argv[0]+"\n\
\n\
This script parses mbox files (or newsgroup postings) and generates \n\
an Org-mode file whose entry lines show the emails in Org-mode agenda.\n\
\n\
Usage: "+sys.argv[0]+" <options>\n\
\n\
Example:\n\
## simple example converting one mbox file:\n\
"+sys.argv[0]+" -f ~/mails/business.mbox -o mails.org_archive\n\
\n\
## more advanced example with multiple files at once:\n\
for myfile in ~/mails/*mbox\n\
do "+sys.argv[0]+" -f \"${myfile}\" >> mails.org_archive\n\
done\n\
\n\
\n\
:copyright: (c) 2011 by Karl Voit <tools@Karl-Voit.at>\n\
:license: GPL v2 or any later version\n\
:bugreports: <tools@Karl-Voit.at>\n\
:version: "+PROG_VERSION_NUMBER+" from "+PROG_VERSION_DATE+"\n"
parser = OptionParser(usage=USAGE)
parser.add_option("-f", "--file", dest="mboxname",
help="a file that holds the emails in mbox format", metavar="FILE")
parser.add_option("-o", "--output", dest="outputfile",
help="Org-mode file that will be generated (see above)." +
" If no output file is given, result gets printed to stdout", metavar="FILE")
parser.add_option("-w", "--overwrite", dest="overwrite", action="store_true",
help="overwrite given output file without checking its existance")
parser.add_option("-n", "--newsgroup", dest="newsgroup", action="store_true",
help="mbox file contains newsgroup postings: ignore \"From:\", add \"Newsgroups:\"")
parser.add_option("--version", dest="version", action="store_true",
help="display version and exit")
parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
help="enable verbose mode")
(options, args) = parser.parse_args()
def handle_logging():
"""Log handling and configuration"""
if options.verbose:
FORMAT = "%(levelname)-8s %(asctime)-15s %(message)s"
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
else:
FORMAT = "%(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
def get_timestamp_from_components(components):
"""returns orgmode timestamp of regex components"""
# resetting contact dictionary
monthsdict = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05',
'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'}
# group 1: email: foo@gmx.at
# group 2: day: Fri
daystrid = 2
# group 3: month: May
monthid = 3
# group 4: day: " 7"
dayid = 4
# group 5: -
# group 6: day: " 7"
# group 7: hour: 13
hourid = 7
# group 8: hour: 13
# group 9: -
# group 10: minutes: 54
minuteid = 10
# group 11: seconds: 15
# group 12: year: 2010
yearid = 12
try:
string = "<" + components.group(yearid) + "-" + monthsdict[components.group(monthid)] + \
"-" + components.group(dayid).strip().zfill(2) + " " + components.group(daystrid) + \
" " + components.group(hourid) + ":" + components.group(minuteid) + ">"
except IndexError as e:
logging.error("Sorry, there were some problems parsing the timestamp of the current from line.")
string = "ERROR"
return string
def generate_output_line(timestamp, fromline, emailaddress, filename, messageid, subject):
"""generates an orgmode entry for an email"""
if fromline == "":
fromline = emailaddress
string = "** " + timestamp
if options.newsgroup:
string += " " + fromline + ": "
else:
string += " [[contact:" + fromline + "][" + fromline + "]]: "
string += "[[file:" + filename + "::" + messageid + "][" + subject + "]]"
return string
def parse_mbox(filename, outputfile):
"""parses an mbox and generates orgmode entries"""
basename = os.path.basename(filename).strip()
logging.debug("--------------------------------------------")
logging.debug("processing line \""+ filename + "\" with basename \"" + basename + "\"")
was_empty_line = True
is_header = False
last_firstline = "" # holds the "From .*" line which is the first line of a new email/posting
last_from = "" # holds real name for emails OR newsgroup name(s) for postings
last_email = ""
last_subject = ""
last_message_id = ""
last_orgmodetimestamp = ""
for line in open(filename, 'r', encoding='LATIN-1'): # my personal archive files seem to be encoded in LATIN-1. FIXXME: proper error handling with detecting encoding
line = line.strip()
if was_empty_line:
# logging.debug("was_empty_line is True")
fromlinecomponents = HEADERSTART_REGEX.match(line)
if is_header:
logging.debug("parsing header line: " + line)
# logging.debug("is_header is True")
subjectcomponents = SUBJECT_REGEX.match(line)
if options.newsgroup:
fromcomponents = NEWSGROUPS_REGEX.match(line)
else:
fromcomponents = FROM_REGEX.match(line)
messageidcomponents = MESSAGEID_REGEX.match(line)
if not is_header and was_empty_line and fromlinecomponents:
logging.debug("new header: " + line)
# here the beginning of a new email header is assumed when an empty line
# is followed by a line that matches HEADERSTART_REGEX
is_header = True
last_email = fromlinecomponents.group(1)
last_firstline = line
last_from = ""
last_subject = ""
last_message_id = ""
subjectcomponents = None
messageidcomponents = None
last_orgmodetimestamp = get_timestamp_from_components(fromlinecomponents)
logging.debug("new email: " + last_email + " ... at " + last_orgmodetimestamp)
elif is_header and subjectcomponents:
last_subject = subjectcomponents.group(1).replace('[', '|').replace("]", "|")
logging.debug("subject: " + last_subject)
elif is_header and fromcomponents:
last_from = fromcomponents.group(1).replace('"', '').replace("'", "")
logging.debug("from: " + last_from)
elif is_header and messageidcomponents:
last_message_id = messageidcomponents.group(2).replace('<', '').replace(">", "")
if last_message_id == "":
logging.error("Sorry, this entry had no correct message-id and is not jumpable in Orgmode.")
logging.debug(last_message_id)
if is_header and last_orgmodetimestamp != "" and last_subject != "" and last_message_id != "":
logging.debug("entry written")
if outputfile:
outputfile.write(generate_output_line(last_orgmodetimestamp, last_from, last_email,
filename, last_message_id, last_subject))
if options.newsgroup:
outputfile.write('\n') # FIXXME: Sorry for this but there seems to be different behaviour when doing newsgroups
else:
print(generate_output_line(last_orgmodetimestamp, last_from, last_email,
filename, last_message_id, last_subject).strip())
is_header = False
if line == "":
was_empty_line = True
if is_header and last_message_id == "":
# recover if only message-id was not found:
# (some NNTP-clients do not generate those and let the NNTP-server do it)
last_message_id = last_firstline
logging.warn("Current entry does not provide a Message-ID, using first From-line instead: " + last_firstline)
elif is_header:
logging.error("Current entry was not recognized as an entry. Missing value(s)?")
if last_orgmodetimestamp:
logging.error(" timestamp: " + last_orgmodetimestamp)
else:
logging.error(" NO timestamp recognized!")
logging.error(" subject: " + last_subject)
logging.error(" message-id: " + last_message_id)
is_header = False
else:
was_empty_line = False
def main():
"""Main function"""
if options.version:
print(os.path.basename(sys.argv[0]) + " version "+PROG_VERSION_NUMBER+" from "+PROG_VERSION_DATE)
sys.exit(0)
handle_logging()
if not options.mboxname:
parser.error("Please provide an input file!")
if not os.path.isfile(options.mboxname):
print(USAGE)
logging.error("\n\nThe argument interpreted as an input file \"" + str(options.mboxname) + \
"\" is not an normal file!\n")
sys.exit(2)
if not options.overwrite and options.outputfile and os.path.isfile(options.outputfile):
print(USAGE)
logging.error("\n\nThe argument interpreted as output file \"" + str(options.outputfile) + \
"\" already exists!\n")
sys.exit(3)
string = "## this file is generated by " + sys.argv[0] + \
". Any modifications will be overwritten upon next invocation!\n"
if options.newsgroup:
string += "* Memacs module for newsgroup postings: " + options.mboxname + " :Memacs:news:"
else:
string += "* Memacs module for mbox emails: " + options.mboxname + " :Memacs:mbox:email:"
if options.outputfile:
output = open(options.outputfile, 'w')
output.write(string + "\n")
else:
output = None
print(string)
parse_mbox(options.mboxname, output)
string = "* this mbox is successfully parsed by " + sys.argv[0] + " at " + INVOCATION_TIME + "."
if options.outputfile:
output.write(string + "\n")
output.close()
else:
print(string)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logging.info("Received KeyboardInterrupt")
# END OF FILE #################################################################
# end
| 12,230
|
Python
|
.py
| 257
| 38.719844
| 235
| 0.585998
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,815
|
memacs-filenametimestamps.py
|
novoid_Memacs/tmp/filenametimestamps/memacs-filenametimestamps.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import re
import time
import logging
from optparse import OptionParser
PROG_VERSION_NUMBER = "0.2"
PROG_VERSION_DATE = "2011-10-10"
INVOCATION_TIME = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
MATCHING_LEVEL = {'day': 1, 'minutes': 2, 'seconds': 3, 'notmatching': 4}
# better performance if pre-compiled:
TIMESTAMP_REGEX = re.compile("([12]\d{3})-([01]\d)-([0123]\d)T([012]\d).([012345]\d)(.([012345]\d))?")
DATESTAMP_REGEX = re.compile("([12]\d{3})-([01]\d)-([0123]\d)")
# RegEx matches more exactly:
# reason: avoid 2011-01-00 (day is zero) or month is >12, ...
# problem: mathing groups will change as well!
# also fix in: vktimestamp2filedate
# dd = 01..31: ( ([12]\d) | (01|02|03|04|05|05|06|07|08|09|30|31) )
# mm = 01..12: ( ([0]\d) | (10|11|12) )
# hh = 00..23: ( ([01]\d) | (20|21|22|23) )
USAGE = "\n\
"+sys.argv[0]+"\n\
\n\
This script parses a text file containing absolute paths to files\n\
with ISO datestamps and timestamps in their file names:\n\
\n\
Examples: \"2010-03-29T20.12 Divegraph.tiff\"\n\
\"2010-12-31T23.59_Cookie_recipies.pdf\"\n\
\"2011-08-29T08.23.59_test.pdf\"\n\
\n\
Then an Org-mode file is generated that contains links to the files.\n\
\n\
Usage: "+sys.argv[0]+" <options>\n\
\n\
Example:\n\
## generating a file containing all ISO timestamp filenames:\n\
find $HOME -name '[12][0-9][0-9][0-9]-[01][0-9]-[0123][0-9]*' \ \n\
-type f > $HOME/files.log\n\
## invoking this script:\n\
"+sys.argv[0]+" -f $HOME/files.log -o result.org\n\
\n\
\n\
:copyright: (c) 2011 by Karl Voit <tools@Karl-Voit.at>\n\
:license: GPL v2 or any later version\n\
:bugreports: <tools@Karl-Voit.at>\n\
:version: "+PROG_VERSION_NUMBER+" from "+PROG_VERSION_DATE+"\n"
parser = OptionParser(usage=USAGE)
parser.add_option("-f", "--filelist", dest="filelistname",
help="file that holds the list of files (see above)", metavar="FILE")
parser.add_option("-o", "--output", dest="outputfile",
help="Org-mode file that will be generated (see above)", metavar="FILE")
parser.add_option("-w", "--overwrite", dest="overwrite", action="store_true",
help="overwrite given output file without checking its existance")
parser.add_option("--version", dest="version", action="store_true",
help="display version and exit")
parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
help="enable verbose mode")
(options, args) = parser.parse_args()
# if we found a timestamp too, take hours,minutes and optionally seconds from this timestamp
def handle_logging():
"""Log handling and configuration"""
if options.verbose:
FORMAT = "%(levelname)-8s %(asctime)-15s %(message)s"
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
else:
FORMAT = "%(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
def get_timestamp_from_file(filename):
"""returns mtime of file"""
return time.localtime(os.path.getmtime(filename))
def check_if_days_in_timestamps_are_same(filename, basename, filenamedatestampcomponents):
"""handles timestamp differences for timestamps containing only day information (and not times)"""
filetimestamp = get_timestamp_from_file(filename)[0:3]
logging.debug("filetimestamp " + str(filetimestamp))
filenamedatestampcomponentslist = [int(x) for x in filenamedatestampcomponents.groups()] # converts strings to integers
filenamedatestampcomponentslist = list(filenamedatestampcomponentslist) # converts tuple to list
logging.debug("filenamedatestampcomponentslist " + str(filenamedatestampcomponentslist))
# logging.debug( "filenamedatestampcomponentslist[0] " + str( filenamedatestampcomponentslist[0] ))
if filenamedatestampcomponentslist[0] == filetimestamp[0] and \
filenamedatestampcomponentslist[1] == filetimestamp[1] and \
filenamedatestampcomponentslist[2] == filetimestamp[2]:
logging.debug("matches only date YYYY-MM-DD")
return True
else:
logging.debug("filetimestamp and filename differs: " + filename)
return False
def generate_orgmode_file_timestamp(filename):
"""generates string for a file containing ISO timestamp in Org-mode"""
# Org-mode timestamp: <2011-07-16 Sat 9:00>
# also working in Org-mode agenda: <2011-07-16 9:00>
basename = os.path.basename(filename)
timestampcomponents = TIMESTAMP_REGEX.match(basename)
# "2010-06-12T13.08.42_test..." -> ('2010', '06', '12', '13', '08', '.42', '42')
# filenametimestampcomponents.group(1) -> '2010'
datestampcomponents = DATESTAMP_REGEX.match(basename)
if timestampcomponents:
datestamp = "<" + str(timestampcomponents.group(1)) + "-" + str(timestampcomponents.group(2)) + "-" + str(timestampcomponents.group(3)) + \
" " + str(timestampcomponents.group(4)) + ":" + str(timestampcomponents.group(5)) + ">"
logging.debug("datestamp (time): " + datestamp)
return "** " + datestamp + " [[file:" + filename + "][" + basename + "]]\n"
elif datestampcomponents:
if check_if_days_in_timestamps_are_same(filename, basename, datestampcomponents):
logging.debug("day of timestamps is different, have to assume time")
assumedtime = "" # no special time assumed; file gets shown as time-independent
# assumedtime = " 12:00" ## files with no special time gets shown at noon
datestamp = "<" + str(datestampcomponents.group(1)) + "-" + str(datestampcomponents.group(2)) + \
"-" + str(datestampcomponents.group(3)) + assumedtime + ">"
logging.debug("datestamp (day): " + datestamp)
return "** " + datestamp + " [[file:" + filename + "][" + basename + "]]\n"
else:
logging.debug("day of timestamps is same, can use file time")
filetimestampcomponents = get_timestamp_from_file(filename)
timestamp = str(filetimestampcomponents[3]).zfill(2) + ":" + str(filetimestampcomponents[4]).zfill(2)
datestamp = "<" + str(datestampcomponents.group(1)) + "-" + str(datestampcomponents.group(2)) + \
"-" + str(datestampcomponents.group(3)) + " " + str(timestamp) + ">"
logging.debug("datestamp (day): " + datestamp)
return "** " + datestamp + " [[file:" + filename + "][" + basename + "]]\n"
else:
logging.warning("FIXXME: this point should never be reached. not recognizing datestamp or timestamp")
return False
def handle_filelist_line(line, output):
"""handles one line of the list of files to check"""
filename = line.strip()
basename = os.path.basename(line).strip()
logging.debug("--------------------------------------------")
logging.debug("processing line \"" + filename + "\" with basename \"" + basename + "\"")
if filename == "":
logging.debug("ignoring empty line")
elif not os.path.isfile(filename):
logging.warn("ignoring \"" + filename + "\" because it is no file")
elif TIMESTAMP_REGEX.match(basename) or DATESTAMP_REGEX.match(basename):
output.write(generate_orgmode_file_timestamp(filename))
else:
logging.warn("ignoring \"" + filename + "\" because its file name does not match ISO date YYYY-MM-DDThh.mm(.ss)")
def main():
"""Main function"""
if options.version:
print(os.path.basename(sys.argv[0]) + " version "+PROG_VERSION_NUMBER+" from "+PROG_VERSION_DATE)
sys.exit(0)
handle_logging()
if not options.filelistname:
parser.error("Please provide an input file!")
if not options.outputfile:
parser.error("Please provide an output file!")
if not os.path.isfile(options.filelistname):
print(USAGE)
logging.error("\n\nThe argument interpreted as an input file \"" + str(options.filelistname) + "\" is not an normal file!\n")
sys.exit(2)
if not options.overwrite and os.path.isfile(options.outputfile):
print(USAGE)
logging.error("\n\nThe argument interpreted as output file \"" + str(options.outputfile) + "\" already exists!\n")
sys.exit(3)
output = open(options.outputfile, 'w')
output.write("## this file is generated by " + sys.argv[0] + ". Any modifications will be overwritten upon next invocation!\n")
output.write("* Memacs file name datestamp :Memacs:filedatestamps:\n")
for line in open(options.filelistname, 'r'):
handle_filelist_line(line, output)
output.write("* this file is successfully generated by " + sys.argv[0] + " at " + INVOCATION_TIME + ".\n")
output.close()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logging.info("Received KeyboardInterrupt")
# END OF FILE #################################################################
# end
| 9,104
|
Python
|
.py
| 168
| 47.738095
| 147
| 0.645612
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,816
|
memacs-easybank.py
|
novoid_Memacs/tmp/bank_statements/easybank.at/memacs-easybank.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2020-03-24 21:54:58 vk>
import os
import sys
import re
import time
import logging
from optparse import OptionParser
import codecs ## for writing unicode file
import pdb
## TODO:
## * fix parts marked with «FIXXME»
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2011-10-09"
INVOCATION_TIME = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
## better performance if ReEx is pre-compiled:
## search for: «DD.MM.(.*)UM HH.MM»
TIMESTAMP_REGEX = re.compile(".*(([012]\d)|(30|31))\.((0\d)|(10|11|12))\..*UM ([012345]\d)\.([012345]\d).*")
## group 1: DD
TIMESTAMP_REGEX_DAYINDEX = 1 ## 2 is not always found
## group 2: DD
## group 3:
## group 4: MM
TIMESTAMP_REGEX_MONTHINDEX = 4 ## 5 is not always found
## group 5: MM
## group 6:
## group 7: HH
TIMESTAMP_REGEX_HOURINDEX = 7
## group 8: MM
TIMESTAMP_REGEX_MINUTEINDEX = 8
## group 9: nil
## search for: «DD.MM.YYYY»
DATESTAMP_REGEX = re.compile("([012345]\d)\.([012345]\d)\.([12]\d\d\d)")
DATESTAMP_REGEX_DAYINDEX = 1
DATESTAMP_REGEX_MONTHINDEX = 2
DATESTAMP_REGEX_YEARINDEX = 3
## search for: <numbers> <numbers> <nonnumbers>
BANKCODE_NAME_REGEX = re.compile("(\d\d\d\d+) (\d\d\d\d+) (.*)")
USAGE = "\n\
" + sys.argv[0] + "\n\
\n\
This script parses bank statements «Umsatzliste» of easybank.at and generates \n\
an Org-mode file whose entry lines show the transactions in Org-mode agenda.\n\
\n\
Usage: " + sys.argv[0] + " <options>\n\
\n\
Example:\n\
" + sys.argv[0] + " -f ~/bank/transactions.csv -o ~/org/bank.org_archive\n\
\n\
\n\
:copyright: (c) 2011 by Karl Voit <tools@Karl-Voit.at>\n\
:license: GPL v2 or any later version\n\
:bugreports: <tools@Karl-Voit.at>\n\
:version: "+PROG_VERSION_NUMBER+" from "+PROG_VERSION_DATE+"\n"
parser = OptionParser(usage=USAGE)
parser.add_option("-f", "--file", dest="csvfilename",
help="a file that holds the transactions in CSV format", metavar="FILE")
parser.add_option("-o", "--output", dest="outputfile",
help="Org-mode file that will be generated (see above)." +\
" If no output file is given, result gets printed to stdout", metavar="FILE")
parser.add_option("-w", "--overwrite", dest="overwrite", action="store_true",
help="overwrite given output file without checking its existance")
parser.add_option("--version", dest="version", action="store_true",
help="display version and exit")
parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
help="enable verbose mode")
(options, args) = parser.parse_args()
def handle_logging():
"""Log handling and configuration"""
if options.verbose:
FORMAT = "%(levelname)-8s %(asctime)-15s %(message)s"
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
else:
FORMAT = "%(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
def extract_datestamp_from_eventday(daystring):
"""extracts day, month, year from string like «DD.MM.YYYY»"""
components = DATESTAMP_REGEX.match(daystring)
if not components:
logging.error("ERROR: could not parse date field: [" + daystring + "]")
sys.exit(5)
return components.group(DATESTAMP_REGEX_DAYINDEX),\
components.group(DATESTAMP_REGEX_MONTHINDEX), \
components.group(DATESTAMP_REGEX_YEARINDEX)
def extract_timestamp_from_timestampcomponents(timestampparts):
"""extracts the components of a time stamp from the timestampcomponents"""
#logging.debug("found " + str(len(timestampparts.groups())) + " part(s) of timestamp within longdescription")
month = timestampparts.group(TIMESTAMP_REGEX_MONTHINDEX)
day = timestampparts.group(TIMESTAMP_REGEX_DAYINDEX)
hour = timestampparts.group(TIMESTAMP_REGEX_HOURINDEX)
minute = timestampparts.group(TIMESTAMP_REGEX_MINUTEINDEX)
logging.debug("extracted timestamp: MM:dd [%s.%s] hh:mm [%s:%s] " % ( month, day, hour, minute) )
return month, day, hour, minute
def generate_orgmodetimestamp(day, month, year, hour, minute):
"""generates <YYYY-MM-DD> or <YYYY-MM-DD HH:MM> from strings in arguments"""
if hour and minute:
timestring = " " + hour + ":" + minute
else:
timestring = ""
return "<" + year + "-" + month + "-" + day + timestring + ">"
def extract_known_datasets(name, shortdescription, longdescription, descriptionparts):
"""handle known entries in the CSV file"""
## Auszahlung Maestro MC/000002270|BANKOMAT 29511 KARTE1 18.04.UM 11.34
if descriptionparts[0].startswith('Auszahlung Maestro '):
logging.debug("found special case \"Auszahlung Maestro\"")
name = None
if len(descriptionparts)>1:
shortdescription = descriptionparts[1].split(" ")[:2] ## the 1st two words of the 2nd part
shortdescription = " ".join(shortdescription)
else:
logging.warning("could not find descriptionparts[1]; using " + \
"\"Auszahlung Maestro\" instead")
shortdescription = "Auszahlung Maestro"
logging.debug("shortdescr.=" + str(shortdescription))
## Bezahlung Maestro MC/000002281|2108 K1 01.05.UM 17.43|OEBB 2483 FSA\\Ebreich sdorf 2483
## Bezahlung Maestro MC/000002277|2108 K1 27.04.UM 17.10|OEBB 8020 FSA\\Graz 8020
## Bezahlung Maestro MC/000002276|WIENER LINIE 3001 K1 28.04.UM 19.05|WIENER LINIEN 3001 \
## Bezahlung Maestro MC/000002272|BRAUN 0001 K1 19.04.UM 23.21|BRAUN DE PRAUN \
## Bezahlung Maestro MC/000002308|BILLA DANKT 6558 K1 11.06.UM 10.21|BILLA 6558 \
## Bezahlung Maestro MC/000002337|AH10 K1 12.07.UM 11.46|Ecotec Computer Dat\\T imelkam 4850
elif descriptionparts[0].startswith('Bezahlung Maestro ') and len(descriptionparts)>2:
logging.debug("found special case \"Bezahlung Maestro\"")
shortdescription = descriptionparts[2].strip() ## the last part
name = None
## does not really work well with Unicode ... (yet)
##if shortdescription.startswith(u"OEBB"):
## logging.debug("found special case \"ÖBB Fahrscheinautomat\"")
## #shortdescription.replace("\\",' ')
## logging.debug("sd[2]: [" + descriptionparts[2].strip() + "]")
## re.sub(ur'OEBB (\d\d\d\d) FSA\\(.*)\s\s+(\\\d)?(\d\d+).*', ur'ÖBB Fahrschein \4 \2', descriptionparts[2].strip())
elif descriptionparts[0].startswith('easykreditkarte MasterCard '):
logging.debug("found special case \"easykreditkarte\"")
name = None
shortdescription = "MasterCard Abrechnung"
elif len(descriptionparts)>1 and descriptionparts[0].startswith('Gutschrift Überweisung ') and \
descriptionparts[1].startswith('TECHNISCHE UNIVERSITAET GRAZ '):
logging.debug("found special case \"Gutschrift Überweisung, TUG\"")
name = "TU Graz"
shortdescription = "Gehalt"
elif len(descriptionparts)>1 and descriptionparts[1] == 'Vergütung für Kontoführung':
logging.debug("found special case \"Vergütung für Kontoführung\"")
name = "easybank"
shortdescription = "Vergütung für Kontoführung"
elif len(descriptionparts)>1 and descriptionparts[1] == 'Entgelt für Kontoführung':
logging.debug("found special case \"Entgelt für Kontoführung\"")
name = "easybank"
shortdescription = "Entgelt für Kontoführung"
if name:
logging.debug("changed name to: " + name)
if shortdescription:
logging.debug("changed shortdescription to: " + shortdescription)
return name, shortdescription
def extract_name_and_shortdescription(longdescription):
"""
Heuristic extraction of any information useful as name or short description.
This is highly dependent on your personal account habit/data!
"""
name = shortdescription = None
## shortdescription is first part of longdescriptions before the first two spaces
shortdescription = longdescription[:longdescription.find(" ")]
if len(shortdescription) < len(longdescription) and len(shortdescription) > 0:
logging.debug(" extracted short description: [" + shortdescription + "]")
else:
shortdescription = None
descriptionparts = longdescription.split('|')
if len(descriptionparts) > 1:
logging.debug(" found " + str(len(descriptionparts)) + " part(s) within longdescription, looking for name ...")
bankcode_name = BANKCODE_NAME_REGEX.match(descriptionparts[1])
if bankcode_name:
name = bankcode_name.group(3)
logging.debug(" found bank code and name. name is: [" + name + "]")
## so far the general stuff; now for parsing some known lines optionally overwriting things:
name, shortdescription = extract_known_datasets(name, shortdescription, longdescription, descriptionparts)
return name, shortdescription
def generate_orgmodeentry(orgmodetimestamp, jumptarget, amount, currency, longdescription, shortdescription, name):
"""generates the string for the Org-mode file"""
## ** $timestamp $amount $currency, [[bank:$jumptarget][$description]]
## if shortdescription:
## ** $timestamp $amount $currency, [[bank:$jumptarget][$shortdescription]]
## if name:
## ** $timestamp $amount $currency, [[contact:$name][name]], [[bank:$jumptarget][$description]]
## if name and shortdescription:
## ** $timestamp $amount $currency, [[contact:$name][name]], [[bank:$jumptarget][$(short)description]]
if currency == "EUR":
currency = "€" # it's shorter :-)
entry = "** " + orgmodetimestamp + " " + amount + currency + ", "
if name and len(name)>0:
entry += "[[contact:" + name + "][" + name + "]], "
if shortdescription:
entry += "[[bank:" + jumptarget + "][" + shortdescription + "]]"
else:
entry += "[[bank:" + jumptarget + "][" + longdescription + "]]"
return entry
def parse_csvfile(filename, handler):
"""parses an csv file and generates orgmode entries"""
basename = os.path.basename(filename).strip()
logging.debug( "--------------------------------------------")
logging.debug("processing file \""+ filename + "\" with basename \""+ basename + "\"")
## please do *not* use csvreader here since it is not able to handle UTF-8/latin-1!
inputfile = codecs.open(filename, 'rb', 'latin-1')
for line in inputfile:
row = line.split(";")
logging.debug("--------------------------------------------------------")
logging.debug("processing row: " + str(str(row)) )
## direct data:
try:
longdescription = str(row[1])
amount = str(row[4])
currency = str(row[5]).strip()
jumptarget = str(row[2]) + ";" + str(row[3]) + ";" + str(row[4])
except UnicodeDecodeError as detail:
logging.error("Encoding error: ")
print(detail)
logging.error("corresponding line is: [" + str(str(row)) + "]")
sys.exit(4)
## derived data:
timestampparts = TIMESTAMP_REGEX.match(longdescription)
year = month = day = hour = minute = None
orgmodetimestamp = None
name = None ## optional
shortdescription = None ## optional
## one line contains following values separated by «;»
#logging.debug("account number: " + row[0] )
logging.debug("long description: [" + longdescription + "]" )
#logging.debug("day of clearing: " + row[2] )
logging.debug("day of event: " + row[3] )
logging.debug("amount: " + amount )
#logging.debug("currency: " + currency )
day, month, year = extract_datestamp_from_eventday(str(row[3]))
if timestampparts:
month, day, hour, minute = extract_timestamp_from_timestampcomponents(timestampparts)
orgmodetimestamp = generate_orgmodetimestamp(day, month, year, hour, minute)
name, shortdescription = extract_name_and_shortdescription(longdescription)
orgmodeentry = generate_orgmodeentry(orgmodetimestamp, jumptarget, amount, \
currency, longdescription, shortdescription, name)
write_output(handler, orgmodeentry)
def write_output(handler, string):
"""write to stdout or to outfile"""
if options.outputfile:
handler.write(str(string) + "\n")
else:
print(string)
def main():
"""Main function"""
if options.version:
print(os.path.basename(sys.argv[0]) + " version "+PROG_VERSION_NUMBER+" from "+PROG_VERSION_DATE)
sys.exit(0)
handle_logging()
if not options.csvfilename:
parser.error("Please provide an input file!")
if not os.path.isfile(options.csvfilename):
print(USAGE)
logging.error("\n\nThe argument interpreted as an input file \"" + str(options.csvfilename) + \
"\" is not an normal file!\n")
sys.exit(2)
if not options.overwrite and options.outputfile and os.path.isfile(options.outputfile):
print(USAGE)
logging.error("\n\nThe argument interpreted as output file \"" + str(options.outputfile) + \
"\" already exists!\n")
sys.exit(3)
if options.outputfile:
handler = codecs.open(options.outputfile, 'w', "utf-8")
write_output(handler, "## -*- coding: utf-8 -*-")
write_output(handler, "## this file is generated by " + sys.argv[0] + \
". Any modifications will be overwritten upon next invocation!")
write_output(handler, "## parameter input filename: " + options.csvfilename)
if options.outputfile:
write_output(handler, "## parameter output filename: " + options.outputfile)
else:
write_output(handler, "## parameter output filename: none, writing to stdout")
write_output(handler, "## invocation time: " + INVOCATION_TIME)
write_output(handler, "* bank transactions :Memacs:bank:")
parse_csvfile(options.csvfilename, handler)
write_output(handler, "* bank transcations above were successfully parsed by " + \
sys.argv[0] + " at " + INVOCATION_TIME + ".\n\n")
if options.outputfile:
handler.close()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logging.info("Received KeyboardInterrupt")
## END OF FILE #################################################################
#end
| 14,765
|
Python
|
.py
| 285
| 44.852632
| 127
| 0.640323
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,817
|
contactparser.py
|
novoid_Memacs/memacs/lib/contactparser.py
|
import logging
import re
from bbdb.database import BBDB
def sanitize_phonenumber(phonenumber):
"""
Convert phonenumber to digits only
"""
sanitized_phonenumber = phonenumber.strip().replace('-','').replace('/','').replace(' ','').replace('+','00')
return sanitized_phonenumber
def parse_org_contact_file(orgfile):
"""
Parses the given Org-mode file for contact entries.
The return format is a follows:
numbers = {'004369912345678':'First2 Last1', '0316987654':'First2 Last2', ...}
@param orgfile: file name of a Org-mode file to parse
@param return: list of dict-entries containing the numbers to name dict
"""
linenr = 0
## defining distinct parsing status states:
headersearch = 21
propertysearch = 42
inproperty = 73
status = headersearch
contacts = {}
current_name = ''
HEADER_REGEX = re.compile('^(\*+)\s+([^\s:]([^:]*)[^\s:])(\s+(:[^\s]+:)+)?')
PHONE = '\s+([\+\d\-/ ]{7,})$'
PHONE_REGEX = re.compile(':(PHONE|oldPHONE|MOBILE|oldMOBILE|HOMEPHONE|oldHOMEPHONE|WORKPHONE|oldWORKPHONE):' + PHONE)
for rawline in open(orgfile, 'r'):
line = rawline.strip() ## trailing and leading spaces are stupid
linenr += 1
header_components = re.match(HEADER_REGEX, line)
if header_components:
## in case of new header, make new currententry because previous one was not a contact header with a property
current_name = header_components.group(2)
status = propertysearch
continue
if status == headersearch:
## if there is something to do, it was done above when a new heading is found
continue
if status == propertysearch:
if line == ':PROPERTIES:':
status = inproperty
continue
elif status == inproperty:
phone_components = re.match(PHONE_REGEX, line)
if phone_components:
phonenumber = sanitize_phonenumber(phone_components.group(2))
contacts[phonenumber] = current_name
elif line == ':END:':
status = headersearch
continue
else:
## I must have mixed up status numbers or similar - should never be reached.
logging.error("Oops. Internal parser error: status \"%s\" unknown. The programmer is an idiot. Current contact entry might get lost due to recovering from that shock. (line number %s)" % (str(status), str(linenr)))
status = headersearch
continue
logging.info("found %s suitable contacts while parsing \"%s\"" % (str(len(contacts)), orgfile))
return contacts
def parse_bbdb_file(bbdbfile):
"""
Parses the given bbdb file for contact entries.
The return format is a follows:
numbers = {'004369912345678':'First2 Last1', '0316987654':'First2 Last2', ...}
@param bbdbfile: file name of a Org-mode file to parse
@param return: list of dict-entries containing the numbers to name dict
"""
contacts = {}
bb = BBDB.fromfile(bbdbfile)
bd = bb.model_dump()
records = bd["records"]
for record in records:
if len(record["phone"]) > 0:
current_name = f"{record['firstname']} {record['lastname']}"
for number in record["phone"]:
phonenumber = sanitize_phonenumber(record["phone"][number])
contacts[phonenumber] = current_name
logging.info("found %s suitable contacts while parsing \"%s\"" % (str(len(contacts)), bbdbfile))
return contacts
| 3,597
|
Python
|
.tac
| 79
| 37.278481
| 226
| 0.632846
|
novoid/Memacs
| 1,003
| 67
| 17
|
GPL-3.0
|
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
|
10,818
|
tagger.py.in
|
metabrainz_picard/tagger.py.in
|
#!/usr/bin/env python3
import os
import sys
sys.path.insert(0, '.')
# This is needed to find resources when using pyinstaller
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
basedir = getattr(sys, '_MEIPASS', '')
else:
basedir = os.path.dirname(os.path.abspath(__file__))
from picard import register_excepthook
register_excepthook()
from picard.tagger import main
main(os.path.join(basedir, 'locale'), %(autoupdate)s)
| 447
|
Python
|
.py
| 13
| 32.307692
| 62
| 0.742991
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,819
|
setup.py
|
metabrainz_picard/setup.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2011-2014, 2017 Lukáš Lalinský
# Copyright (C) 2007 Santiago M. Mola
# Copyright (C) 2008 Robert Kaye
# Copyright (C) 2008-2009, 2018-2024 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2011-2012, 2014, 2016-2018 Wieland Hoffmann
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2012, 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2013-2014 Johannes Dewender
# Copyright (C) 2013-2015, 2017-2020 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016-2017 Ville Skyttä
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2018 Abhinav Ohri
# Copyright (C) 2018 Kartik Ohri
# Copyright (C) 2018 virusMac
# Copyright (C) 2019 Kurt Mosiejczuk
# Copyright (C) 2020 Jason E. Hale
#
# This program is free software; you can redistribute it and/or
# modify 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.
import datetime
import glob
from io import StringIO
import logging as log
import os
import re
import stat
import sys
import tempfile
from setuptools import (
Command,
Extension,
setup,
)
from setuptools.command.install import install
from setuptools.dist import Distribution
try:
from setuptools.command.build import build
except ImportError:
from distutils.command.build import build
# required for PEP 517
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
from picard import ( # noqa: E402
PICARD_APP_ID,
PICARD_APP_NAME,
PICARD_DESKTOP_NAME,
PICARD_DISPLAY_NAME,
PICARD_VERSION,
PICARD_VERSION_STR_SHORT,
)
if sys.version_info < (3, 9):
sys.exit("ERROR: You need Python 3.9 or higher to use Picard.")
PACKAGE_NAME = "picard"
APPDATA_FILE = PICARD_APP_ID + '.appdata.xml'
APPDATA_FILE_TEMPLATE = APPDATA_FILE + '.in'
DESKTOP_FILE = PICARD_APP_ID + '.desktop'
DESKTOP_FILE_TEMPLATE = DESKTOP_FILE + '.in'
ext_modules = [
Extension('picard.util._astrcmp', sources=['picard/util/_astrcmp.c']),
]
def newer(source, target):
"""Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise FileNotFoundError if 'source' does not exist.
"""
if not os.path.exists(source):
raise FileNotFoundError('file "%s" does not exist' % os.path.abspath(source))
if not os.path.exists(target):
return True
return os.path.getmtime(source) > os.path.getmtime(target)
class picard_test(Command):
description = "run automated tests"
user_options = [
("tests=", None, "list of tests to run (default all)"),
("verbosity=", "v", "verbosity"),
]
def initialize_options(self):
self.tests = []
self.verbosity = 1
def finalize_options(self):
if self.tests:
self.tests = self.tests.split(",")
# In case the verbosity flag is used, verbosity is None
if not self.verbosity:
self.verbosity = 2
# Convert to appropriate verbosity if passed by --verbosity option
self.verbosity = int(self.verbosity)
def run(self):
import unittest
names = []
for filename in glob.glob("test/**/test_*.py", recursive=True):
modules = os.path.splitext(filename)[0].split(os.sep)
name = '.'.join(modules[1:])
if not self.tests or name in self.tests:
names.append('test.' + name)
tests = unittest.defaultTestLoader.loadTestsFromNames(names)
t = unittest.TextTestRunner(verbosity=self.verbosity)
testresult = t.run(tests)
if not testresult.wasSuccessful():
sys.exit("At least one test failed.")
class picard_build_locales(Command):
description = 'build locale files'
user_options = [
('build-dir=', 'd', "directory to build to"),
('inplace', 'i', "ignore build-lib and put compiled locales into the 'locale' directory"),
]
def initialize_options(self):
self.build_dir = None
self.inplace = 0
def finalize_options(self):
self.set_undefined_options('build', ('build_locales', 'build_dir'))
self.locales = self.distribution.locales
def run(self):
for domain, locale, po in self.locales:
if self.inplace:
path = os.path.join('locale', locale, 'LC_MESSAGES')
else:
path = os.path.join(self.build_dir, locale, 'LC_MESSAGES')
mo = os.path.join(path, '%s.mo' % domain)
self.mkpath(path)
self.spawn(['msgfmt', '-o', mo, po])
Distribution.locales = None
class picard_install_locales(Command):
description = "install locale files"
user_options = [
('install-dir=', 'd', "directory to install locale files to"),
('build-dir=', 'b', "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"),
('skip-build', None, "skip the build steps"),
]
boolean_options = ['force', 'skip-build']
def initialize_options(self):
self.install_dir = None
self.build_dir = None
self.force = 0
self.skip_build = None
self.outfiles = []
def finalize_options(self):
self.set_undefined_options('build', ('build_locales', 'build_dir'))
self.set_undefined_options('install',
('install_locales', 'install_dir'),
('force', 'force'),
('skip_build', 'skip_build'),
)
def run(self):
if not self.skip_build:
self.run_command('build_locales')
self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
def get_inputs(self):
return self.locales or []
def get_outputs(self):
return self.outfiles
class picard_install(install):
user_options = install.user_options + [
('install-locales=', None,
"installation directory for locales"),
('localedir=', None, ''),
('disable-autoupdate', None, 'disable update checking and hide settings for it'),
('disable-locales', None, ''),
]
sub_commands = install.sub_commands
def initialize_options(self):
install.initialize_options(self)
self.install_locales = None
self.localedir = None
self.disable_autoupdate = None
self.disable_locales = None
def finalize_options(self):
install.finalize_options(self)
if self.install_locales is None:
self.install_locales = os.path.join(self.install_data, 'share', 'locale')
if self.root and self.install_locales.startswith(self.root):
self.install_locales = self.install_locales[len(self.root):]
self.install_locales = os.path.normpath(self.install_locales)
self.localedir = self.install_locales
# can't use set_undefined_options :/
self.distribution.get_command_obj('build').localedir = self.localedir
self.distribution.get_command_obj('build').disable_autoupdate = self.disable_autoupdate
if self.root is not None:
self.change_roots('locales')
if self.disable_locales is None:
self.sub_commands.append(('install_locales', None))
def run(self):
install.run(self)
class picard_build(build):
user_options = build.user_options + [
('build-locales=', 'd', "build directory for locale files"),
('localedir=', None, ''),
('disable-autoupdate', None, 'disable update checking and hide settings for it'),
('disable-locales', None, ''),
('build-number=', None, 'build number (integer)'),
]
def initialize_options(self):
super().initialize_options()
self.build_number = 0
self.build_locales = None
self.localedir = None
self.disable_autoupdate = None
self.disable_locales = None
def finalize_options(self):
super().finalize_options()
try:
self.build_number = int(self.build_number)
except ValueError:
self.build_number = 0
if self.build_locales is None:
self.build_locales = os.path.join(self.build_base, 'locale')
if self.localedir is None:
self.localedir = '/usr/share/locale'
if self.disable_autoupdate is None:
self.disable_autoupdate = False
if self.disable_locales is None:
self.sub_commands.append(('build_locales', None))
def run(self):
params = {'localedir': self.localedir, 'autoupdate': not self.disable_autoupdate}
generate_file('tagger.py.in', 'tagger.py', params)
make_executable('tagger.py')
generate_file('scripts/picard.in', 'scripts/' + PACKAGE_NAME, params)
if sys.platform == 'win32':
file_version = PICARD_VERSION[0:3] + (self.build_number,)
file_version_str = '.'.join(str(v) for v in file_version)
installer_args = {
'display-name': PICARD_DISPLAY_NAME,
'file-version': file_version_str,
}
if os.path.isfile('installer/picard-setup.nsi.in'):
generate_file('installer/picard-setup.nsi.in', 'installer/picard-setup.nsi', {**args, **installer_args})
log.info('generating NSIS translation files')
self.spawn(['python', 'installer/i18n/json2nsh.py'])
version_args = {
'filevers': str(file_version),
'prodvers': str(file_version),
}
generate_file('win-version-info.txt.in', 'win-version-info.txt', {**args, **version_args})
default_publisher = 'CN=Metabrainz Foundation Inc., O=Metabrainz Foundation Inc., L=San Luis Obispo, S=California, C=US'
# Combine patch version with build number. As Windows store apps require continuously
# growing version numbers we combine the patch version with a build number set by the
# build script.
store_version = (PICARD_VERSION.major, PICARD_VERSION.minor, PICARD_VERSION.patch * 1000 + min(self.build_number, 999), 0)
generate_file('appxmanifest.xml.in', 'appxmanifest.xml', {
'app-id': "MetaBrainzFoundationInc." + PICARD_APP_ID,
'display-name': PICARD_DISPLAY_NAME,
'short-name': PICARD_APP_NAME,
'publisher': os.environ.get('PICARD_APPX_PUBLISHER', default_publisher),
'version': '.'.join(str(v) for v in store_version),
})
elif sys.platform not in {'darwin', 'haiku1', 'win32'}:
self.run_command('build_appdata')
self.run_command('build_desktop_file')
super().run()
def py_from_ui(uifile):
return "ui_%s.py" % os.path.splitext(os.path.basename(uifile))[0]
def py_from_ui_with_defaultdir(uifile):
return os.path.join('picard', 'ui', 'forms', py_from_ui(uifile))
def ui_files():
for uifile in glob.glob("ui/*.ui"):
yield (uifile, py_from_ui_with_defaultdir(uifile))
class picard_build_ui(Command):
description = "build Qt UI files and resources"
user_options = [
("files=", None, "comma-separated list of files to rebuild"),
]
def initialize_options(self):
self.files = []
def finalize_options(self):
if self.files:
files = []
for f in self.files.split(","):
head, tail = os.path.split(f)
m = re.match(r'(?:ui_)?([^.]+)', tail)
if m:
name = m.group(1)
else:
log.warn('ignoring %r (cannot extract base name)', f)
continue
uiname = name + '.ui'
uifile = os.path.join(head, uiname)
if os.path.isfile(uifile):
pyfile = os.path.join(os.path.dirname(uifile),
py_from_ui(uifile))
files.append((uifile, pyfile))
else:
uifile = os.path.join('ui', uiname)
if os.path.isfile(uifile):
files.append((uifile,
py_from_ui_with_defaultdir(uifile)))
else:
log.warn('ignoring %r', f)
self.files = files
def run(self):
from PyQt6 import uic
_translate_re = (
(re.compile(r'(\s+_translate = QtCore\.QCoreApplication\.translate)'), r''),
(re.compile(
r'QtGui\.QApplication.translate\(.*?, (.*?), None, '
r'QtGui\.QApplication\.UnicodeUTF8\)'), r'_(\1)'),
(re.compile(r'\b_translate\(.*?, (.*?)(?:, None)?\)'), r'_(\1)'),
)
def compile_ui(uifile, pyfile):
tmp = StringIO()
log.info("compiling %s -> %s", uifile, pyfile)
uic.compileUi(uifile, tmp)
source = tmp.getvalue()
# replace QT translations stuff by ours
for matcher, replacement in _translate_re:
source = matcher.sub(replacement, source)
# replace headers
rc = re.compile(r'\n# WARNING.*?(?=\nclass )', re.MULTILINE | re.DOTALL)
command = _get_option_name(self)
new_header = f"""
# Automatically generated - do not edit.
# Use `python setup.py {command}` to update it.
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.i18n import gettext as _
"""
source = rc.sub(new_header, source)
# save to final file
with open(pyfile, "w") as f:
f.write(source)
if self.files:
for uifile, pyfile in self.files:
compile_ui(uifile, pyfile)
else:
for uifile, pyfile in ui_files():
if newer(uifile, pyfile):
compile_ui(uifile, pyfile)
from resources import (
compile,
makeqrc,
)
makeqrc.main()
compile.main()
class picard_clean_ui(Command):
description = "clean up compiled Qt UI files and resources"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
for uifile, pyfile in ui_files():
try:
os.unlink(pyfile)
log.info("removing %s", pyfile)
except OSError:
log.warn("'%s' does not exist -- can't clean it", pyfile)
pyfile = os.path.join("picard", "resources.py")
try:
os.unlink(pyfile)
log.info("removing %s", pyfile)
except OSError:
log.warn("'%s' does not exist -- can't clean it", pyfile)
class picard_build_appdata(Command):
description = 'Build appdata metadata file'
user_options = []
re_release = re.compile(r'^# Version (?P<version>\d+(?:\.\d+){1,2}) - (?P<date>\d{4}-\d{2}-\d{2})', re.MULTILINE)
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
with tempfile.NamedTemporaryFile(suffix=APPDATA_FILE) as tmp_file:
self.spawn([
'msgfmt', '--xml',
'--template=%s' % APPDATA_FILE_TEMPLATE,
'-d', 'po/appstream',
'-o', tmp_file.name,
])
self.add_release_list(tmp_file.name)
def add_release_list(self, source_file):
template = '<release date="{date}" version="{version}"/>'
with open('NEWS.md', 'r') as newsfile:
news = newsfile.read()
releases = [template.format(**m.groupdict()) for m in self.re_release.finditer(news)]
args = {
'app-id': PICARD_APP_ID,
'desktop-id': PICARD_DESKTOP_NAME,
'releases': '\n '.join(releases)
}
generate_file(source_file, APPDATA_FILE, args)
class picard_build_desktop_file(Command):
description = 'Build XDG desktop file'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
self.spawn([
'msgfmt', '--desktop',
'--template=%s' % DESKTOP_FILE_TEMPLATE,
'-d', 'po/appstream',
'-o', DESKTOP_FILE,
])
class picard_regen_appdata_pot_file(Command):
description = 'Regenerate translations from appdata metadata and XDG desktop file templates'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
output_dir = 'po/appstream/'
pot_file = os.path.join(output_dir, 'picard-appstream.pot')
self.spawn([
'xgettext',
'--output', pot_file,
'--language=appdata',
APPDATA_FILE_TEMPLATE,
])
self.spawn([
'xgettext',
'--output', pot_file,
'--language=desktop',
'--join-existing',
DESKTOP_FILE_TEMPLATE,
])
for filepath in glob.glob(os.path.join(output_dir, '*.po')):
self.spawn([
'msgmerge',
'--update',
filepath,
pot_file
])
_regen_pot_description = "Regenerate po/picard.pot, parsing source tree for new or updated strings"
_regen_constants_pot_description = "Regenerate po/constants/constants.pot, parsing source tree for new or updated strings"
try:
from babel.messages import frontend as babel
class picard_regen_pot_file(babel.extract_messages):
description = _regen_pot_description
def initialize_options(self):
super().initialize_options()
self.output_file = 'po/picard.pot'
self.input_dirs = 'picard'
self.ignore_dirs = ('const',)
class picard_regen_constants_pot_file(babel.extract_messages):
description = _regen_constants_pot_description
def initialize_options(self):
super().initialize_options()
self.output_file = 'po/constants/constants.pot'
self.input_dirs = 'picard/const'
except ImportError:
class picard_regen_pot_file(Command):
description = _regen_pot_description
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
sys.exit("Babel is required to use this command (see po/README.md)")
class picard_regen_constants_pot_file(picard_regen_pot_file):
description = _regen_constants_pot_description
def _get_option_name(obj):
"""Returns the name of the option for specified Command object"""
for name, klass in obj.distribution.cmdclass.items():
if obj.__class__ == klass:
return name
raise Exception("No such command class")
class picard_update_constants(Command):
description = "Regenerate attributes.py and countries.py"
user_options = [
('skip-pull', None, "skip the translation pull step"),
('weblate-key=', None, "Weblate API key"),
]
boolean_options = ['skip-pull']
def initialize_options(self):
self.skip_pull = None
self.weblate_key = None
def finalize_options(self):
self.locales = self.distribution.locales
def run(self):
from babel.messages import pofile
if not self.skip_pull:
cmd = [
os.path.join(os.path.dirname(__file__), 'scripts', 'tools', 'pull-shared-translations.py'),
]
if self.weblate_key:
cmd.append('--key')
cmd.append(self.weblate_key)
self.spawn(cmd)
countries = dict()
countries_potfile = os.path.join('po', 'countries', 'countries.pot')
isocode_comment = 'iso.code:'
with open(countries_potfile, 'rb') as f:
log.info('Parsing %s' % countries_potfile)
po = pofile.read_po(f)
for message in po:
if not message.id or not isinstance(message.id, str):
continue
for comment in message.auto_comments:
if comment.startswith(isocode_comment):
code = comment.replace(isocode_comment, '')
countries[code] = message.id
if countries:
self.countries_py_file(countries)
else:
sys.exit('Failed to extract any country code/name !')
attributes = dict()
attributes_potfile = os.path.join('po', 'attributes', 'attributes.pot')
extract_attributes = (
'DB:cover_art_archive.art_type/name',
'DB:medium_format/name',
'DB:release_group_primary_type/name',
'DB:release_group_secondary_type/name',
'DB:release_status/name',
)
with open(attributes_potfile, 'rb') as f:
log.info('Parsing %s' % attributes_potfile)
po = pofile.read_po(f)
for message in po:
if not message.id or not isinstance(message.id, str):
continue
for loc, pos in message.locations:
if loc in extract_attributes:
attributes["%s:%03d" % (loc, pos)] = message.id
if attributes:
self.attributes_py_file(attributes)
else:
sys.exit('Failed to extract any attribute !')
def countries_py_file(self, countries):
header = ("# -*- coding: utf-8 -*-\n"
"# Automatically generated - don't edit.\n"
"# Use `python setup.py {option}` to update it.\n"
"\n"
"RELEASE_COUNTRIES = {{\n")
line = " '{code}': '{name}',\n"
footer = "}}\n"
filename = os.path.join('picard', 'const', 'countries.py')
with open(filename, 'w', encoding='utf-8') as countries_py:
def write(s, **kwargs):
countries_py.write(s.format(**kwargs))
write(header, option=_get_option_name(self))
for code, name in sorted(countries.items(), key=lambda t: t[0]):
write(line, code=code, name=name.replace("'", "\\'"))
write(footer)
log.info("%s was rewritten (%d countries)", filename, len(countries))
def attributes_py_file(self, attributes):
header = ("# -*- coding: utf-8 -*-\n"
"# Automatically generated - don't edit.\n"
"# Use `python setup.py {option}` to update it.\n"
"\n"
"MB_ATTRIBUTES = {{\n")
line = " '{key}': '{value}',\n"
footer = "}}\n"
filename = os.path.join('picard', 'const', 'attributes.py')
with open(filename, 'w', encoding='utf-8') as attributes_py:
def write(s, **kwargs):
attributes_py.write(s.format(**kwargs))
write(header, option=_get_option_name(self))
for key, value in sorted(attributes.items(), key=lambda i: i[0]):
write(line, key=key, value=value.replace("'", "\\'"))
write(footer)
log.info("%s was rewritten (%d attributes)", filename, len(attributes))
class picard_patch_version(Command):
description = "Update PICARD_BUILD_VERSION_STR for daily builds"
user_options = [
('platform=', 'p', "platform for the build version, ie. osx or win"),
]
def initialize_options(self):
self.platform = sys.platform
def finalize_options(self):
pass
def run(self):
self.patch_version('picard/__init__.py')
def patch_version(self, filename):
regex = re.compile(r'^PICARD_BUILD_VERSION_STR\s*=.*$', re.MULTILINE)
with open(filename, 'r+b') as f:
source = (f.read()).decode()
build = self.platform + '.' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M%S')
patched_source = regex.sub('PICARD_BUILD_VERSION_STR = "%s"' % build, source).encode()
f.seek(0)
f.write(patched_source)
f.truncate()
def cflags_to_include_dirs(cflags):
cflags = cflags.split()
include_dirs = []
for cflag in cflags:
if cflag.startswith('-I'):
include_dirs.append(cflag[2:])
return include_dirs
def _picard_get_locale_files():
locales = []
domain_path = {
'picard': 'po',
'picard-attributes': os.path.join('po', 'attributes'),
'picard-constants': os.path.join('po', 'constants'),
'picard-countries': os.path.join('po', 'countries'),
}
for domain, path in domain_path.items():
for filepath in glob.glob(os.path.join(path, '*.po')):
filename = os.path.basename(filepath)
locale = os.path.splitext(filename)[0]
locales.append((domain, locale, filepath))
return locales
def _explode_path(path):
"""Return a list of components of the path (ie. "/a/b" -> ["a", "b"])"""
components = []
while True:
(path, tail) = os.path.split(path)
if tail == "":
components.reverse()
return components
components.append(tail)
def _picard_packages():
"""Build a tuple containing each module under picard/"""
packages = []
for subdir, dirs, files in os.walk("picard"):
packages.append(".".join(_explode_path(subdir)))
return tuple(sorted(packages))
this_directory = os.path.abspath(os.path.dirname(__file__))
def _get_description():
with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f:
return f.read()
def _get_requirements():
with open(os.path.join(this_directory, 'requirements.txt'), encoding='utf-8') as f:
return f.readlines()
args = {
'name': PACKAGE_NAME,
'version': PICARD_VERSION_STR_SHORT,
'description': 'The next generation MusicBrainz tagger',
'keywords': 'MusicBrainz metadata tagger picard',
'long_description': _get_description(),
'long_description_content_type': 'text/markdown',
'url': 'https://picard.musicbrainz.org/',
'package_dir': {'picard': 'picard'},
'packages': _picard_packages(),
'locales': _picard_get_locale_files(),
'ext_modules': ext_modules,
'data_files': [],
'cmdclass': {
'test': picard_test,
'build': picard_build,
'build_locales': picard_build_locales,
'build_ui': picard_build_ui,
'clean_ui': picard_clean_ui,
'build_appdata': picard_build_appdata,
'regen_appdata_pot_file': picard_regen_appdata_pot_file,
'build_desktop_file': picard_build_desktop_file,
'install': picard_install,
'install_locales': picard_install_locales,
'update_constants': picard_update_constants,
'regen_pot_file': picard_regen_pot_file,
'regen_constants_pot_file': picard_regen_constants_pot_file,
'patch_version': picard_patch_version,
},
'scripts': ['scripts/' + PACKAGE_NAME],
'install_requires': _get_requirements(),
'python_requires': '~=3.9',
'classifiers': [
'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',
'Development Status :: 5 - Production/Stable',
'Environment :: MacOS X',
'Environment :: Win32 (MS Windows)',
'Environment :: X11 Applications :: Qt',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Topic :: Multimedia :: Sound/Audio',
'Topic :: Multimedia :: Sound/Audio :: Analysis',
'Intended Audience :: End Users/Desktop',
]
}
def generate_file(infilename, outfilename, variables):
log.info('generating %s from %s', outfilename, infilename)
with open(infilename, "rt") as f_in:
with open(outfilename, "wt") as f_out:
f_out.write(f_in.read() % variables)
def make_executable(filename):
os.chmod(filename, os.stat(filename).st_mode | stat.S_IEXEC)
def find_file_in_path(filename):
for include_path in sys.path:
file_path = os.path.join(include_path, filename)
if os.path.exists(file_path):
return file_path
if sys.platform not in {'darwin', 'haiku1', 'win32'}:
args['data_files'].append(('share/applications', [PICARD_DESKTOP_NAME]))
args['data_files'].append(('share/icons/hicolor/scalable/apps', ['resources/%s.svg' % PICARD_APP_ID]))
for size in (16, 24, 32, 48, 128, 256):
args['data_files'].append((
'share/icons/hicolor/{size}x{size}/apps'.format(size=size),
['resources/images/{size}x{size}/{app_id}.png'.format(size=size, app_id=PICARD_APP_ID)]
))
args['data_files'].append(('share/metainfo', [APPDATA_FILE]))
if sys.platform == 'win32':
args['entry_points'] = {
'gui_scripts': [
'picard = picard.tagger:main'
]
}
setup(**args)
| 30,345
|
Python
|
.py
| 720
| 32.85
| 134
| 0.596199
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,820
|
.pylintrc
|
metabrainz_picard/.pylintrc
|
[MAIN]
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
# in a server-like mode.
clear-cache-post-run=no
# Load and enable all available extensions. Use --list-extensions to see a list
# all available extensions.
#enable-all-extensions=
# In error mode, messages with a category besides ERROR or FATAL are
# suppressed, and no reports are done by default. Error mode is compatible with
# disabling specific errors.
#errors-only=
# Always return a 0 (non-error) status code, even if lint errors are found.
# This is primarily useful in continuous integration scripts.
#exit-zero=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-allow-list=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
# for backward compatibility.)
extension-pkg-whitelist=
# Return non-zero exit code if any of these messages/categories are detected,
# even if score is above --fail-under value. Syntax same as enable. Messages
# specified are enabled, while categories only check already-enabled messages.
fail-on=
# Specify a score threshold under which the program will exit with error.
fail-under=10.0
# Interpret the stdin as a python script, whose filename needs to be passed as
# the module_or_package argument.
#from-stdin=
# Files or directories to be skipped. They should be base names, not paths.
ignore=CVS
# Add files or directories matching the regular expressions patterns to the
# ignore-list. The regex matches against paths and can be in Posix or Windows
# format. Because '\\' represents the directory delimiter on Windows systems,
# it can't be used as an escape character.
ignore-paths=picard/ui/forms
# Files or directories matching the regular expression patterns are skipped.
# The regex matches against base names, not paths. The default value ignores
# Emacs file locks
ignore-patterns=^\.#
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use, and will cap the count on Windows to
# avoid hangs.
jobs=0
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Minimum Python version to use for version dependent checks. Will default to
# the version used to run pylint.
py-version=3.10
# Discover python modules and packages in the file system subtree.
recursive=no
# Add paths to the list of the source roots. Supports globbing patterns. The
# source root is an absolute path or a path relative to the current working
# directory used to determine a package namespace for modules located under the
# source root.
source-roots=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# In verbose mode, extra non-checker-related info will be displayed.
#verbose=
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style. If left empty, argument names will be checked with the set
# naming style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style. If left empty, attribute names will be checked with the set naming
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style. If left empty, class attribute names will be checked
# with the set naming style.
#class-attribute-rgx=
# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE
# Regular expression matching correct class constant names. Overrides class-
# const-naming-style. If left empty, class constant names will be checked with
# the set naming style.
#class-const-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style. If left empty, class names will be checked with the set naming style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style. If left empty, constant names will be checked with the set naming
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style. If left empty, function names will be checked with the set
# naming style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style. If left empty, inline iteration names will be checked
# with the set naming style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style. If left empty, method names will be checked with the set naming style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style. If left empty, module names will be checked with the set naming style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Regular expression matching correct type alias names. If left empty, type
# alias names will be checked with the set naming style.
#typealias-rgx=
# Regular expression matching correct type variable names. If left empty, type
# variable names will be checked with the set naming style.
#typevar-rgx=
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style. If left empty, variable names will be checked with the set
# naming style.
#variable-rgx=
[CLASSES]
# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[DESIGN]
# List of regular expressions of class ancestor names to ignore when counting
# public methods (see R0903)
exclude-too-few-public-methods=
# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[EXCEPTIONS]
# Exceptions that will emit a warning when caught.
overgeneral-exceptions=builtins.Exception
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module.
max-module-lines=1000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow explicit reexports by alias from a package __init__.
allow-reexport-from-package=no
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=
# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=
# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
# UNDEFINED.
confidence=HIGH,
CONTROL_FLOW,
INFERENCE,
INFERENCE_FAILURE,
UNDEFINED
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
c-extension-no-member,
unnecessary-lambda-assignment,
unnecessary-direct-lambda-call,
non-ascii-name,
non-ascii-module-import,
unneeded-not,
consider-iterating-dictionary,
consider-using-dict-items,
use-maxsplit-arg,
use-sequence-for-iteration,
consider-using-f-string,
use-implicit-booleaness-not-len,
use-implicit-booleaness-not-comparison,
invalid-name,
disallowed-name,
typevar-name-incorrect-variance,
typevar-double-variance,
typevar-name-mismatch,
empty-docstring,
missing-module-docstring,
missing-class-docstring,
missing-function-docstring,
singleton-comparison,
bad-file-encoding,
wrong-spelling-in-comment,
wrong-spelling-in-docstring,
invalid-characters-in-docstring,
unnecessary-dunder-call,
multiple-imports,
wrong-import-order,
ungrouped-imports,
wrong-import-position,
useless-import-alias,
import-outside-toplevel,
bad-classmethod-argument,
bad-mcs-method-argument,
bad-mcs-classmethod-argument,
single-string-used-for-slots,
line-too-long,
too-many-lines,
missing-final-newline,
trailing-newlines,
multiple-statements,
superfluous-parens,
mixed-line-endings,
unexpected-line-ending-format,
useless-option-value,
consider-merging-isinstance,
too-many-nested-blocks,
simplifiable-if-statement,
no-else-return,
consider-using-ternary,
trailing-comma-tuple,
stop-iteration-return,
simplify-boolean-expression,
inconsistent-return-statements,
useless-return,
consider-swap-variables,
consider-using-join,
consider-using-in,
consider-using-get,
chained-comparison,
consider-using-dict-comprehension,
consider-using-set-comprehension,
simplifiable-if-expression,
no-else-raise,
unnecessary-comprehension,
consider-using-sys-exit,
no-else-break,
no-else-continue,
super-with-arguments,
simplifiable-condition,
condition-evals-to-constant,
consider-using-generator,
use-a-generator,
consider-using-min-builtin,
consider-using-max-builtin,
consider-using-with,
unnecessary-dict-index-lookup,
use-list-literal,
use-dict-literal,
unnecessary-list-index-lookup,
literal-comparison,
comparison-with-itself,
comparison-of-constants,
cyclic-import,
consider-using-from-import,
duplicate-code,
useless-object-inheritance,
property-with-parameters,
too-many-ancestors,
too-many-instance-attributes,
too-few-public-methods,
too-many-public-methods,
too-many-return-statements,
too-many-branches,
too-many-arguments,
too-many-locals,
too-many-statements,
too-many-boolean-expressions,
unknown-option-value,
fixme,
unnecessary-ellipsis,
bad-open-mode,
boolean-datetime,
redundant-unittest-assert,
bad-thread-instantiation,
shallow-copy-environ,
invalid-envvar-default,
subprocess-popen-preexec-fn,
subprocess-run-check,
unspecified-encoding,
forgotten-debug-statement,
method-cache-max-size-none,
deprecated-method,
deprecated-argument,
deprecated-class,
deprecated-decorator,
bad-chained-comparison,
nested-min-max,
non-ascii-file-name,
try-except-raise,
raise-missing-from,
raising-format-tuple,
wrong-exception-operation,
broad-exception-caught,
broad-exception-raised,
useless-with-lock,
eval-used,
using-constant-test,
missing-parentheses-for-call-in-test,
self-assigning-variable,
redeclared-assigned-name,
assert-on-string-literal,
duplicate-value,
named-expr-without-context,
pointless-exception-statement,
comparison-with-callable,
nan-comparison,
keyword-arg-before-vararg,
arguments-out-of-order,
non-str-assignment-to-dunder-name,
isinstance-second-argument-not-valid-type,
missing-timeout,
unused-format-string-key,
unused-format-string-argument,
duplicate-string-formatting-argument,
f-string-without-interpolation,
format-string-without-interpolation,
anomalous-backslash-in-string,
anomalous-unicode-escape-in-string,
implicit-str-concat,
inconsistent-quotes,
redundant-u-string-prefix,
logging-not-lazy,
logging-format-interpolation,
logging-fstring-interpolation,
wildcard-import,
import-self,
preferred-module,
shadowed-import,
deprecated-module,
attribute-defined-outside-init,
bad-staticmethod-argument,
protected-access,
implicit-flag-alias,
abstract-method,
super-init-not-called,
invalid-overridden-method,
arguments-renamed,
unused-private-member,
overridden-final-method,
subclassed-final-class,
redefined-slots-in-subclass,
super-without-brackets,
useless-parent-delegation,
modified-iterating-list,
using-f-string-in-unsupported-version,
using-final-decorator-in-unsupported-version,
unnecessary-semicolon,
bad-indentation,
global-statement,
unused-variable,
unused-argument,
unused-wildcard-import,
redefined-outer-name,
redefined-builtin,
undefined-loop-variable,
unbalanced-tuple-unpacking,
cell-var-from-loop,
possibly-unused-variable,
self-cls-assignment,
unbalanced-dict-unpacking,
syntax-error,
unrecognized-inline-option,
bad-plugin-value,
bad-configuration-section,
unrecognized-option,
invalid-envvar-value,
singledispatch-method,
singledispatchmethod-function,
yield-inside-async-function,
not-async-context-manager,
used-prior-global-declaration,
bad-reversed-sequence,
misplaced-format-function,
no-member,
not-callable,
too-many-function-args,
assignment-from-none,
not-context-manager,
invalid-unary-operand-type,
unsupported-binary-operation,
unsupported-membership-test,
unsubscriptable-object,
unsupported-assignment-operation,
unsupported-delete-operation,
invalid-metaclass,
dict-iter-missing-items,
await-outside-async,
unhashable-member,
invalid-slice-step,
not-an-iterable,
not-a-mapping,
invalid-unicode-codec,
bidirectional-unicode,
invalid-character-backspace,
invalid-character-carriage-return,
invalid-character-sub,
invalid-character-esc,
invalid-character-nul,
invalid-character-zero-width-space,
positional-only-arguments-expected,
too-many-format-args,
bad-string-format-type,
bad-str-strip-call,
import-error,
relative-beyond-top-level,
no-self-argument,
assigning-non-slot,
class-variable-slots-conflict,
invalid-class-object,
invalid-enum-extension,
invalid-length-returned,
invalid-bool-returned,
invalid-index-returned,
invalid-repr-returned,
invalid-str-returned,
invalid-bytes-returned,
invalid-hash-returned,
invalid-length-hint-returned,
invalid-format-returned,
invalid-getnewargs-returned,
invalid-getnewargs-ex-returned,
modified-iterating-dict,
modified-iterating-set,
invalid-all-format,
no-name-in-module,
unpacking-non-sequence,
potential-index-error,
fatal,
astroid-error,
parse-error,
config-parse-error,
method-check-failed
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=consider-using-enumerate,
unidiomatic-typecheck,
trailing-whitespace,
redefined-argument-from-local,
no-classmethod-decorator,
no-staticmethod-decorator,
bare-except,
duplicate-except,
binary-op-exception,
useless-else-on-loop,
unreachable,
dangerous-default-value,
pointless-statement,
pointless-string-statement,
expression-not-assigned,
unnecessary-lambda,
duplicate-key,
exec-used,
confusing-with-statement,
lost-exception,
assert-on-tuple,
unnecessary-pass,
bad-format-string-key,
bad-format-string,
missing-format-argument-key,
format-combined-specification,
missing-format-attribute,
invalid-format-index,
reimported,
misplaced-future,
arguments-differ,
signature-differs,
non-parent-init-called,
global-variable-undefined,
global-variable-not-assigned,
global-at-module-level,
unused-import,
bad-super-call,
bad-except-order,
raising-bad-type,
misplaced-bare-raise,
bad-exception-cause,
raising-non-exception,
notimplemented-raised,
catching-non-exception,
init-is-generator,
return-in-init,
function-redefined,
not-in-loop,
return-outside-function,
yield-outside-function,
return-arg-in-generator,
nonexistent-operator,
duplicate-argument-name,
abstract-class-instantiated,
too-many-star-expressions,
invalid-star-assignment-target,
star-needs-assignment-target,
nonlocal-and-global,
continue-in-finally,
nonlocal-without-binding,
assignment-from-no-return,
no-value-for-parameter,
unexpected-keyword-arg,
redundant-keyword-arg,
missing-kwoa,
invalid-sequence-index,
invalid-slice-index,
repeated-keyword,
bad-format-character,
truncated-format-string,
mixed-format-string,
format-needs-mapping,
missing-format-string-key,
too-few-format-args,
logging-unsupported-format,
logging-format-truncated,
logging-too-many-args,
logging-too-few-args,
method-hidden,
access-member-before-definition,
no-method-argument,
invalid-slots-object,
invalid-slots,
inherit-non-class,
inconsistent-mro,
duplicate-bases,
non-iterator-returned,
unexpected-special-method-signature,
used-before-assignment,
undefined-variable,
undefined-all-variable,
invalid-all-object
[METHOD_ARGS]
# List of qualified names (i.e., library.method) which require a timeout
# parameter e.g. 'requests.api.get,requests.api.post'
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
notes-rgx=
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
# 'convention', and 'info' which contain the number of messages in each
# category, as well as 'statement' which is the total number of statements
# analyzed. This score is used by the global evaluation report (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
#output-format=
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[SIMILARITIES]
# Comments are removed from the similarity computation
ignore-comments=yes
# Docstrings are removed from the similarity computation
ignore-docstrings=yes
# Imports are removed from the similarity computation
ignore-imports=no
# Signatures are removed from the similarity computation
ignore-signatures=yes
# Minimum lines number of a similarity.
min-similarity-lines=4
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. No available dictionaries : You need to install
# both the python package and the system dependency for enchant to work..
spelling-dict=
# List of comma separated words that should be considered directives if they
# appear at the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of symbolic message names to ignore for Mixin members.
ignored-checks-for-mixins=no-member,
not-async-context-manager,
not-context-manager,
attribute-defined-outside-init
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=thread._local,_thread._local
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# Regex pattern to define which classes are considered mixins.
mixin-class-rgx=.*[Mm]ixin
# List of decorators that change the signature of a decorated function.
signature-mutators=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of names allowed to shadow builtins
allowed-redefined-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
| 32,229
|
Python
|
.py
| 815
| 34.422086
| 166
| 0.737284
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,821
|
test_script.py
|
metabrainz_picard/test/test_script.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Lukáš Lalinský
# Copyright (C) 2010, 2014, 2018-2022 Philipp Wolfer
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2013 Michael Wiencek
# Copyright (C) 2013, 2017-2021 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Antonio Larrosa
# Copyright (C) 2017-2018, 2021 Wieland Hoffmann
# Copyright (C) 2018 virusMac
# Copyright (C) 2020-2022 Bob Swift
# Copyright (C) 2021 Adam James
#
# This program is free software; you can redistribute it and/or
# modify 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.
import datetime
import re
import unittest
from unittest import mock
from unittest.mock import (
MagicMock,
patch,
)
from test.picardtestcase import PicardTestCase
from picard.cluster import Cluster
from picard.const.defaults import DEFAULT_FILE_NAMING_FORMAT
from picard.extension_points.script_functions import (
FunctionRegistryItem,
register_script_function,
script_function,
)
from picard.metadata import (
MULTI_VALUED_JOINER,
Metadata,
)
from picard.plugin import ExtensionPoint
from picard.script import (
MultiValue,
ScriptEndOfFile,
ScriptError,
ScriptExpression,
ScriptFunction,
ScriptFunctionDocError,
ScriptParser,
ScriptRuntimeError,
ScriptSyntaxError,
ScriptUnicodeError,
ScriptUnknownFunction,
script_function_documentation,
script_function_documentation_all,
)
try:
from markdown import markdown
except ImportError:
markdown = None
class _TestTimezone(datetime.tzinfo):
def utcoffset(self, dt):
# Set to GMT+2
return datetime.timedelta(hours=2) + self.dst(dt)
def dst(self, dt):
d = datetime.datetime(dt.year, 4, 1)
self.dston = d - datetime.timedelta(days=d.weekday() + 1)
d = datetime.datetime(dt.year, 11, 1)
self.dstoff = d - datetime.timedelta(days=d.weekday() + 1)
if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
return datetime.timedelta(hours=1)
else:
return datetime.timedelta(0)
def tzname(self, dt):
return "TZ Test"
class _DateTime(datetime.datetime):
@classmethod
def now(cls, tz=None):
return datetime.datetime(2020, 1, 2, hour=12, minute=34, second=56, microsecond=789, tzinfo=tz)
def astimezone(self, tz=None):
# Ignore tz passed to the method and force use of test timezone.
tz = _TestTimezone()
utc = (self - self.utcoffset()).replace(tzinfo=tz)
# Convert from UTC to tz's local time.
return tz.fromutc(utc)
class ScriptParserTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({
'enabled_plugins': '',
})
self.parser = ScriptParser()
# ensure we start on clean registry
ScriptParser._cache = {}
def assertScriptResultEquals(self, script, expected, context=None, file=None):
"""Asserts that evaluating `script` returns `expected`.
Args:
script: The tagger script
expected: The expected result
context: A Metadata object with pre-set tags or None
"""
actual = self.parser.eval(script, context=context, file=file)
self.assertEqual(actual,
expected,
"'%s' evaluated to '%s', expected '%s'"
% (script, actual, expected))
def test_function_registry_item(self):
def somefunc():
return 'x'
item = FunctionRegistryItem(somefunc, 'x', 'y', 'doc')
self.assertEqual(item.function, somefunc)
self.assertEqual(item.eval_args, 'x')
self.assertEqual(item.argcount, 'y')
self.assertEqual(item.documentation, 'doc')
regex = r'^'\
+ re.escape(r'FunctionRegistryItem(<function ')\
+ r'[^ ]+'\
+ re.escape(r'.somefunc at ')\
+ r'[^>]+'\
+ re.escape(r'>, x, y, """doc""")')\
+ r'$'
self.assertRegex(repr(item), regex)
def test_script_unicode_char(self):
self.assertScriptResultEquals("\\u6e56", "湖")
self.assertScriptResultEquals("foo\\u6e56bar", "foo湖bar")
self.assertScriptResultEquals("\\uFFFF", "\uffff")
def test_script_unicode_char_eof(self):
areg = r"^\d+:\d+: Unexpected end of script"
with self.assertRaisesRegex(ScriptEndOfFile, areg):
self.parser.eval("\\u")
with self.assertRaisesRegex(ScriptEndOfFile, areg):
self.parser.eval("\\uaff")
def test_script_unicode_char_err(self):
areg = r"^\d+:\d+: Invalid unicode character '\\ufffg'"
with self.assertRaisesRegex(ScriptUnicodeError, areg):
self.parser.eval("\\ufffg")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_decorator_default(self):
# test default decorator and default prefix
@script_function()
def func_somefunc(parser):
return "x"
self.assertScriptResultEquals("$somefunc()", "x")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_decorator_no_prefix(self):
# function without prefix
@script_function()
def somefunc(parser):
return "x"
self.assertScriptResultEquals("$somefunc()", "x")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_decorator_arg(self):
# function with argument
@script_function()
def somefunc(parser, arg):
return arg
@script_function()
def title(parser, arg):
return arg.upper()
self.assertScriptResultEquals("$somefunc($title(x))", "X")
areg = r"^\d+:\d+:\$somefunc: Wrong number of arguments for \$somefunc: Expected exactly 1"
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$somefunc()")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_decorator_argcount(self):
# ignore argument count
@script_function(check_argcount=False)
def somefunc(parser, *arg):
return str(len(arg))
self.assertScriptResultEquals("$somefunc(a,b,c)", "3")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_decorator_altname(self):
# alternative name
@script_function(name="otherfunc")
def somefunc4(parser):
return "x"
self.assertScriptResultEquals("$otherfunc()", "x")
areg = r"^\d+:\d+:\$somefunc: Unknown function '\$somefunc'"
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$somefunc()")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_decorator_altprefix(self):
# alternative prefix
@script_function(prefix='theprefix_')
def theprefix_somefunc(parser):
return "x"
self.assertScriptResultEquals("$somefunc()", "x")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_decorator_eval_args(self):
# disable argument evaluation
@script_function(eval_args=False)
def somefunc(parser, arg):
return arg.eval(parser)
@script_function()
def title(parser, arg):
return arg.upper()
self.assertScriptResultEquals("$somefunc($title(x))", "X")
@staticmethod
def assertStartswith(text, expect):
if not text.startswith(expect):
raise AssertionError("do not start with %r but with %r" % (expect, text[:len(expect)]))
@staticmethod
def assertEndswith(text, expect):
if not text.endswith(expect):
raise AssertionError("do not end with %r but with %r" % (expect, text[-len(expect):]))
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_documentation_nodoc(self):
"""test script_function_documentation() with a function without documentation"""
@script_function()
def func_nodocfunc(parser):
return ""
doc = script_function_documentation('nodocfunc', 'markdown')
self.assertEqual(doc, '')
doc = script_function_documentation('nodocfunc', 'html')
self.assertEqual(doc, '')
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_documentation(self):
"""test script_function_documentation() with a function with documentation"""
# the documentation used to test includes backquotes
testdoc = '`$somefunc()`'
@script_function(documentation=testdoc)
def func_somefunc(parser):
return "x"
doc = script_function_documentation('somefunc', 'markdown')
self.assertEqual(doc, testdoc)
areg = r"^no such documentation format: unknownformat"
with self.assertRaisesRegex(ScriptFunctionDocError, areg):
script_function_documentation('somefunc', 'unknownformat')
@unittest.skipUnless(markdown, "markdown module missing")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_documentation_html(self):
"""test script_function_documentation() with a function with documentation"""
# get html code as generated by markdown
pre, post = markdown('`XXX`').split('XXX')
# the documentation used to test includes backquotes
testdoc = '`$somefunc()`'
@script_function(documentation=testdoc)
def func_somefunc(parser):
return "x"
doc = script_function_documentation('somefunc', 'html')
self.assertEqual(doc, pre + '$somefunc()' + post)
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_documentation_unknown_function(self):
"""test script_function_documentation() with an unknown function"""
areg = r"^no such function: unknownfunc"
with self.assertRaisesRegex(ScriptFunctionDocError, areg):
script_function_documentation('unknownfunc', 'html')
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_documentation_all(self):
"""test script_function_documentation_all() with markdown format"""
@script_function(documentation='somedoc2')
def func_somefunc2(parser):
return "x"
@script_function(documentation='somedoc1')
def func_somefunc1(parser):
return "x"
docall = script_function_documentation_all()
self.assertEqual(docall, 'somedoc1\nsomedoc2')
@unittest.skipUnless(markdown, "markdown module missing")
@patch('picard.extension_points.script_functions.ext_point_script_functions', ExtensionPoint(label='test_script'))
def test_script_function_documentation_all_html(self):
"""test script_function_documentation_all() with html format"""
# get html code as generated by markdown
pre, post = markdown('XXX').split('XXX')
@script_function(documentation='somedoc')
def func_somefunc(parser):
return "x"
def postprocessor(data, function):
return 'w' + data + function.name + 'y'
docall = script_function_documentation_all(
fmt='html',
pre='<div id="test">',
post="</div>\n",
postprocessor=postprocessor,
)
self.assertStartswith(docall, '<div id="test">w' + pre)
self.assertEndswith(docall, post + 'somefuncy</div>\n')
def test_unknown_function(self):
areg = r"^\d+:\d+:\$unknownfunction: Unknown function '\$unknownfunction'"
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$unknownfunction()")
def test_noname_function(self):
areg = r"^\d+:\d+:\$: Unknown function '\$'"
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$()")
def test_unexpected_end_of_script(self):
areg = r"^\d+:\d+: Unexpected end of script"
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$noop(")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$")
def test_unexpected_character(self):
areg = r"^\d+:\d+: Unexpected character '\^'"
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$^noop()")
def test_scriptfunction_unknown(self):
parser = ScriptParser()
parser.parse('')
areg = r"^\d+:\d+:\$x: Unknown function '\$x'"
with self.assertRaisesRegex(ScriptError, areg):
ScriptFunction('x', '', parser)
areg = r"^\d+:\d+:\$noop: Unknown function '\$noop'"
with self.assertRaisesRegex(ScriptError, areg):
f = ScriptFunction('noop', '', parser)
del parser.functions['noop']
f.eval(parser)
def test_cmd_noop(self):
self.assertScriptResultEquals("$noop()", "")
self.assertScriptResultEquals("$noop(abcdefg)", "")
def test_cmd_if(self):
self.assertScriptResultEquals("$if(1,a,b)", "a")
self.assertScriptResultEquals("$if(,a,b)", "b")
def test_cmd_if2(self):
self.assertScriptResultEquals("$if2(,a,b)", "a")
self.assertScriptResultEquals("$if2($noop(),b)", "b")
self.assertScriptResultEquals("$if2()", "")
self.assertScriptResultEquals("$if2(,)", "")
def test_cmd_left(self):
self.assertScriptResultEquals("$left(abcd,2)", "ab")
self.assertScriptResultEquals("$left(abcd,x)", "")
def test_cmd_right(self):
self.assertScriptResultEquals("$right(abcd,2)", "cd")
self.assertScriptResultEquals("$right(abcd,x)", "")
def test_cmd_set(self):
context = Metadata()
self.assertScriptResultEquals("$set(test,aaa)%test%", "aaa", context)
self.assertEqual(context['test'], 'aaa')
def test_cmd_set_empty(self):
self.assertScriptResultEquals("$set(test,)%test%", "")
def test_cmd_set_multi_valued(self):
context = Metadata()
context["source"] = ["multi", "valued"]
self.parser.eval("$set(test,%source%)", context)
self.assertEqual(context.getall("test"), ["multi; valued"]) # list has only a single value
def test_cmd_setmulti_multi_valued(self):
context = Metadata()
context["source"] = ["multi", "valued"]
self.assertEqual("", self.parser.eval("$setmulti(test,%source%)", context)) # no return value
self.assertEqual(context.getall("source"), context.getall("test"))
def test_cmd_setmulti_multi_valued_wth_spaces(self):
context = Metadata()
context["source"] = ["multi, multi", "valued, multi"]
self.assertEqual("", self.parser.eval("$setmulti(test,%source%)", context)) # no return value
self.assertEqual(context.getall("source"), context.getall("test"))
def test_cmd_setmulti_not_multi_valued(self):
context = Metadata()
context["source"] = "multi, multi"
self.assertEqual("", self.parser.eval("$setmulti(test,%source%)", context)) # no return value
self.assertEqual(context.getall("source"), context.getall("test"))
def test_cmd_setmulti_will_keep_empty_items(self):
context = Metadata()
context["source"] = ["", "multi", ""]
self.assertEqual("", self.parser.eval("$setmulti(test,%source%)", context)) # no return value
self.assertEqual(["", "multi", ""], context.getall("test"))
def test_cmd_setmulti_custom_splitter_string(self):
context = Metadata()
self.assertEqual("", self.parser.eval("$setmulti(test,multi##valued##test##,##)", context)) # no return value
self.assertEqual(["multi", "valued", "test", ""], context.getall("test"))
def test_cmd_setmulti_empty_splitter_does_nothing(self):
context = Metadata()
self.assertEqual("", self.parser.eval("$setmulti(test,multi; valued,)", context)) # no return value
self.assertEqual(["multi; valued"], context.getall("test"))
def test_cmd_get(self):
context = Metadata()
context["test"] = "aaa"
self.assertScriptResultEquals("$get(test)", "aaa", context)
context["test2"] = ["multi", "valued"]
self.assertScriptResultEquals("$get(test2)", "multi; valued", context)
def test_cmd_num(self):
self.assertScriptResultEquals("$num(3,3)", "003")
self.assertScriptResultEquals("$num(03,3)", "003")
self.assertScriptResultEquals("$num(123,2)", "123")
self.assertScriptResultEquals("$num(123,a)", "")
self.assertScriptResultEquals("$num(a,2)", "00")
self.assertScriptResultEquals("$num(123,-1)", "123")
self.assertScriptResultEquals("$num(123,35)", "00000000000000000123")
def test_cmd_or(self):
self.assertScriptResultEquals("$or(,)", "")
self.assertScriptResultEquals("$or(,,)", "")
self.assertScriptResultEquals("$or(,q)", "1")
self.assertScriptResultEquals("$or(q,)", "1")
self.assertScriptResultEquals("$or(q,q)", "1")
self.assertScriptResultEquals("$or(q,,)", "1")
def test_cmd_and(self):
self.assertScriptResultEquals("$and(,)", "")
self.assertScriptResultEquals("$and(,q)", "")
self.assertScriptResultEquals("$and(q,)", "")
self.assertScriptResultEquals("$and(q,q,)", "")
self.assertScriptResultEquals("$and(q,q)", "1")
self.assertScriptResultEquals("$and(q,q,q)", "1")
def test_cmd_not(self):
self.assertScriptResultEquals("$not($noop())", "1")
self.assertScriptResultEquals("$not(q)", "")
def test_cmd_trim(self):
self.assertScriptResultEquals("$trim( \\t test \\n )", "test")
self.assertScriptResultEquals("$trim(test,t)", "es")
self.assertScriptResultEquals("$trim(test,ts)", "e")
def test_cmd_add(self):
self.assertScriptResultEquals("$add(1,2)", "3")
self.assertScriptResultEquals("$add(1,2,3)", "6")
self.assertScriptResultEquals("$add(a,2)", "")
self.assertScriptResultEquals("$add(2,a)", "")
def test_cmd_sub(self):
self.assertScriptResultEquals("$sub(1,2)", "-1")
self.assertScriptResultEquals("$sub(2,1)", "1")
self.assertScriptResultEquals("$sub(4,2,1)", "1")
self.assertScriptResultEquals("$sub(a,2)", "")
self.assertScriptResultEquals("$sub(2,a)", "")
def test_cmd_div(self):
self.assertScriptResultEquals("$div(9,3)", "3")
self.assertScriptResultEquals("$div(10,3)", "3")
self.assertScriptResultEquals("$div(30,3,3)", "3")
self.assertScriptResultEquals("$div(30,0)", "")
self.assertScriptResultEquals("$div(30,a)", "")
def test_cmd_mod(self):
self.assertScriptResultEquals("$mod(9,3)", "0")
self.assertScriptResultEquals("$mod(10,3)", "1")
self.assertScriptResultEquals("$mod(10,6,3)", "1")
self.assertScriptResultEquals("$mod(a,3)", "")
self.assertScriptResultEquals("$mod(10,a)", "")
self.assertScriptResultEquals("$mod(10,0)", "")
def test_cmd_mul(self):
self.assertScriptResultEquals("$mul(9,3)", "27")
self.assertScriptResultEquals("$mul(10,3)", "30")
self.assertScriptResultEquals("$mul(2,5,3)", "30")
self.assertScriptResultEquals("$mul(2,a)", "")
self.assertScriptResultEquals("$mul(2,5,a)", "")
def test_cmd_eq(self):
self.assertScriptResultEquals("$eq(,)", "1")
self.assertScriptResultEquals("$eq(,$noop())", "1")
self.assertScriptResultEquals("$eq(,q)", "")
self.assertScriptResultEquals("$eq(q,q)", "1")
self.assertScriptResultEquals("$eq(q,)", "")
def test_cmd_ne(self):
self.assertScriptResultEquals("$ne(,)", "")
self.assertScriptResultEquals("$ne(,$noop())", "")
self.assertScriptResultEquals("$ne(,q)", "1")
self.assertScriptResultEquals("$ne(q,q)", "")
self.assertScriptResultEquals("$ne(q,)", "1")
def test_cmd_lower(self):
self.assertScriptResultEquals("$lower(AbeCeDA)", "abeceda")
def test_cmd_upper(self):
self.assertScriptResultEquals("$upper(AbeCeDA)", "ABECEDA")
def test_cmd_pad(self):
self.assertScriptResultEquals("$pad(abc de,10,-)", "----abc de")
self.assertScriptResultEquals("$pad(abc de,e,-)", "")
self.assertScriptResultEquals("$pad(abc de,6,-)", "abc de")
self.assertScriptResultEquals("$pad(abc de,3,-)", "abc de")
self.assertScriptResultEquals("$pad(abc de,0,-)", "abc de")
self.assertScriptResultEquals("$pad(abc de,-3,-)", "abc de")
def test_cmd_replace(self):
self.assertScriptResultEquals("$replace(abc ab abd a,ab,test)", "testc test testd a")
def test_cmd_replacemulti(self):
context = Metadata()
context["genre"] = ["Electronic", "Idm", "Techno"]
self.assertScriptResultEquals("$replacemulti(%genre%,Idm,IDM)", "Electronic; IDM; Techno", context)
context["genre"] = ["Electronic", "Jungle", "Bardcore"]
self.assertScriptResultEquals("$replacemulti(%genre%,Bardcore,Hardcore)", "Electronic; Jungle; Hardcore", context)
context["test"] = ["One", "Two", "Three"]
self.assertScriptResultEquals("$replacemulti(%test%,Two,)", "One; Three", context)
context["test"] = ["One", "Two", "Three"]
self.assertScriptResultEquals("$replacemulti(%test%,Four,Five)", "One; Two; Three", context)
context["test"] = ["Four", "Five", "Six"]
self.assertScriptResultEquals("$replacemulti(%test%,Five,)", "Four; Six", context)
self.assertScriptResultEquals("$replacemulti(a; b,,,)", "a; b")
self.assertScriptResultEquals("$setmulti(foo,a; b)$replacemulti(%foo%,,,)", "a; b")
def test_cmd_strip(self):
self.assertScriptResultEquals("$strip( \t abc de \n f )", "abc de f")
def test_cmd_rreplace(self):
self.assertScriptResultEquals(r'''$rreplace(test \(disc 1\),\\s\\\(disc \\d+\\\),)''', "test")
self.assertScriptResultEquals(r'''$rreplace(test,[t,)''', "test")
def test_cmd_rsearch(self):
self.assertScriptResultEquals(r"$rsearch(test \(disc 1\),\\\(disc \(\\d+\)\\\))", "1")
self.assertScriptResultEquals(r"$rsearch(test \(disc 1\),\\\(disc \\d+\\\))", "(disc 1)")
self.assertScriptResultEquals(r"$rsearch(test,x)", "")
self.assertScriptResultEquals(r'''$rsearch(test,[t)''', "")
def test_arguments(self):
self.assertTrue(
self.parser.eval(
r"$set(bleh,$rsearch(test \(disc 1\),\\\(disc \(\\d+\)\\\)))) $set(wer,1)"))
def test_cmd_gt(self):
# Test with default processing
self.assertScriptResultEquals("$gt(10,4)", "1")
self.assertScriptResultEquals("$gt(6,6)", "")
self.assertScriptResultEquals("$gt(6,7)", "")
self.assertScriptResultEquals("$gt(6.5,4)", "1")
self.assertScriptResultEquals("$gt(6.5,4.5)", "1")
self.assertScriptResultEquals("$gt(6.5,6.5)", "")
self.assertScriptResultEquals("$gt(a,b)", "")
self.assertScriptResultEquals("$gt(b,a)", "1")
self.assertScriptResultEquals("$gt(a,6)", "1")
self.assertScriptResultEquals("$gt(a,6.5)", "1")
self.assertScriptResultEquals("$gt(6,a)", "")
self.assertScriptResultEquals("$gt(6.5,a)", "")
# Test with "int" processing
self.assertScriptResultEquals("$gt(10,4,int)", "1")
self.assertScriptResultEquals("$gt(6,4,int)", "1")
self.assertScriptResultEquals("$gt(6.5,4,int)", "")
self.assertScriptResultEquals("$gt(6,7,int)", "")
self.assertScriptResultEquals("$gt(6,6,int)", "")
self.assertScriptResultEquals("$gt(a,b,int)", "")
# Test with "float" processing
self.assertScriptResultEquals("$gt(1.2,1,float)", "1")
self.assertScriptResultEquals("$gt(1.2,1.1,float)", "1")
self.assertScriptResultEquals("$gt(1.2,1.3,float)", "")
self.assertScriptResultEquals("$gt(1.2,1.2,float)", "")
self.assertScriptResultEquals("$gt(a,b,float)", "")
# Test date type arguments with "text" processing
self.assertScriptResultEquals("$gt(2020-01-01,2020-01-02,text)", "")
self.assertScriptResultEquals("$gt(2020-01-02,2020-01-01,text)", "1")
self.assertScriptResultEquals("$gt(2020-01-01,2020-02,text)", "")
self.assertScriptResultEquals("$gt(2020-02,2020-01-01,text)", "1")
self.assertScriptResultEquals("$gt(2020-01-01,2020-01-01,text)", "")
# Test text type arguments with "text" processing
self.assertScriptResultEquals("$gt(abc,abcd,text)", "")
self.assertScriptResultEquals("$gt(abcd,abc,text)", "1")
self.assertScriptResultEquals("$gt(abc,ac,text)", "")
self.assertScriptResultEquals("$gt(ac,abc,text)", "1")
self.assertScriptResultEquals("$gt(abc,abc,text)", "")
# Test with empty arguments (default processing)
self.assertScriptResultEquals("$gt(,1)", "")
self.assertScriptResultEquals("$gt(1,)", "1")
self.assertScriptResultEquals("$gt(,)", "")
# Test with empty arguments ("int" processing)
self.assertScriptResultEquals("$gt(,1,int)", "")
self.assertScriptResultEquals("$gt(1,,int)", "")
self.assertScriptResultEquals("$gt(,,int)", "")
# Test with empty arguments ("float" processing)
self.assertScriptResultEquals("$gt(,1.1,float)", "")
self.assertScriptResultEquals("$gt(1.1,float)", "")
self.assertScriptResultEquals("$gt(,,float)", "")
# Test with empty arguments ("text" processing)
self.assertScriptResultEquals("$gt(,a,text)", "")
self.assertScriptResultEquals("$gt(a,,text)", "1")
self.assertScriptResultEquals("$gt(,,text)", "")
# Test case sensitive arguments ("text" processing)
self.assertScriptResultEquals("$gt(A,a,text)", "")
self.assertScriptResultEquals("$gt(a,A,text)", "1")
# Test case insensitive arguments ("nocase" processing)
self.assertScriptResultEquals("$gt(a,B,nocase)", "")
self.assertScriptResultEquals("$gt(A,b,nocase)", "")
self.assertScriptResultEquals("$gt(B,a,nocase)", "1")
self.assertScriptResultEquals("$gt(b,A,nocase)", "1")
# Test unknown processing type
self.assertScriptResultEquals("$gt(2,1,unknown)", "")
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$gt: Wrong number of arguments for \$gt: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$gt()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$gt(1)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$gt(foo,bar,text,)")
def test_cmd_gte(self):
# Test with default processing
self.assertScriptResultEquals("$gte(10,9)", "1")
self.assertScriptResultEquals("$gte(10,10)", "1")
self.assertScriptResultEquals("$gte(10,11)", "")
self.assertScriptResultEquals("$gte(10.1,10)", "1")
self.assertScriptResultEquals("$gte(10.1,10.1)", "1")
self.assertScriptResultEquals("$gte(10.1,10.2)", "")
self.assertScriptResultEquals("$gte(a,b)", "")
self.assertScriptResultEquals("$gte(b,a)", "1")
self.assertScriptResultEquals("$gte(a,a)", "1")
self.assertScriptResultEquals("$gte(a,6)", "1")
self.assertScriptResultEquals("$gte(a,6.5)", "1")
self.assertScriptResultEquals("$gte(6,a)", "")
self.assertScriptResultEquals("$gte(6.5,a)", "")
# Test with "int" processing
self.assertScriptResultEquals("$gte(10,10.1,int)", "")
self.assertScriptResultEquals("$gte(10,10,int)", "1")
self.assertScriptResultEquals("$gte(10,4,int)", "1")
self.assertScriptResultEquals("$gte(6,4,int)", "1")
self.assertScriptResultEquals("$gte(6,7,int)", "")
self.assertScriptResultEquals("$gte(a,b,int)", "")
# Test with "float" processing
self.assertScriptResultEquals("$gte(10.2,10.1,float)", "1")
self.assertScriptResultEquals("$gte(10.2,10.2,float)", "1")
self.assertScriptResultEquals("$gte(6,4,float)", "1")
self.assertScriptResultEquals("$gte(10,10.1,float)", "")
self.assertScriptResultEquals("$gte(10.2,10.3,float)", "")
self.assertScriptResultEquals("$gte(6,7,float)", "")
self.assertScriptResultEquals("$gte(a,b,float)", "")
# Test date type arguments ("text" processing)
self.assertScriptResultEquals("$gte(2020-01-01,2020-01-02,text)", "")
self.assertScriptResultEquals("$gte(2020-01-02,2020-01-01,text)", "1")
self.assertScriptResultEquals("$gte(2020-01-01,2020-02,text)", "")
self.assertScriptResultEquals("$gte(2020-02,2020-01-01,text)", "1")
self.assertScriptResultEquals("$gte(2020-01-01,2020-01-01,text)", "1")
# Test text type arguments ("text" processing)
self.assertScriptResultEquals("$gte(abc,abcd,text)", "")
self.assertScriptResultEquals("$gte(abcd,abc,text)", "1")
self.assertScriptResultEquals("$gte(abc,ac,text)", "")
self.assertScriptResultEquals("$gte(ac,abc,text)", "1")
self.assertScriptResultEquals("$gte(abc,abc,text)", "1")
# Test with empty arguments (default processing)
self.assertScriptResultEquals("$gte(,1)", "")
self.assertScriptResultEquals("$gte(1,)", "1")
self.assertScriptResultEquals("$gte(,)", "1")
# Test with empty arguments ("int" processing)
self.assertScriptResultEquals("$gte(,1,int)", "")
self.assertScriptResultEquals("$gte(1,,int)", "")
self.assertScriptResultEquals("$gte(,,int)", "")
# Test with empty arguments ("float" processing)
self.assertScriptResultEquals("$gte(,1,float)", "")
self.assertScriptResultEquals("$gte(1,float)", "")
self.assertScriptResultEquals("$gte(,,float)", "")
# Test with empty arguments ("text" processing)
self.assertScriptResultEquals("$gte(,a,text)", "")
self.assertScriptResultEquals("$gte(a,,text)", "1")
self.assertScriptResultEquals("$gte(,,text)", "1")
# Test case sensitive arguments ("text" processing)
self.assertScriptResultEquals("$gte(A,a,text)", "")
self.assertScriptResultEquals("$gte(a,A,text)", "1")
# Test case insensitive arguments ("nocase" processing)
self.assertScriptResultEquals("$gte(a,B,nocase)", "")
self.assertScriptResultEquals("$gte(A,b,nocase)", "")
self.assertScriptResultEquals("$gte(B,a,nocase)", "1")
self.assertScriptResultEquals("$gte(b,A,nocase)", "1")
self.assertScriptResultEquals("$gte(a,A,nocase)", "1")
self.assertScriptResultEquals("$gte(A,a,nocase)", "1")
# Test unknown processing type
self.assertScriptResultEquals("$gte(2,1,unknown)", "")
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$gte: Wrong number of arguments for \$gte: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$gte()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$gte(1)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$gte(foo,bar,text,)")
def test_cmd_lt(self):
# Test with default processing
self.assertScriptResultEquals("$lt(10,4)", "")
self.assertScriptResultEquals("$lt(6,6)", "")
self.assertScriptResultEquals("$lt(6,7)", "1")
self.assertScriptResultEquals("$lt(6.5,4)", "")
self.assertScriptResultEquals("$lt(6.5,4.5)", "")
self.assertScriptResultEquals("$lt(6.5,6.5)", "")
self.assertScriptResultEquals("$lt(6.5,6.6)", "1")
self.assertScriptResultEquals("$lt(a,b)", "1")
self.assertScriptResultEquals("$lt(b,a)", "")
self.assertScriptResultEquals("$lt(a,6)", "")
self.assertScriptResultEquals("$lt(a,6.5)", "")
self.assertScriptResultEquals("$lt(6,a)", "1")
self.assertScriptResultEquals("$lt(6.5,a)", "1")
# Test with "int" processing
self.assertScriptResultEquals("$lt(4,6,int)", "1")
self.assertScriptResultEquals("$lt(4,6.1,int)", "")
self.assertScriptResultEquals("$lt(4,3,int)", "")
self.assertScriptResultEquals("$lt(4,4.1,int)", "")
self.assertScriptResultEquals("$lt(4.1,4.2,int)", "")
self.assertScriptResultEquals("$lt(4,4,int)", "")
self.assertScriptResultEquals("$lt(a,b,int)", "")
# Test with "float" processing
self.assertScriptResultEquals("$lt(4,4.1,float)", "1")
self.assertScriptResultEquals("$lt(4.1,4.2,float)", "1")
self.assertScriptResultEquals("$lt(4,6,float)", "1")
self.assertScriptResultEquals("$lt(4.2,4.1,float)", "")
self.assertScriptResultEquals("$lt(4.1,4.1,float)", "")
self.assertScriptResultEquals("$lt(a,b,float)", "")
# Test date type arguments ("text" processing)
self.assertScriptResultEquals("$lt(2020-01-01,2020-01-02,text)", "1")
self.assertScriptResultEquals("$lt(2020-01-02,2020-01-01,text)", "")
self.assertScriptResultEquals("$lt(2020-01-01,2020-02,text)", "1")
self.assertScriptResultEquals("$lt(2020-02,2020-01-01,text)", "")
self.assertScriptResultEquals("$lt(2020-01-01,2020-01-01,text)", "")
# Test text type arguments ("text" processing)
self.assertScriptResultEquals("$lt(abc,abcd,text)", "1")
self.assertScriptResultEquals("$lt(abcd,abc,text)", "")
self.assertScriptResultEquals("$lt(abc,ac,text)", "1")
self.assertScriptResultEquals("$lt(ac,abc,text)", "")
self.assertScriptResultEquals("$lt(abc,abc,text)", "")
# Test with empty arguments (default processing)
self.assertScriptResultEquals("$lt(,1)", "1")
self.assertScriptResultEquals("$lt(1,)", "")
self.assertScriptResultEquals("$lt(,)", "")
# Test with empty arguments ("int" processing)
self.assertScriptResultEquals("$lt(,1,int)", "")
self.assertScriptResultEquals("$lt(1,,int)", "")
self.assertScriptResultEquals("$lt(,,int)", "")
# Test with empty arguments ("float" processing)
self.assertScriptResultEquals("$lt(,1,float)", "")
self.assertScriptResultEquals("$lt(1,,float)", "")
self.assertScriptResultEquals("$lt(,,float)", "")
# Test with empty arguments ("text" processing)
self.assertScriptResultEquals("$lt(,a,text)", "1")
self.assertScriptResultEquals("$lt(a,,text)", "")
self.assertScriptResultEquals("$lt(,,text)", "")
# Test case sensitive arguments ("text" processing)
self.assertScriptResultEquals("$lt(A,a,text)", "1")
self.assertScriptResultEquals("$lt(a,A,text)", "")
# Test case insensitive arguments ("nocase" processing)
self.assertScriptResultEquals("$lt(a,B,nocase)", "1")
self.assertScriptResultEquals("$lt(A,b,nocase)", "1")
self.assertScriptResultEquals("$lt(B,a,nocase)", "")
self.assertScriptResultEquals("$lt(b,A,nocase)", "")
# Test unknown processing type
self.assertScriptResultEquals("$lt(1,2,unknown)", "")
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$lt: Wrong number of arguments for \$lt: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$lt()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$lt(1)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$lt(foo,bar,text,)")
def test_cmd_lte(self):
# Test with default processing
self.assertScriptResultEquals("$lte(10,4)", "")
self.assertScriptResultEquals("$lte(6,6)", "1")
self.assertScriptResultEquals("$lte(6,7)", "1")
self.assertScriptResultEquals("$lte(6.5,4)", "")
self.assertScriptResultEquals("$lte(6.5,4.5)", "")
self.assertScriptResultEquals("$lte(6.5,6.5)", "1")
self.assertScriptResultEquals("$lte(6.5,6.6)", "1")
self.assertScriptResultEquals("$lte(a,b)", "1")
self.assertScriptResultEquals("$lte(a,a)", "1")
self.assertScriptResultEquals("$lte(b,a)", "")
self.assertScriptResultEquals("$lte(a,6)", "")
self.assertScriptResultEquals("$lte(a,6.5)", "")
self.assertScriptResultEquals("$lte(6,a)", "1")
self.assertScriptResultEquals("$lte(6.5,a)", "1")
# Test with "int" processing
self.assertScriptResultEquals("$lte(10,10,int)", "1")
self.assertScriptResultEquals("$lte(10.1,10.2,int)", "")
self.assertScriptResultEquals("$lte(4,10,int)", "1")
self.assertScriptResultEquals("$lte(4,3,int)", "")
self.assertScriptResultEquals("$lte(a,b,int)", "")
# Test with "float" processing
self.assertScriptResultEquals("$lte(10,10,float)", "1")
self.assertScriptResultEquals("$lte(10.1,10.1,float)", "1")
self.assertScriptResultEquals("$lte(10.1,10.2,float)", "1")
self.assertScriptResultEquals("$lte(10.2,10.1,float)", "")
self.assertScriptResultEquals("$lte(4,3,float)", "")
self.assertScriptResultEquals("$lte(a,b,float)", "")
# Test date type arguments ("text" processing)
self.assertScriptResultEquals("$lte(2020-01-01,2020-01-02,text)", "1")
self.assertScriptResultEquals("$lte(2020-01-02,2020-01-01,text)", "")
self.assertScriptResultEquals("$lte(2020-01-01,2020-02,text)", "1")
self.assertScriptResultEquals("$lte(2020-02,2020-01-01,text)", "")
self.assertScriptResultEquals("$lte(2020-01-01,2020-01-01,text)", "1")
# Test text type arguments ("text" processing)
self.assertScriptResultEquals("$lte(abc,abcd,text)", "1")
self.assertScriptResultEquals("$lte(abcd,abc,text)", "")
self.assertScriptResultEquals("$lte(abc,ac,text)", "1")
self.assertScriptResultEquals("$lte(ac,abc,text)", "")
self.assertScriptResultEquals("$lte(abc,abc,text)", "1")
# Test with empty arguments (default processing)
self.assertScriptResultEquals("$lte(,1)", "1")
self.assertScriptResultEquals("$lte(1,)", "")
self.assertScriptResultEquals("$lte(,)", "1")
# Test with empty arguments ("int" processing)
self.assertScriptResultEquals("$lte(,1,int)", "")
self.assertScriptResultEquals("$lte(1,,int)", "")
self.assertScriptResultEquals("$lte(,,int)", "")
# Test with empty arguments ("float" processing)
self.assertScriptResultEquals("$lte(,1,float)", "")
self.assertScriptResultEquals("$lte(1,,float)", "")
self.assertScriptResultEquals("$lte(,,float)", "")
# Test with empty arguments ("text" processing)
self.assertScriptResultEquals("$lte(,a,text)", "1")
self.assertScriptResultEquals("$lte(a,,text)", "")
self.assertScriptResultEquals("$lte(,,text)", "1")
# Test case sensitive arguments ("text" processing)
self.assertScriptResultEquals("$lte(A,a,text)", "1")
self.assertScriptResultEquals("$lte(a,A,text)", "")
# Test case insensitive arguments ("nocase" processing)
self.assertScriptResultEquals("$lte(a,B,nocase)", "1")
self.assertScriptResultEquals("$lte(A,b,nocase)", "1")
self.assertScriptResultEquals("$lte(B,a,nocase)", "")
self.assertScriptResultEquals("$lte(b,A,nocase)", "")
self.assertScriptResultEquals("$lte(a,A,nocase)", "1")
self.assertScriptResultEquals("$lte(A,a,nocase)", "1")
# Test unknown processing type
self.assertScriptResultEquals("$lte(1,2,unknown)", "")
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$lte: Wrong number of arguments for \$lte: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$lte()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$lte(1)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$lte(foo,bar,text,)")
def test_cmd_len(self):
self.assertScriptResultEquals("$len(abcdefg)", "7")
self.assertScriptResultEquals("$len(0)", "1")
self.assertScriptResultEquals("$len()", "0")
def test_cmd_firstalphachar(self):
self.assertScriptResultEquals("$firstalphachar(abc)", "A")
self.assertScriptResultEquals("$firstalphachar(Abc)", "A")
self.assertScriptResultEquals("$firstalphachar(1abc)", "#")
self.assertScriptResultEquals("$firstalphachar(...abc)", "#")
self.assertScriptResultEquals("$firstalphachar(1abc,_)", "_")
self.assertScriptResultEquals("$firstalphachar(...abc,_)", "_")
self.assertScriptResultEquals("$firstalphachar()", "#")
self.assertScriptResultEquals("$firstalphachar(,_)", "_")
self.assertScriptResultEquals("$firstalphachar( abc)", "#")
def test_cmd_initials(self):
self.assertScriptResultEquals("$initials(Abc def Ghi)", "AdG")
self.assertScriptResultEquals("$initials(Abc #def Ghi)", "AG")
self.assertScriptResultEquals("$initials(Abc 1def Ghi)", "AG")
self.assertScriptResultEquals("$initials(Abc)", "A")
self.assertScriptResultEquals("$initials()", "")
def test_cmd_firstwords(self):
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,11)", "Abc Def Ghi")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,12)", "Abc Def Ghi")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,7)", "Abc Def")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,8)", "Abc Def")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,6)", "Abc")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,0)", "")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,NaN)", "")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,)", "")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,-2)", "Abc Def")
self.assertScriptResultEquals("$firstwords(Abc Def Ghi,-50)", "")
def test_cmd_startswith(self):
self.assertScriptResultEquals("$startswith(abc,a)", "1")
self.assertScriptResultEquals("$startswith(abc,abc)", "1")
self.assertScriptResultEquals("$startswith(abc,)", "1")
self.assertScriptResultEquals("$startswith(abc,b)", "")
self.assertScriptResultEquals("$startswith(abc,Ab)", "")
def test_cmd_endswith(self):
self.assertScriptResultEquals("$endswith(abc,c)", "1")
self.assertScriptResultEquals("$endswith(abc,abc)", "1")
self.assertScriptResultEquals("$endswith(abc,)", "1")
self.assertScriptResultEquals("$endswith(abc,b)", "")
self.assertScriptResultEquals("$endswith(abc,bC)", "")
def test_cmd_truncate(self):
self.assertScriptResultEquals("$truncate(abcdefg,0)", "")
self.assertScriptResultEquals("$truncate(abcdefg,7)", "abcdefg")
self.assertScriptResultEquals("$truncate(abcdefg,3)", "abc")
self.assertScriptResultEquals("$truncate(abcdefg,10)", "abcdefg")
self.assertScriptResultEquals("$truncate(abcdefg,)", "abcdefg")
self.assertScriptResultEquals("$truncate(abcdefg,NaN)", "abcdefg")
def test_cmd_copy(self):
context = Metadata()
tagsToCopy = ["tag1", "tag2"]
context["source"] = tagsToCopy
context["target"] = ["will", "be", "overwritten"]
self.parser.eval("$copy(target,source)", context)
self.assertEqual(self.parser.context.getall("target"), tagsToCopy)
def _eval_and_check_copymerge(self, context, expected):
self.parser.eval("$copymerge(target,source)", context)
self.assertEqual(self.parser.context.getall("target"), expected)
def test_cmd_copymerge_notarget(self):
context = Metadata()
tagsToCopy = ["tag1", "tag2"]
context["source"] = tagsToCopy
self._eval_and_check_copymerge(context, tagsToCopy)
def test_cmd_copymerge_nosource(self):
context = Metadata()
target = ["tag1", "tag2"]
context["target"] = target
self._eval_and_check_copymerge(context, target)
def test_cmd_copymerge_removedupes(self):
context = Metadata()
context["target"] = ["tag1", "tag2", "tag1"]
context["source"] = ["tag2", "tag3", "tag2"]
self._eval_and_check_copymerge(context, ["tag1", "tag2", "tag3"])
def test_cmd_copymerge_nonlist(self):
context = Metadata()
context["target"] = "targetval"
context["source"] = "sourceval"
self._eval_and_check_copymerge(context, ["targetval", "sourceval"])
def test_cmd_copymerge_empty_keepdupes(self):
context = Metadata()
context["target"] = ["tag1", "tag2", "tag1"]
context["source"] = ["tag2", "tag3", "tag2"]
self.parser.eval("$copymerge(target,source,)", context)
self.assertEqual(self.parser.context.getall("target"), ["tag1", "tag2", "tag3"])
def test_cmd_copymerge_keepdupes(self):
context = Metadata()
context["target"] = ["tag1", "tag2", "tag1"]
context["source"] = ["tag2", "tag3", "tag2"]
self.parser.eval("$copymerge(target,source,keep)", context)
self.assertEqual(self.parser.context.getall("target"), ["tag1", "tag2", "tag1", "tag2", "tag3", "tag2"])
def test_cmd_copymerge_nonlist_keepdupes(self):
context = Metadata()
context["target"] = "targetval"
context["source"] = "targetval"
self.parser.eval("$copymerge(target,source,keep)", context)
self.assertEqual(self.parser.context.getall("target"), ["targetval", "targetval"])
def test_cmd_eq_any(self):
self.assertScriptResultEquals("$eq_any(abc,def,ghi,jkl)", "")
self.assertScriptResultEquals("$eq_any(abc,def,ghi,jkl,abc)", "1")
def test_cmd_ne_all(self):
self.assertScriptResultEquals("$ne_all(abc,def,ghi,jkl)", "1")
self.assertScriptResultEquals("$ne_all(abc,def,ghi,jkl,abc)", "")
def test_cmd_eq_all(self):
self.assertScriptResultEquals("$eq_all(abc,abc,abc,abc)", "1")
self.assertScriptResultEquals("$eq_all(abc,abc,def,ghi)", "")
def test_cmd_ne_any(self):
self.assertScriptResultEquals("$ne_any(abc,abc,abc,abc)", "")
self.assertScriptResultEquals("$ne_any(abc,abc,def,ghi)", "1")
def test_cmd_title(self):
self.assertScriptResultEquals("$title(abc Def g)", "Abc Def G")
self.assertScriptResultEquals("$title(Abc Def G)", "Abc Def G")
self.assertScriptResultEquals("$title(abc def g)", "Abc Def G")
self.assertScriptResultEquals("$title(#1abc 4def - g)", "#1abc 4def - G")
self.assertScriptResultEquals(r"$title(abcd \(efg hi jkl mno\))", "Abcd (Efg Hi Jkl Mno)")
self.assertScriptResultEquals("$title(...abcd)", "...Abcd")
self.assertScriptResultEquals("$title(a)", "A")
self.assertScriptResultEquals("$title(’a)", "’a")
self.assertScriptResultEquals("$title('a)", "'a")
self.assertScriptResultEquals("$title(l'a)", "L'a")
self.assertScriptResultEquals("$title(2'a)", "2'A")
self.assertScriptResultEquals(r"$title(%empty%)", "")
# Tests wrong number of arguments
areg = r"^\d+:\d+:\$title: Wrong number of arguments for \$title: Expected exactly 1, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$title()")
def test_cmd_swapprefix(self):
self.assertScriptResultEquals("$swapprefix(A stitch in time)", "stitch in time, A")
self.assertScriptResultEquals("$swapprefix(The quick brown fox)", "quick brown fox, The")
self.assertScriptResultEquals("$swapprefix(How now brown cow)", "How now brown cow")
self.assertScriptResultEquals("$swapprefix(When the red red robin)", "When the red red robin")
self.assertScriptResultEquals("$swapprefix(A stitch in time,How,When,Who)", "A stitch in time")
self.assertScriptResultEquals("$swapprefix(The quick brown fox,How,When,Who)", "The quick brown fox")
self.assertScriptResultEquals("$swapprefix(How now brown cow,How,When,Who)", "now brown cow, How")
self.assertScriptResultEquals("$swapprefix(When the red red robin,How,When,Who)", "the red red robin, When")
def test_cmd_delprefix(self):
self.assertScriptResultEquals("$delprefix(A stitch in time)", "stitch in time")
self.assertScriptResultEquals("$delprefix(The quick brown fox)", "quick brown fox")
self.assertScriptResultEquals("$delprefix(How now brown cow)", "How now brown cow")
self.assertScriptResultEquals("$delprefix(When the red red robin)", "When the red red robin")
self.assertScriptResultEquals("$delprefix(A stitch in time,How,When,Who)", "A stitch in time")
self.assertScriptResultEquals("$delprefix(The quick brown fox,How,When,Who)", "The quick brown fox")
self.assertScriptResultEquals("$delprefix(How now brown cow,How,When,Who)", "now brown cow")
self.assertScriptResultEquals("$delprefix(When the red red robin,How,When,Who)", "the red red robin")
def test_default_filenaming(self):
context = Metadata()
context['albumartist'] = 'albumartist'
context['artist'] = 'artist'
context['album'] = 'album'
context['totaldiscs'] = 2
context['discnumber'] = 1
context['tracknumber'] = 8
context['title'] = 'title'
result = self.parser.eval(DEFAULT_FILE_NAMING_FORMAT, context)
self.assertEqual(result, 'albumartist/\nalbum/\n1-08 title')
context['~multiartist'] = '1'
result = self.parser.eval(DEFAULT_FILE_NAMING_FORMAT, context)
self.assertEqual(result, 'albumartist/\nalbum/\n1-08 artist - title')
def test_default_NAT_filenaming(self):
context = Metadata()
context['artist'] = 'artist'
context['album'] = '[standalone recordings]'
context['title'] = 'title'
result = self.parser.eval(DEFAULT_FILE_NAMING_FORMAT, context)
self.assertEqual(result, 'artist/\n\ntitle')
def test_cmd_with_not_arguments(self):
def func_noargstest(parser):
return ""
register_script_function(func_noargstest, "noargstest")
self.parser.eval("$noargstest()")
def test_cmd_with_wrong_argcount_or(self):
# $or() requires at least 2 arguments
areg = r"^\d+:\d+:\$or: Wrong number of arguments for \$or: Expected at least 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval('$or(0)')
def test_cmd_with_wrong_argcount_eq(self):
# $eq() requires exactly 2 arguments
areg = r"^\d+:\d+:\$eq: Wrong number of arguments for \$eq: Expected exactly 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval('$eq(0)')
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval('$eq(0,0,0)')
def test_cmd_with_wrong_argcount_if(self):
areg = r"^\d+:\d+:\$if: Wrong number of arguments for \$if: Expected between 2 and 3, "
# $if() requires 2 or 3 arguments
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval('$if(1)')
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval('$if(1,a,b,c)')
def test_cmd_unset_simple(self):
context = Metadata()
context['title'] = 'Foo'
context['album'] = 'Foo'
context['artist'] = 'Foo'
self.parser.eval("$unset(album)", context)
self.assertNotIn('album', context)
def test_cmd_unset_prefix(self):
context = Metadata()
context['title'] = 'Foo'
context['~rating'] = '4'
self.parser.eval("$unset(_rating)", context)
self.assertNotIn('~rating', context)
def test_cmd_unset_multi(self):
context = Metadata()
context['performer:foo'] = 'Foo'
context['performer:bar'] = 'Foo'
self.parser.eval("$unset(performer:*)", context)
self.assertNotIn('performer:bar', context)
self.assertNotIn('performer:foo', context)
def test_cmd_unset(self):
context = Metadata()
context['title'] = 'Foo'
self.parser.eval("$unset(title)", context)
self.assertNotIn('title', context)
self.assertNotIn('title', context.deleted_tags)
def test_cmd_delete(self):
context = Metadata()
context['title'] = 'Foo'
self.parser.eval("$delete(title)", context)
self.assertNotIn('title', context)
self.assertIn('title', context.deleted_tags)
def test_cmd_inmulti(self):
context = Metadata()
# Test with single-value string
context["foo"] = "First:A; Second:B; Third:C"
# Tests with $in for comparison purposes
self.assertScriptResultEquals("$in(%foo%,Second:B)", "1", context)
self.assertScriptResultEquals("$in(%foo%,irst:A; Second:B; Thi)", "1", context)
self.assertScriptResultEquals("$in(%foo%,First:A; Second:B; Third:C)", "1", context)
# Base $inmulti tests
self.assertScriptResultEquals("$inmulti(%foo%,Second:B)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,irst:A; Second:B; Thi)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,First:A; Second:B; Third:C)", "1", context)
# Test separator override but with existing separator - results should be same as base
self.assertScriptResultEquals("$inmulti(%foo%,Second:B,; )", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,irst:A; Second:B; Thi,; )", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,First:A; Second:B; Third:C,; )", "1", context)
# Test separator override
self.assertScriptResultEquals("$inmulti(%foo%,First:A,:)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,Second:B,:)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,Third:C,:)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,First,:)", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,A; Second,:)", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,B; Third,:)", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,C,:)", "1", context)
# Test no separator
self.assertScriptResultEquals("$inmulti(%foo%,First:A; Second:B; Third:C,)", "1", context)
# Test with multi-values
context["foo"] = ["First:A", "Second:B", "Third:C"]
# Tests with $in for comparison purposes
self.assertScriptResultEquals("$in(%foo%,Second:B)", "1", context)
self.assertScriptResultEquals("$in(%foo%,irst:A; Second:B; Thi)", "1", context)
self.assertScriptResultEquals("$in(%foo%,First:A; Second:B; Third:C)", "1", context)
# Base $inmulti tests
self.assertScriptResultEquals("$inmulti(%foo%,Second:B)", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,irst:A; Second:B; Thi)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,First:A; Second:B; Third:C)", "", context)
# Test separator override but with existing separator - results should be same as base
self.assertScriptResultEquals("$inmulti(%foo%,Second:B,; )", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,irst:A; Second:B; Thi,; )", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,First:A; Second:B; Third:C,; )", "", context)
# Test separator override
self.assertScriptResultEquals("$inmulti(%foo%,First:A,:)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,Second:B,:)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,Third:C,:)", "", context)
self.assertScriptResultEquals("$inmulti(%foo%,First,:)", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,A; Second,:)", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,B; Third,:)", "1", context)
self.assertScriptResultEquals("$inmulti(%foo%,C,:)", "1", context)
# Test no separator
self.assertScriptResultEquals("$inmulti(%foo%,First:A; Second:B; Third:C,)", "1", context)
def test_cmd_lenmulti(self):
context = Metadata()
context["foo"] = "First:A; Second:B; Third:C"
context["bar"] = ["First:A", "Second:B", "Third:C"]
# Tests with $len for comparison purposes
self.assertScriptResultEquals("$len(%foo%)", "26", context)
self.assertScriptResultEquals("$len(%bar%)", "26", context)
# Base $lenmulti tests
self.assertScriptResultEquals("$lenmulti(%foo%)", "1", context)
self.assertScriptResultEquals("$lenmulti(%bar%)", "3", context)
self.assertScriptResultEquals("$lenmulti(%foo%.)", "3", context)
# Test separator override but with existing separator - results should be same as base
self.assertScriptResultEquals("$lenmulti(%foo%,; )", "1", context)
self.assertScriptResultEquals("$lenmulti(%bar%,; )", "3", context)
self.assertScriptResultEquals("$lenmulti(%foo%.,; )", "3", context)
# Test separator override
self.assertScriptResultEquals("$lenmulti(%foo%,:)", "4", context)
self.assertScriptResultEquals("$lenmulti(%bar%,:)", "4", context)
self.assertScriptResultEquals("$lenmulti(%foo%.,:)", "4", context)
# Test no separator
self.assertScriptResultEquals("$lenmulti(%foo%,)", "1", context)
self.assertScriptResultEquals("$lenmulti(%bar%,)", "1", context)
# Test blank name
context["baz"] = ""
self.assertScriptResultEquals("$lenmulti(%baz%)", "0", context)
self.assertScriptResultEquals("$lenmulti(%baz%,:)", "0", context)
# Test empty multi-value
context["baz"] = []
self.assertScriptResultEquals("$lenmulti(%baz%)", "0", context)
self.assertScriptResultEquals("$lenmulti(%baz%,:)", "0", context)
# Test empty multi-value elements
context["baz"] = ["one", "", "three"]
self.assertScriptResultEquals("$lenmulti(%baz%)", "3", context)
# Test missing name
self.assertScriptResultEquals("$lenmulti(,)", "0", context)
self.assertScriptResultEquals("$lenmulti(,:)", "0", context)
def test_cmd_performer(self):
context = Metadata()
context['performer:guitar'] = 'Foo1'
context['performer:rhythm-guitar'] = ['Foo2', 'Foo3']
context['performer:drums'] = 'Drummer'
# Matches pattern
result = self.parser.eval("$performer(guitar)", context=context)
self.assertEqual({'Foo1', 'Foo2', 'Foo3'}, set(result.split(', ')))
# Empty pattern returns all performers
result = self.parser.eval("$performer()", context=context)
self.assertEqual({'Foo1', 'Foo2', 'Foo3', 'Drummer'}, set(result.split(', ')))
self.assertScriptResultEquals("$performer(perf)", "", context)
def test_cmd_performer_regex(self):
context = Metadata()
context['performer:guitar'] = 'Foo1'
context['performer:guitars'] = 'Foo2'
context['performer:rhythm-guitar'] = 'Foo3'
context['performer:drums (drum kit)'] = 'Drummer'
result = self.parser.eval(r"$performer(/^guitar/)", context=context)
self.assertEqual({'Foo1', 'Foo2'}, set(result.split(', ')))
result = self.parser.eval(r"$performer(/^guitar\$/)", context=context)
self.assertEqual({'Foo1'}, set(result.split(', ')))
def test_cmd_performer_regex_invalid(self):
context = Metadata()
context['performer:drums (drum kit)'] = 'Drummer'
self.assertScriptResultEquals(r"$performer(/drums \(/)", "", context)
self.assertScriptResultEquals(r"$performer(drums \()", "Drummer", context)
def test_cmd_performer_regex_ignore_case(self):
context = Metadata()
context['performer:guitar'] = 'Foo1'
context['performer:GUITARS'] = 'Foo2'
context['performer:rhythm-guitar'] = 'Foo3'
result = self.parser.eval(r"$performer(/^guitars?/i)", context=context)
self.assertEqual({'Foo1', 'Foo2'}, set(result.split(', ')))
def test_cmd_performer_custom_join(self):
context = Metadata()
context['performer:guitar'] = 'Foo1'
context['performer:rhythm-guitar'] = 'Foo2'
context['performer:drums'] = 'Drummer'
result = self.parser.eval("$performer(guitar, / )", context=context)
self.assertEqual({'Foo1', 'Foo2'}, set(result.split(' / ')))
def test_cmd_performer_multi_colons(self):
context = Metadata()
context['performer:CV:松井栞里'] = '仁奈(CV:大出千夏)'
result = self.parser.eval("$performer(CV:松井栞里)", context=context)
self.assertEqual('仁奈(CV:大出千夏)', result)
def test_cmd_matchedtracks(self):
file = MagicMock()
file.parent_item.album.get_num_matched_tracks.return_value = 42
self.assertScriptResultEquals("$matchedtracks()", "42", file=file)
self.assertScriptResultEquals("$matchedtracks()", "0")
# The following only is possible for backward compatibility, arg is unused
self.assertScriptResultEquals("$matchedtracks(arg)", "0")
def test_cmd_matchedtracks_with_cluster(self):
file = MagicMock()
cluster = Cluster(name="Test")
cluster.files.append(file)
file.parent_item = cluster
self.assertScriptResultEquals("$matchedtracks()", "0", file=file)
def test_cmd_is_complete(self):
file = MagicMock()
file.parent_item.album.is_complete.return_value = True
self.assertScriptResultEquals("$is_complete()", "1", file=file)
file.parent_item.album.is_complete.return_value = False
self.assertScriptResultEquals("$is_complete()", "", file=file)
self.assertScriptResultEquals("$is_complete()", "")
def test_cmd_is_complete_with_cluster(self):
file = MagicMock()
cluster = Cluster(name="Test")
cluster.files.append(file)
file.parent_item = cluster
self.assertScriptResultEquals("$is_complete()", "", file=file)
def test_cmd_is_video(self):
context = Metadata({'~video': '1'})
self.assertScriptResultEquals("$is_video()", "1", context=context)
context = Metadata({'~video': '0'})
self.assertScriptResultEquals("$is_video()", "", context=context)
self.assertScriptResultEquals("$is_video()", "")
def test_cmd_is_audio(self):
context = Metadata({'~video': '1'})
self.assertScriptResultEquals("$is_audio()", "", context=context)
context = Metadata({'~video': '0'})
self.assertScriptResultEquals("$is_audio()", "1", context=context)
self.assertScriptResultEquals("$is_audio()", "1")
def test_required_kwonly_parameters(self):
def func(a, *, required_kwarg):
pass
with self.assertRaises(TypeError,
msg="Functions with required keyword-only parameters are not supported"):
register_script_function(func)
@staticmethod
def test_optional_kwonly_parameters():
def func(a, *, optional_kwarg=1):
pass
register_script_function(func)
def test_char_escape(self):
self.assertScriptResultEquals(r"\n\t\$\%\(\)\,\\", "\n\t$%(),\\")
def test_char_escape_unexpected_char(self):
self.assertRaises(ScriptSyntaxError, self.parser.eval, r'\x')
def test_char_escape_end_of_file(self):
self.assertRaises(ScriptEndOfFile, self.parser.eval, 'foo\\')
def test_raise_unknown_function(self):
self.assertRaises(ScriptUnknownFunction, self.parser.eval, '$unknownfn()')
def test_raise_end_of_file(self):
self.assertRaises(ScriptEndOfFile, self.parser.eval, '$noop(')
self.assertRaises(ScriptEndOfFile, self.parser.eval, '%var')
def test_raise_syntax_error(self):
self.assertRaises(ScriptSyntaxError, self.parser.eval, '%var()%')
self.assertRaises(ScriptSyntaxError, self.parser.eval, '$noop(()')
self.assertRaises(ScriptSyntaxError, self.parser.eval, r'\x')
def test_cmd_find(self):
context = Metadata()
context["foo"] = "First:A; Second:B; Third:C"
context["bar"] = ["First:A", "Second:B", "Third:C"]
context["baz"] = "Second"
context["err"] = "Forth"
# Tests with context
self.assertScriptResultEquals("$find(%foo%,%baz%)", "9", context)
self.assertScriptResultEquals("$find(%bar%,%baz%)", "9", context)
self.assertScriptResultEquals("$find(%foo%,%bar%)", "0", context)
self.assertScriptResultEquals("$find(%bar%,%foo%)", "0", context)
self.assertScriptResultEquals("$find(%foo%,%err%)", "", context)
# Tests with static input
self.assertScriptResultEquals("$find(abcdef,c)", "2", context)
self.assertScriptResultEquals("$find(abcdef,cd)", "2", context)
self.assertScriptResultEquals("$find(abcdef,g)", "", context)
# Tests ends of string
self.assertScriptResultEquals("$find(abcdef,a)", "0", context)
self.assertScriptResultEquals("$find(abcdef,ab)", "0", context)
self.assertScriptResultEquals("$find(abcdef,f)", "5", context)
self.assertScriptResultEquals("$find(abcdef,ef)", "4", context)
# Tests case sensitivity
self.assertScriptResultEquals("$find(abcdef,C)", "", context)
# Tests no characters processed as wildcards
self.assertScriptResultEquals("$find(abcdef,.f)", "", context)
self.assertScriptResultEquals("$find(abcdef,?f)", "", context)
self.assertScriptResultEquals("$find(abcdef,*f)", "", context)
self.assertScriptResultEquals("$find(abc.ef,cde)", "", context)
self.assertScriptResultEquals("$find(abc?ef,cde)", "", context)
self.assertScriptResultEquals("$find(abc*ef,cde)", "", context)
# Tests missing inputs
self.assertScriptResultEquals("$find(,c)", "", context)
self.assertScriptResultEquals("$find(abcdef,)", "0", context)
# Tests wrong number of arguments
areg = r"^\d+:\d+:\$find: Wrong number of arguments for \$find: Expected exactly 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$find(abcdef)")
def test_cmd_reverse(self):
context = Metadata()
context["foo"] = "One; Two; Three"
context["bar"] = ["One", "Two", "Three"]
# Tests with context
self.assertScriptResultEquals("$reverse(%foo%)", "eerhT ;owT ;enO", context)
self.assertScriptResultEquals("$reverse(%bar%)", "eerhT ;owT ;enO", context)
# Tests with static input
self.assertScriptResultEquals("$reverse(One; Two; Three)", "eerhT ;owT ;enO", context)
# Tests with missing input
areg = r"^\d+:\d+:\$reverse: Wrong number of arguments for \$reverse: Expected exactly 1, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$reverse()")
def test_cmd_substr(self):
context = Metadata()
context["foo"] = "One; Two; Three"
context["bar"] = ["One", "Two", "Three"]
context["start"] = '5'
context["end"] = '9'
# Tests with context
self.assertScriptResultEquals("$substr(%foo%,%start%,%end%)", "Two;", context)
self.assertScriptResultEquals("$substr(%bar%,%start%,%end%)", "Two;", context)
# Tests with static input
self.assertScriptResultEquals("$substr(One; Two; Three,5,9)", "Two;", context)
# Tests ends of string
self.assertScriptResultEquals("$substr(One; Two; Three,0,4)", "One;", context)
self.assertScriptResultEquals("$substr(One; Two; Three,10,15)", "Three", context)
# Tests negative index inputs
self.assertScriptResultEquals("$substr(One; Two; Three,-15,4)", "One;", context)
self.assertScriptResultEquals("$substr(One; Two; Three,-5,15)", "Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,-10,8)", "Two", context)
self.assertScriptResultEquals("$substr(One; Two; Three,5,-7)", "Two", context)
# Tests overrun ends of string
self.assertScriptResultEquals("$substr(One; Two; Three,10,25)", "Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,-25,4)", "One;", context)
self.assertScriptResultEquals("$substr(One; Two; Three,-5,25)", "Three", context)
# Tests invalid ranges (end < start, end = start)
self.assertScriptResultEquals("$substr(One; Two; Three,10,9)", "", context)
self.assertScriptResultEquals("$substr(One; Two; Three,10,10)", "", context)
# Tests invalid index inputs
self.assertScriptResultEquals("$substr(One; Two; Three,10-1,4)", "One;", context)
self.assertScriptResultEquals("$substr(One; Two; Three,10,4+2)", "Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,10-1,4+2)", "One; Two; Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,a,4)", "One;", context)
self.assertScriptResultEquals("$substr(One; Two; Three,0,b)", "One; Two; Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,a,b)", "One; Two; Three", context)
# # Tests with missing input
self.assertScriptResultEquals("$substr(One; Two; Three,,4)", "One;", context)
self.assertScriptResultEquals("$substr(One; Two; Three,10)", "Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,10,)", "Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,)", "One; Two; Three", context)
self.assertScriptResultEquals("$substr(One; Two; Three,,)", "One; Two; Three", context)
# Tests with missing input
areg = r"^\d+:\d+:\$substr: Wrong number of arguments for \$substr: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$substr()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$substr(abc)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$substr(abc,0,,)")
def test_cmd_getmulti(self):
context = Metadata()
context["foo"] = ["First:A", "Second:B", "Third:C"]
context["index"] = "1"
# Tests with context
self.assertScriptResultEquals("$getmulti(%foo%,%index%)", "Second:B", context)
# Tests with static inputs
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,0)", "First:A", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,1)", "Second:B", context)
# Tests separator override
self.assertScriptResultEquals("$getmulti(%foo%,1,:)", "A; Second", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,1,:)", "A; Second", context)
# Tests negative index values
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,-1)", "Third:C", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,-2)", "Second:B", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,-3)", "First:A", context)
# Tests out of range index values
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,10)", "", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,-4)", "", context)
# Tests invalid index values
self.assertScriptResultEquals("$getmulti(,0)", "", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,)", "", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,10+1)", "", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,a)", "", context)
# Tests with missing inputs
self.assertScriptResultEquals("$getmulti(,0)", "", context)
self.assertScriptResultEquals("$getmulti(First:A; Second:B; Third:C,)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$getmulti: Wrong number of arguments for \$getmulti: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$getmulti()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$getmulti(abc)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$getmulti(abc,0,; ,extra)")
def test_cmd_foreach(self):
context = Metadata()
context["foo"] = "First:A; Second:B; Third:C"
context["bar"] = ["First:A", "Second:B", "Third:C"]
foo_output = "Output: 1=First:A; Second:B; Third:C"
loop_output = "Output: 1=First:A 2=Second:B 3=Third:C"
alternate_output = "Output: 1=First 2=A; Second 3=B; Third 4=C"
# Tests with context
context["output"] = "Output:"
self.assertScriptResultEquals("$foreach(%foo%,$set(output,%output% %_loop_count%=%_loop_value%))%output%", foo_output, context)
context["output"] = "Output:"
self.assertScriptResultEquals("$foreach(%bar%,$set(output,%output% %_loop_count%=%_loop_value%))%output%", loop_output, context)
# Tests with static inputs
context["output"] = "Output:"
self.assertScriptResultEquals("$foreach(First:A; Second:B; Third:C,$set(output,%output% %_loop_count%=%_loop_value%))%output%", loop_output, context)
# Tests with missing inputs
context["output"] = "Output:"
self.assertScriptResultEquals("$foreach(,$set(output,%output% %_loop_count%=%_loop_value%))%output%", "Output:", context)
context["output"] = "Output:"
self.assertScriptResultEquals("$foreach(First:A; Second:B; Third:C,)%output%", "Output:", context)
# Tests with separator override
context["output"] = "Output:"
self.assertScriptResultEquals("$foreach(First:A; Second:B; Third:C,$set(output,%output% %_loop_count%=%_loop_value%),:)%output%", alternate_output, context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$foreach: Wrong number of arguments for \$foreach: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$foreach()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$foreach(abc;def)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$foreach(abc:def,$noop(),:,extra)")
def test_cmd_while(self):
context = Metadata()
context["max_value"] = '5'
loop_output = "Output: 1 2 3 4 5"
# Tests with context
context["output"] = "Output:"
self.assertScriptResultEquals("$set(_loop_count,1)$while($lt(%_loop_count%,%max_value%,int),$set(output,%output% %_loop_count%))%output%", loop_output, context)
# Tests with static inputs
context["output"] = "Output:"
self.assertScriptResultEquals("$set(_loop_count,1)$while($lt(%_loop_count%,5,int),$set(output,%output% %_loop_count%))%output%", loop_output, context)
# Tests with invalid conditional input
context["output"] = "Output:"
self.assertScriptResultEquals("$while($lt(%_loop_count%,5,int),$set(output,%output% %_loop_count%))%output%", "Output:", context)
# Tests with forced conditional (runaway condition)
context["output"] = "Output:"
self.assertScriptResultEquals("$while(1,$set(output,%output% %_loop_count%))$right(%output%,4)", "1000", context)
context["output"] = "Output:"
self.assertScriptResultEquals("$while(0,$set(output,%output% %_loop_count%))$right(%output%,4)", "1000", context)
# Tests with missing inputs
context["output"] = "Output:"
self.assertScriptResultEquals("$while($lt(%_loop_count%,5,int),)%output%", "Output:", context)
context["output"] = "Output:"
self.assertScriptResultEquals("$while(,$set(output,%output% %_loop_count%))%output%", "Output:", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$while: Wrong number of arguments for \$while: Expected exactly 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$while()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$while(a)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$while(a,$noop(),extra)")
def test_cmd_map(self):
context = Metadata()
foo_output = "1=FIRST:A; SECOND:B; THIRD:C"
loop_output = "1=FIRST:A; 2=SECOND:B; 3=THIRD:C"
alternate_output = "1=FIRST:2=A; SECOND:3=B; THIRD:4=C"
# Tests with context
context["foo"] = "First:A; Second:B; Third:C"
self.assertScriptResultEquals("$map(%foo%,$upper(%_loop_count%=%_loop_value%))", foo_output, context)
context["bar"] = ["First:A", "Second:B", "Third:C"]
self.assertScriptResultEquals("$map(%bar%,$upper(%_loop_count%=%_loop_value%))", loop_output, context)
# Tests with static inputs
self.assertScriptResultEquals("$map(First:A; Second:B; Third:C,$upper(%_loop_count%=%_loop_value%))", loop_output, context)
# Tests for removing empty elements
context["baz"] = ["First:A", "Second:B", "Remove", "Third:C"]
test_output = "1=FIRST:A; 2=SECOND:B; 4=THIRD:C"
self.assertScriptResultEquals("$lenmulti(%baz%)", "4", context)
self.assertScriptResultEquals("$map(%baz%,$if($eq(%_loop_count%,3),,$upper(%_loop_count%=%_loop_value%)))", test_output, context)
context["baz"] = ["First:A", "Second:B", "Remove", "Third:C"]
self.assertScriptResultEquals("$setmulti(baz,$map(%baz%,$if($eq(%_loop_count%,3),,$upper(%_loop_count%=%_loop_value%))))%baz%", test_output, context)
self.assertScriptResultEquals("$lenmulti(%baz%)", "3", context)
self.assertScriptResultEquals("%baz%", test_output, context)
# Tests with missing inputs
self.assertScriptResultEquals("$map(,$upper(%_loop_count%=%_loop_value%))", "", context)
self.assertScriptResultEquals("$map(First:A; Second:B; Third:C,)", "", context)
# Tests with separator override
self.assertScriptResultEquals("$map(First:A; Second:B; Third:C,$upper(%_loop_count%=%_loop_value%),:)", alternate_output, context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$map: Wrong number of arguments for \$map: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$map()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$map(abc; def)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$map(abc:def,$noop(),:,extra)")
def test_cmd_joinmulti(self):
context = Metadata()
context["foo"] = "First:A; Second:B; Third:C"
context["bar"] = ["First:A", "Second:B", "Third:C"]
context["joiner"] = " ==> "
foo_output = "First:A; Second:B; Third:C"
bar_output = "First:A ==> Second:B ==> Third:C"
alternate_output = "First ==> A; Second ==> B; Third ==> C"
# Tests with context
self.assertScriptResultEquals("$join(%foo%,%joiner%)", foo_output, context)
self.assertScriptResultEquals("$join(%bar%,%joiner%)", bar_output, context)
# Tests with static inputs
self.assertScriptResultEquals("$join(First:A; Second:B; Third:C, ==> )", bar_output, context)
# Tests with missing inputs
self.assertScriptResultEquals("$join(, ==> )", "", context)
self.assertScriptResultEquals("$join(First:A; Second:B; Third:C,)", "First:ASecond:BThird:C", context)
# Tests with separator override
self.assertScriptResultEquals("$join(First:A; Second:B; Third:C, ==> ,:)", alternate_output, context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$join: Wrong number of arguments for \$join: Expected between 2 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$join()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$join(abc; def)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$join(abc:def, ==> ,:,extra)")
def test_cmd_slice(self):
context = Metadata()
context["foo"] = "First:A; Second:B; Third:C"
context["bar"] = ["First:A", "Second:B", "Third:C"]
context["zero"] = '0'
context["one"] = '1'
context["two"] = '2'
context["three"] = '3'
output_0_1 = "First:A"
output_0_2 = "First:A; Second:B"
output_0_3 = "First:A; Second:B; Third:C"
output_1_2 = "Second:B"
output_1_3 = "Second:B; Third:C"
output_2_3 = "Third:C"
alternate_output = "A; Second:B; Third"
# Tests with context
self.assertScriptResultEquals("$slice(%foo%,%zero%,%one%)", output_0_3, context)
self.assertScriptResultEquals("$slice(%bar%,%zero%,%one%)", output_0_1, context)
self.assertScriptResultEquals("$slice(%bar%,%zero%,%two%)", output_0_2, context)
self.assertScriptResultEquals("$slice(%bar%,%zero%,%three%)", output_0_3, context)
# Tests with static inputs
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,0,1)", output_0_1, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,0,2)", output_0_2, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,0,3)", output_0_3, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,1,2)", output_1_2, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,1,3)", output_1_3, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,2,3)", output_2_3, context)
# Tests with negative inputs
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,-3,1)", output_0_1, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,0,-1)", output_0_2, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,-2,2)", output_1_2, context)
# Tests with missing inputs
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,,1)", output_0_1, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,1)", output_1_3, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,1,)", output_1_3, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,,)", output_0_3, context)
# Tests with invalid inputs (end < start)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,1,0)", "", context)
# Tests with invalid inputs (non-numeric end and/or start)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,a,1)", output_0_1, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,1,b)", output_1_3, context)
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,a,b)", output_0_3, context)
# Tests with separator override
self.assertScriptResultEquals("$slice(First:A; Second:B; Third:C,1,3,:)", alternate_output, context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$slice: Wrong number of arguments for \$slice: Expected between 2 and 4, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$slice()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$slice(abc; def)")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$slice(abc; def),0,1,:,extra")
def test_cmd_datetime(self):
# Save original datetime object and substitute one returning
# a fixed now() value for testing.
original_datetime = datetime.datetime
datetime.datetime = _DateTime
try:
context = Metadata()
context["foo"] = "%Y%m%d%H%M%S.%f"
# Tests with context
self.assertScriptResultEquals("$datetime(%foo%)", "20200102123456.000789", context)
self.assertScriptResultEquals("$datetime($initials())", "2020-01-02 12:34:56", context)
# Tests with static input
self.assertScriptResultEquals(r"$datetime(\%Y\%m\%d\%H\%M\%S.\%f)", "20200102123456.000789", context)
# Tests with timezones
self.assertScriptResultEquals(r"$datetime(\%H\%M\%S \%z \%Z)", "123456 +0200 TZ Test", context)
# Tests with missing input
self.assertScriptResultEquals("$datetime()", "2020-01-02 12:34:56", context)
# Tests with invalid format
self.assertScriptResultEquals("$datetime(xxx)", "xxx", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$datetime: Wrong number of arguments for \$datetime: Expected between 0 and 1, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$datetime(abc,def)")
finally:
# Restore original datetime object
datetime.datetime = original_datetime
def test_cmd_datetime_platform_dependent(self):
# Platform dependent testing because different platforms (both os and Python version)
# support some format arguments differently.
possible_tests = (
'%', # Hanging % at end of format
'%-d', # Non zero-padded day
'%-m', # Non zero-padded month
'%3Y', # Length specifier shorter than string
)
tests_to_run = []
# Get list of tests for unsupported format codes
for test_case in possible_tests:
try:
datetime.datetime.now().strftime(test_case)
except ValueError:
tests_to_run.append(test_case)
if not tests_to_run:
self.skipTest('datetime module supports all test cases')
# Save original datetime object and substitute one returning
# a fixed now() value for testing.
original_datetime = datetime.datetime
datetime.datetime = _DateTime
try:
areg = r"^\d+:\d+:\$datetime: Unsupported format code"
# Tests with invalid format code (platform dependent tests)
for test_case in tests_to_run:
with self.assertRaisesRegex(ScriptRuntimeError, areg):
self.parser.eval(r'$datetime(\{0})'.format(test_case))
finally:
# Restore original datetime object
datetime.datetime = original_datetime
def test_scriptruntimeerror(self):
# Platform dependent testing because different platforms (both os and Python version)
# support some format arguments differently. Use $datetime function to generate exceptions.
possible_tests = (
'%', # Hanging % at end of format
'%-d', # Non zero-padded day
'%-m', # Non zero-padded month
'%3Y', # Length specifier shorter than string
)
test_to_run = ''
# Get list of tests for unsupported format codes
for test_case in possible_tests:
try:
datetime.datetime.now().strftime(test_case)
except ValueError:
test_to_run = test_case
break
if not test_to_run:
self.skipTest('no test found to generate ScriptRuntimeError')
# Save original datetime object and substitute one returning
# a fixed now() value for testing.
original_datetime = datetime.datetime
datetime.datetime = _DateTime
try:
# Test that the correct position number is passed
areg = r"^\d+:7:\$datetime: Unsupported format code"
with self.assertRaisesRegex(ScriptRuntimeError, areg):
self.parser.eval(r'$noop()$datetime(\{0})'.format(test_to_run))
# Test that the function stack is returning the correct name (nested functions)
areg = r"^\d+:\d+:\$datetime: Unsupported format code"
with self.assertRaisesRegex(ScriptRuntimeError, areg):
self.parser.eval(r'$set(foo,$datetime($if(,,\{0})))'.format(test_to_run))
# Test that the correct line number is passed
areg = r"^2:\d+:\$datetime: Unsupported format code"
with self.assertRaisesRegex(ScriptRuntimeError, areg):
self.parser.eval('$noop(\n)$datetime($if(,,\\{0})))'.format(test_to_run))
finally:
# Restore original datetime object
datetime.datetime = original_datetime
def test_multivalue_1(self):
self.parser.context = Metadata({'foo': ':', 'bar': 'x:yz', 'empty': ''})
expr = self.parser.parse('a:bc; d:ef')
self.assertIsInstance(expr, ScriptExpression)
mv = MultiValue(self.parser, expr, MULTI_VALUED_JOINER)
self.assertEqual(mv._multi, ['a:bc', 'd:ef'])
self.assertEqual(mv.separator, MULTI_VALUED_JOINER)
self.assertEqual(len(mv), 2)
del mv[0]
self.assertEqual(len(mv), 1)
mv.insert(0, 'x')
self.assertEqual(mv[0], 'x')
mv[0] = 'y'
self.assertEqual(mv[0], 'y')
self.assertEqual(str(mv), 'y; d:ef')
self.assertTrue(repr(mv).startswith('MultiValue('))
mv = MultiValue(self.parser, expr, ':')
self.assertEqual(mv._multi, ['a', 'bc; d', 'ef'])
self.assertEqual(mv.separator, ':')
expr = self.parser.parse('a:bc; d:ef')
self.assertIsInstance(expr, ScriptExpression)
sep = self.parser.parse('%foo%')
self.assertIsInstance(sep, ScriptExpression)
mv = MultiValue(self.parser, expr, sep)
self.assertEqual(mv._multi, ['a', 'bc; d', 'ef'])
expr = self.parser.parse('%bar%; d:ef')
self.assertIsInstance(expr, ScriptExpression)
sep = self.parser.parse('%foo%')
self.assertIsInstance(sep, ScriptExpression)
mv = MultiValue(self.parser, expr, sep)
self.assertEqual(mv._multi, ['x', 'yz; d', 'ef'])
expr = self.parser.parse('%bar%')
self.assertIsInstance(expr, ScriptExpression)
mv = MultiValue(self.parser, expr, MULTI_VALUED_JOINER)
self.assertEqual(mv._multi, ['x:yz'])
expr = self.parser.parse('%bar%; d:ef')
self.assertIsInstance(expr, ScriptExpression)
sep = self.parser.parse('%empty%')
self.assertIsInstance(sep, ScriptExpression)
mv = MultiValue(self.parser, expr, sep)
self.assertEqual(mv._multi, ['x:yz; d:ef'])
expr = self.parser.parse('')
self.assertIsInstance(expr, ScriptExpression)
mv = MultiValue(self.parser, expr, MULTI_VALUED_JOINER)
self.assertEqual(mv._multi, [])
def test_cmd_sortmulti(self):
context = Metadata()
context["foo"] = ['B', 'D', 'E', 'A', 'C']
context["bar"] = ['B:AB', 'D:C', 'E:D', 'A:A', 'C:X']
context['baz'] = "B; D; E; A; C"
# Tests with context
self.assertScriptResultEquals("$sortmulti(%foo%)", "A; B; C; D; E", context)
self.assertScriptResultEquals("$sortmulti(%bar%)", "A:A; B:AB; C:X; D:C; E:D", context)
self.assertScriptResultEquals("$sortmulti(%baz%)", "B; D; E; A; C", context)
# Tests with static inputs
self.assertScriptResultEquals("$sortmulti(B; D; E; A; C)", "A; B; C; D; E", context)
self.assertScriptResultEquals("$sortmulti(B:AB; D:C; E:D; A:A; C:X)", "A:A; B:AB; C:X; D:C; E:D", context)
# Tests with separator override
self.assertScriptResultEquals("$sortmulti(B:AB; D:C; E:D; A:A; C:X,:)", "A; C:AB; D:B:C; E:D; A:X", context)
# Tests with missing inputs
self.assertScriptResultEquals("$sortmulti(,)", "", context)
self.assertScriptResultEquals("$sortmulti(,:)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$sortmulti: Wrong number of arguments for \$sortmulti: Expected between 1 and 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$sortmulti()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$sortmulti(B:AB; D:C; E:D; A:A; C:X,:,extra)")
def test_cmd_reversemulti(self):
context = Metadata()
context["foo"] = ['B', 'D', 'E', 'A', 'C']
context["bar"] = ['B:AB', 'D:C', 'E:D', 'A:A', 'C:X']
context['baz'] = "B; D; E; A; C"
# Tests with context
self.assertScriptResultEquals("$reversemulti(%foo%)", "C; A; E; D; B", context)
self.assertScriptResultEquals("$reversemulti(%bar%)", "C:X; A:A; E:D; D:C; B:AB", context)
self.assertScriptResultEquals("$reversemulti(%baz%)", "B; D; E; A; C", context)
# Tests with static inputs
self.assertScriptResultEquals("$reversemulti(B; D; E; A; C)", "C; A; E; D; B", context)
self.assertScriptResultEquals("$reversemulti(B:AB; D:C; E:D; A:A; C:X)", "C:X; A:A; E:D; D:C; B:AB", context)
# Tests with separator override
self.assertScriptResultEquals("$reversemulti(B:AB; D:C; E:D; A:A; C:X,:)", "X:A; C:D; A:C; E:AB; D:B", context)
# Tests with missing inputs
self.assertScriptResultEquals("$reversemulti(,)", "", context)
self.assertScriptResultEquals("$reversemulti(,:)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$reversemulti: Wrong number of arguments for \$reversemulti: Expected between 1 and 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$reversemulti()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$reversemulti(B:AB; D:C; E:D; A:A; C:X,:,extra)")
def test_cmd_unique(self):
context = Metadata()
context["foo"] = ['a', 'A', 'B', 'b', 'cd', 'Cd', 'cD', 'CD', 'a', 'A', 'b']
context["bar"] = "a; A; B; b; cd; Cd; cD; CD; a; A; b"
# Tests with context
self.assertScriptResultEquals("$unique(%foo%)", "A; CD; b", context)
self.assertScriptResultEquals("$unique(%bar%)", "a; A; B; b; cd; Cd; cD; CD; a; A; b", context)
# Tests with static inputs
self.assertScriptResultEquals("$unique(a; A; B; b; cd; Cd; cD; CD; a; A; b)", "A; CD; b", context)
# Tests with separator override
self.assertScriptResultEquals("$unique(a: A: B: b: cd: Cd: cD: CD: a: A: b,,: )", "A: CD: b", context)
# Tests with case-sensitive comparison
self.assertScriptResultEquals("$unique(%foo%,1)", "A; B; CD; Cd; a; b; cD; cd", context)
# Tests with missing inputs
self.assertScriptResultEquals("$unique(,)", "", context)
self.assertScriptResultEquals("$unique(,,)", "", context)
self.assertScriptResultEquals("$unique(,:)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$unique: Wrong number of arguments for \$unique: Expected between 1 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$unique()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$unique(B:AB; D:C; E:D; A:A; C:X,1,:,extra)")
def test_cmd_countryname(self):
context = Metadata()
context["foo"] = "ca"
context["bar"] = ""
context["baz"] = "INVALID"
# Mock function to simulate English locale.
def mock_gettext_countries_en(arg):
return arg
# Mock function to simulate Russian locale.
def mock_gettext_countries_ru(arg):
return "Канада" if arg == 'Canada' else arg
# Test with Russian locale
with mock.patch('picard.script.functions.gettext_countries', mock_gettext_countries_ru):
self.assertScriptResultEquals("$countryname(ca)", "Canada", context)
self.assertScriptResultEquals("$countryname(ca,)", "Canada", context)
self.assertScriptResultEquals("$countryname(ca, )", "Канада", context)
self.assertScriptResultEquals("$countryname(ca,yes)", "Канада", context)
self.assertScriptResultEquals("$countryname(INVALID,yes)", "", context)
# Test for unknown translation of correct code
self.assertScriptResultEquals("$countryname(fr,yes)", "France", context)
# Reset locale to English for remaining tests
with mock.patch('picard.script.functions.gettext_countries', mock_gettext_countries_en):
self.assertScriptResultEquals("$countryname(ca,)", "Canada", context)
self.assertScriptResultEquals("$countryname(ca,yes)", "Canada", context)
self.assertScriptResultEquals("$countryname(ca)", "Canada", context)
self.assertScriptResultEquals("$countryname(CA)", "Canada", context)
self.assertScriptResultEquals("$countryname(%foo%)", "Canada", context)
self.assertScriptResultEquals("$countryname(%bar%)", "", context)
self.assertScriptResultEquals("$countryname(%baz%)", "", context)
self.assertScriptResultEquals("$countryname(INVALID)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$countryname: Wrong number of arguments for \$countryname: Expected between 1 and 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$countryname()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$countryname(CA,,Extra)")
def test_cmd_year(self):
context = Metadata()
context["foo"] = "07.21.2021"
context["bar"] = "mdy"
# Test with default values
self.assertScriptResultEquals("$year(2021 07 21)", "2021", context)
self.assertScriptResultEquals("$year(2021.07.21)", "2021", context)
self.assertScriptResultEquals("$year(2021-07-21)", "2021", context)
self.assertScriptResultEquals("$year(21-07-21)", "21", context)
# Test with overrides specified
self.assertScriptResultEquals("$year(%foo%,%bar%)", "2021", context)
# Test with invalid overrides
self.assertScriptResultEquals("$year(2021-07-21,myd)", "2021", context)
# Test missing elements
self.assertScriptResultEquals("$year(,)", "", context)
self.assertScriptResultEquals("$year(07-21,mdy)", "", context)
self.assertScriptResultEquals("$year(21-07,dmy)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$year: Wrong number of arguments for \$year: Expected between 1 and 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$year()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$year(2021-07-21,,)")
def test_cmd_month(self):
context = Metadata()
context["foo"] = "07.21.2021"
context["bar"] = "mdy"
# Test with default values
self.assertScriptResultEquals("$month(2021 07 21)", "07", context)
self.assertScriptResultEquals("$month(2021.07.21)", "07", context)
self.assertScriptResultEquals("$month(2021-07-21)", "07", context)
self.assertScriptResultEquals("$month(2021-7-21)", "7", context)
# Test with overrides specified
self.assertScriptResultEquals("$month(%foo%,%bar%)", "07", context)
# Test with invalid overrides
self.assertScriptResultEquals("$month(2021-07-21,myd)", "07", context)
# Test missing elements
self.assertScriptResultEquals("$month(,)", "", context)
self.assertScriptResultEquals("$month(-21-2021,mdy)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$month: Wrong number of arguments for \$month: Expected between 1 and 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$month()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$month(2021-07-21,,)")
def test_cmd_day(self):
context = Metadata()
context["foo"] = "07.21.2021"
context["bar"] = "mdy"
# Test with default values
self.assertScriptResultEquals("$day(2021 07 21)", "21", context)
self.assertScriptResultEquals("$day(2021.07.21)", "21", context)
self.assertScriptResultEquals("$day(2021-07-21)", "21", context)
self.assertScriptResultEquals("$day(2021-07-2)", "2", context)
# Test with overrides specified
self.assertScriptResultEquals("$day(%foo%,%bar%)", "21", context)
# Test with invalid overrides
self.assertScriptResultEquals("$day(2021-07-21,myd)", "21", context)
# Test missing elements
self.assertScriptResultEquals("$day(,)", "", context)
self.assertScriptResultEquals("$day(-07-2021,dmy)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$day: Wrong number of arguments for \$day: Expected between 1 and 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$day()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$day(2021-07-21,,)")
def test_cmd_dateformat(self):
context = Metadata()
context["foo"] = "07.21.2021"
context["bar"] = "mdy"
context["format"] = "%Y.%m.%d"
# Test with default values
self.assertScriptResultEquals("$dateformat(2021 07 21)", "2021-07-21", context)
self.assertScriptResultEquals("$dateformat(2021.07.21)", "2021-07-21", context)
self.assertScriptResultEquals("$dateformat(2021-07-21)", "2021-07-21", context)
self.assertScriptResultEquals("$dateformat(2021-7-21)", "2021-07-21", context)
# Test with overrides specified
self.assertScriptResultEquals("$dateformat(%foo%,%format%,%bar%)", "2021.07.21", context)
# Test with invalid overrides
self.assertScriptResultEquals("$dateformat(2021-07-21,,myd)", "2021-07-21", context)
self.assertScriptResultEquals("$dateformat(2021-07-21,,dmy)", "", context)
self.assertScriptResultEquals("$dateformat(2021-07-21,,mdy)", "", context)
self.assertScriptResultEquals("$dateformat(2021-July-21)", "", context)
self.assertScriptResultEquals("$dateformat(2021)", "", context)
self.assertScriptResultEquals("$dateformat(2021-07)", "", context)
# Test missing elements
self.assertScriptResultEquals("$dateformat(,)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$dateformat: Wrong number of arguments for \$dateformat: Expected between 1 and 3, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$dateformat()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$dateformat(2021-07-21,,,)")
def test_cmd_is_multi(self):
context = Metadata()
context["foo"] = "a; b; c"
context["bar"] = ""
self.assertScriptResultEquals("$is_multi(%foo%)", "", context)
self.assertScriptResultEquals("$is_multi(%bar%)", "", context)
self.assertScriptResultEquals("$setmulti(baz,a)$is_multi(%baz%)", "", context)
self.assertScriptResultEquals("$setmulti(baz,a; b; c)$is_multi(%baz%)", "1", context)
self.assertScriptResultEquals("$is_multi(a; b; c)", "1", context)
self.assertScriptResultEquals("$is_multi(a)", "", context)
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$is_multi: Wrong number of arguments for \$is_multi: Expected exactly 1, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$is_multi()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$is_multi(a,)")
def test_cmd_cleanmulti(self):
context = Metadata()
context["foo"] = ["", "one", "two"]
context["bar"] = ["one", "", "two"]
context["baz"] = ["one", "two", ""]
# Confirm initial values
self.assertScriptResultEquals("%foo%", "; one; two", context)
self.assertScriptResultEquals("%bar%", "one; ; two", context)
self.assertScriptResultEquals("%baz%", "one; two; ", context)
# Test cleaned values
self.assertScriptResultEquals("$cleanmulti(foo)%foo%", "one; two", context)
self.assertScriptResultEquals("$cleanmulti(bar)%bar%", "one; two", context)
self.assertScriptResultEquals("$cleanmulti(baz)%baz%", "one; two", context)
def test_cmd_cleanmulti_with_hidden_var(self):
context = Metadata()
context["~foo"] = ["one", "", "two"]
# Confirm initial values
self.assertScriptResultEquals("%_foo%", "one; ; two", context)
# Test cleaned values
self.assertScriptResultEquals("$cleanmulti(_foo)%_foo%", "one; two", context)
def test_cmd_cleanmulti_only_empty_strings(self):
context = Metadata()
context["foo"] = ["", "", ""]
# Confirm initial values
self.assertScriptResultEquals("%foo%", "; ; ", context)
# Test cleaned values
self.assertScriptResultEquals("$cleanmulti(foo)%foo%", "", context)
def test_cmd_cleanmulti_indirect_argument(self):
context = Metadata()
context["foo"] = ["", "one", "two"]
context["bar"] = "foo"
# Confirm initial values
self.assertScriptResultEquals("%foo%", "; one; two", context)
# Test cleaned values
self.assertScriptResultEquals("$cleanmulti(%bar%)%foo%", "one; two", context)
def test_cmd_cleanmulti_non_multi_argument(self):
context = Metadata()
context["foo"] = "one"
context["bar"] = "one; ; two"
context["baz"] = ""
# Confirm initial values
self.assertScriptResultEquals("%foo%", "one", context)
self.assertScriptResultEquals("%bar%", "one; ; two", context)
self.assertScriptResultEquals("%baz%", "", context)
# Test cleaned values
self.assertScriptResultEquals("$cleanmulti(foo)%foo%", "one", context)
self.assertScriptResultEquals("$cleanmulti(bar)%bar%", "one; ; two", context)
self.assertScriptResultEquals("$cleanmulti(baz)%baz%", "", context)
def test_cmd_cleanmulti_invalid_number_of_arguments(self):
areg = r"^\d+:\d+:\$cleanmulti: Wrong number of arguments for \$cleanmulti: Expected exactly 1, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$cleanmulti()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$cleanmulti(foo,)")
def test_cmd_min(self):
# Test "text" processing
self.assertScriptResultEquals("$min(text,abc)", "abc")
self.assertScriptResultEquals("$min(text,abc,abcd,ac)", "abc")
self.assertScriptResultEquals("$min(text,ac,abcd,abc)", "abc")
self.assertScriptResultEquals("$min(text,,a)", "")
self.assertScriptResultEquals("$min(text,a,)", "")
self.assertScriptResultEquals("$min(text,,)", "")
# Test date type arguments using "text" processing
self.assertScriptResultEquals("$min(text,2020-01-01)", "2020-01-01")
self.assertScriptResultEquals("$min(text,2020-01-01,2020-01-02,2020-02)", "2020-01-01")
self.assertScriptResultEquals("$min(text,2020-02,2020-01-02,2020-01-01)", "2020-01-01")
# Test "int" processing
self.assertScriptResultEquals("$min(int,1)", "1")
self.assertScriptResultEquals("$min(int,2,3)", "2")
self.assertScriptResultEquals("$min(int,2,1,3)", "1")
self.assertScriptResultEquals("$min(int,2,1,3.1)", "")
self.assertScriptResultEquals("$min(int,2,1,a)", "")
self.assertScriptResultEquals("$min(int,2,,1)", "")
self.assertScriptResultEquals("$min(int,2,1,)", "")
# Test "float" processing
self.assertScriptResultEquals("$min(float,1)", "1.0")
self.assertScriptResultEquals("$min(float,2,3)", "2.0")
self.assertScriptResultEquals("$min(float,2,1,3)", "1.0")
self.assertScriptResultEquals("$min(float,2,1.1,3)", "1.1")
self.assertScriptResultEquals("$min(float,1.11,1.1,1.111)", "1.1")
self.assertScriptResultEquals("$min(float,2,1,a)", "")
self.assertScriptResultEquals("$min(float,2,,1)", "")
self.assertScriptResultEquals("$min(float,2,1,)", "")
# Test 'nocase' processing
self.assertScriptResultEquals("$min(nocase,a,B)", "a")
self.assertScriptResultEquals("$min(nocase,c,A,b)", "A")
# Test case sensitive arguments with 'text' processing
self.assertScriptResultEquals("$min(text,A,a)", "A")
self.assertScriptResultEquals("$min(text,a,B)", "B")
# Test multi-value arguments
context = Metadata()
context['mv'] = ['y', 'z', 'x']
self.assertScriptResultEquals("$min(text,%mv%)", "x", context)
self.assertScriptResultEquals("$min(text,a,%mv%)", "a", context)
self.assertScriptResultEquals("$min(text,y; z; x)", "x")
self.assertScriptResultEquals("$min(text,a,y; z; x)", "a")
self.assertScriptResultEquals("$min(int,5,4; 6; 3)", "3")
self.assertScriptResultEquals("$min(float,5.9,4.2; 6; 3.35)", "3.35")
# Test 'auto' processing
self.assertScriptResultEquals("$min(,1,2)", "1")
self.assertScriptResultEquals("$min(,2,1)", "1")
self.assertScriptResultEquals("$min(auto,1,2)", "1")
self.assertScriptResultEquals("$min(auto,2,1)", "1")
self.assertScriptResultEquals("$min(,1,2.1)", "1.0")
self.assertScriptResultEquals("$min(,2.1,1)", "1.0")
self.assertScriptResultEquals("$min(auto,1,2.1)", "1.0")
self.assertScriptResultEquals("$min(auto,2.1,1)", "1.0")
self.assertScriptResultEquals("$min(,2.1,1,a)", "1")
self.assertScriptResultEquals("$min(auto,2.1,1,a)", "1")
self.assertScriptResultEquals("$min(,a,A)", "A")
self.assertScriptResultEquals("$min(,A,a)", "A")
self.assertScriptResultEquals("$min(auto,a,A)", "A")
self.assertScriptResultEquals("$min(auto,A,a)", "A")
# Test invalid processing types
self.assertScriptResultEquals("$min(unknown,a,B)", "")
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$min: Wrong number of arguments for \$min: Expected at least 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$min()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$min(text)")
def test_cmd_max(self):
# Test "text" processing
self.assertScriptResultEquals("$max(text,abc)", "abc")
self.assertScriptResultEquals("$max(text,abc,abcd,ac)", "ac")
self.assertScriptResultEquals("$max(text,ac,abcd,abc)", "ac")
self.assertScriptResultEquals("$max(text,,a)", "a")
self.assertScriptResultEquals("$max(text,a,)", "a")
self.assertScriptResultEquals("$max(text,,)", "")
# Test date type arguments using "text" processing
self.assertScriptResultEquals("$max(text,2020-01-01)", "2020-01-01")
self.assertScriptResultEquals("$max(text,2020-01-01,2020-01-02,2020-02)", "2020-02")
self.assertScriptResultEquals("$max(text,2020-02,2020-01-02,2020-01-01)", "2020-02")
# Test "int" processing
self.assertScriptResultEquals("$max(int,1)", "1")
self.assertScriptResultEquals("$max(int,2,3)", "3")
self.assertScriptResultEquals("$max(int,2,1,3)", "3")
self.assertScriptResultEquals("$max(int,2,1,3.1)", "")
self.assertScriptResultEquals("$max(int,2,1,a)", "")
self.assertScriptResultEquals("$max(int,2,,1)", "")
self.assertScriptResultEquals("$max(int,2,1,)", "")
# Test "float" processing
self.assertScriptResultEquals("$max(float,1)", "1.0")
self.assertScriptResultEquals("$max(float,2,3)", "3.0")
self.assertScriptResultEquals("$max(float,2,1.1,3)", "3.0")
self.assertScriptResultEquals("$max(float,2,1,3.1)", "3.1")
self.assertScriptResultEquals("$max(float,2.1,2.11,2.111)", "2.111")
self.assertScriptResultEquals("$max(float,2,1,a)", "")
self.assertScriptResultEquals("$max(float,2,,1)", "")
self.assertScriptResultEquals("$max(float,2,1,)", "")
# Test 'nocase' processing
self.assertScriptResultEquals("$max(nocase,a,B)", "B")
self.assertScriptResultEquals("$max(nocase,c,a,B)", "c")
# Test case sensitive arguments with 'text' processing
self.assertScriptResultEquals("$max(text,A,a)", "a")
self.assertScriptResultEquals("$max(text,a,B)", "a")
# Test multi-value arguments
context = Metadata()
context['mv'] = ['y', 'z', 'x']
self.assertScriptResultEquals("$max(text,%mv%)", "z", context)
self.assertScriptResultEquals("$max(text,a,%mv%)", "z", context)
self.assertScriptResultEquals("$max(text,y; z; x)", "z")
self.assertScriptResultEquals("$max(text,a,y; z; x)", "z")
self.assertScriptResultEquals("$max(int,5,4; 6; 3)", "6")
self.assertScriptResultEquals("$max(float,5.9,4.2; 6; 3.35)", "6.0")
# Test 'auto' processing
self.assertScriptResultEquals("$max(,1,2)", "2")
self.assertScriptResultEquals("$max(,2,1)", "2")
self.assertScriptResultEquals("$max(auto,1,2)", "2")
self.assertScriptResultEquals("$max(auto,2,1)", "2")
self.assertScriptResultEquals("$max(,1.1,2)", "2.0")
self.assertScriptResultEquals("$max(,2,1.1)", "2.0")
self.assertScriptResultEquals("$max(auto,1.1,2)", "2.0")
self.assertScriptResultEquals("$max(auto,2,1.1)", "2.0")
self.assertScriptResultEquals("$max(,2.1,1,a)", "a")
self.assertScriptResultEquals("$max(auto,2.1,1,a)", "a")
self.assertScriptResultEquals("$max(,a,A)", "a")
self.assertScriptResultEquals("$max(,A,a)", "a")
self.assertScriptResultEquals("$max(auto,a,A)", "a")
self.assertScriptResultEquals("$max(auto,A,a)", "a")
# Test invalid processing types
self.assertScriptResultEquals("$max(unknown,a,B)", "")
# Tests with invalid number of arguments
areg = r"^\d+:\d+:\$max: Wrong number of arguments for \$max: Expected at least 2, "
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$max()")
with self.assertRaisesRegex(ScriptError, areg):
self.parser.eval("$max(text)")
| 117,478
|
Python
|
.py
| 2,062
| 47.916101
| 168
| 0.635721
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,822
|
test_bytes2human.py
|
metabrainz_picard/test/test_bytes2human.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2019-2021 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import os.path
from test.picardtestcase import PicardTestCase
from picard.util import bytes2human
class Testbytes2human(PicardTestCase):
def test_00(self):
self.run_test()
self.assertEqual(bytes2human.binary(45682), '44.6 KiB')
self.assertEqual(bytes2human.binary(-45682), '-44.6 KiB')
self.assertEqual(bytes2human.binary(-45682, 2), '-44.61 KiB')
self.assertEqual(bytes2human.decimal(45682), '45.7 kB')
self.assertEqual(bytes2human.decimal(45682, 2), '45.68 kB')
self.assertEqual(bytes2human.decimal(9223372036854775807), '9223.4 PB')
self.assertEqual(bytes2human.decimal(9223372036854775807, 3), '9223.372 PB')
self.assertEqual(bytes2human.decimal(123.6), '123 B')
self.assertRaises(ValueError, bytes2human.decimal, 'xxx')
self.assertRaises(ValueError, bytes2human.decimal, '123.6')
self.assertRaises(ValueError, bytes2human.binary, 'yyy')
self.assertRaises(ValueError, bytes2human.binary, '456yyy')
try:
bytes2human.decimal('123')
except Exception as e:
self.fail('Unexpected exception: %s' % e)
def test_calc_unit_raises_value_error(self):
self.assertRaises(ValueError, bytes2human.calc_unit, 1, None)
self.assertRaises(ValueError, bytes2human.calc_unit, 1, 100)
self.assertRaises(ValueError, bytes2human.calc_unit, 1, 999)
self.assertRaises(ValueError, bytes2human.calc_unit, 1, 1023)
self.assertRaises(ValueError, bytes2human.calc_unit, 1, 1025)
self.assertEqual((1.0, 'B'), bytes2human.calc_unit(1, 1024))
self.assertEqual((1.0, 'B'), bytes2human.calc_unit(1, 1000))
def run_test(self, lang='C', create_test_data=False):
"""
Compare data generated with sample files
Setting create_test_data to True will generated sample files
from code execution (developer-only, check carefully)
"""
filename = os.path.join('test', 'data', 'b2h_test_%s.dat' % lang)
testlist = self._create_testlist()
if create_test_data:
self._save_expected_to(filename, testlist)
expected = self._read_expected_from(filename)
self.assertEqual(testlist, expected)
if create_test_data:
# be sure it is disabled
self.fail('!!! UNSET create_test_data mode !!! (%s)' % filename)
@staticmethod
def _create_testlist():
values = [0, 1]
for n in (1000, 1024):
p = 1
for e in range(0, 6):
p *= n
for x in (0.1, 0.5, 0.99, 0.9999, 1, 1.5):
values.append(int(p * x))
list = []
for x in sorted(values):
list.append(";".join([str(x), bytes2human.decimal(x),
bytes2human.binary(x),
bytes2human.short_string(x, 1024, 2)]))
return list
@staticmethod
def _save_expected_to(path, a_list):
with open(path, 'wb') as f:
f.writelines([line + "\n" for line in a_list])
f.close()
@staticmethod
def _read_expected_from(path):
with open(path, 'r') as f:
lines = [line.rstrip("\n") for line in f.readlines()]
f.close()
return lines
def test_calc_unit(self):
self.assertEqual(bytes2human.calc_unit(12456, 1024), (12.1640625, 'KiB'))
self.assertEqual(bytes2human.calc_unit(-12456, 1000), (-12.456, 'kB'))
self.assertRaises(ValueError, bytes2human.calc_unit, 0, 1001)
| 4,571
|
Python
|
.py
| 98
| 38.77551
| 84
| 0.652242
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,823
|
test_releaseversions.py
|
metabrainz_picard/test/test_releaseversions.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2018, 2020-2021 Laurent Monin
# Copyright (C) 2014 Michael Wiencek
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2017 Sophist-UK
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2019-2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from unittest.mock import patch
from test.picardtestcase import (
PicardTestCase,
load_test_json,
)
from picard.releasegroup import (
ReleaseGroup,
prepare_releases_for_versions,
)
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": False
}
class ReleaseTest(PicardTestCase):
def test_1(self):
self.set_config_values(settings)
rlist = load_test_json('release_group_2.json')
releases = list(prepare_releases_for_versions(rlist['releases']))
expected = [
{'id': '123', 'year': '2009', 'country': 'GB', 'format': 'CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '5', 'barcode': '0123456789', 'packaging': 'Jewel Case', 'disambiguation': 'special', '_disambiguate_name': [], 'totaltracks': 5, 'countries': [], 'formats': ['CD']},
{'id': '456', 'year': '2009', 'country': 'GB', 'format': 'CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '5', 'barcode': '0123456789', 'packaging': 'Digipak', 'disambiguation': 'special', '_disambiguate_name': [], 'totaltracks': 5, 'countries': [], 'formats': ['CD']},
{'id': '789', 'year': '2009', 'country': 'GB', 'format': 'CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '5', 'barcode': '0123456789', 'packaging': 'Digipak', 'disambiguation': 'specialx', '_disambiguate_name': [], 'totaltracks': 5, 'countries': [], 'formats': ['CD']},
]
self.assertEqual(releases, expected)
r = ReleaseGroup(1)
r._parse_versions(rlist)
self.assertEqual(r.versions[0]['name'],
'5 / 2009 / GB / CD / label A / cat 123 / Jewel Case / special')
self.assertEqual(r.versions[1]['name'],
'5 / 2009 / GB / CD / label A / cat 123 / Digipak / special')
self.assertEqual(r.versions[2]['name'],
'5 / 2009 / GB / CD / label A / cat 123 / Digipak / specialx')
def test_2(self):
self.set_config_values(settings)
rlist = load_test_json('release_group_3.json')
releases = list(prepare_releases_for_versions(rlist['releases']))
expected = [
{'id': '789', 'year': '2011', 'country': 'FR', 'format': 'CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '5', 'barcode': '0123456789', 'packaging': '??', 'disambiguation': 'special A', '_disambiguate_name': [], 'totaltracks': 5, 'countries': [], 'formats': ['CD']},
{'id': '789', 'year': '2011', 'country': 'FR', 'format': 'CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '5', 'barcode': '0123456789', 'packaging': '??', 'disambiguation': '', '_disambiguate_name': [], 'totaltracks': 5, 'countries': [], 'formats': ['CD']},
]
self.assertEqual(releases, expected)
r = ReleaseGroup(1)
r._parse_versions(rlist)
self.assertEqual(r.versions[0]['name'],
'5 / 2011 / FR / CD / label A / cat 123 / special A')
self.assertEqual(r.versions[1]['name'],
'5 / 2011 / FR / CD / label A / cat 123')
def test_3(self):
self.set_config_values(settings)
rlist = load_test_json('release_group_4.json')
releases = list(prepare_releases_for_versions(rlist['releases']))
expected = [
{'id': '789', 'year': '2009', 'country': 'FR', 'format': 'CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '5', 'barcode': '0123456789', 'packaging': '??', 'disambiguation': '', '_disambiguate_name': [], 'totaltracks': 5, 'countries': [], 'formats': ['CD']},
{'id': '789', 'year': '2009', 'country': 'FR', 'format': 'CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '5', 'barcode': '[no barcode]', 'packaging': '??', 'disambiguation': '', '_disambiguate_name': [], 'totaltracks': 5, 'countries': [], 'formats': ['CD']},
]
self.assertEqual(releases, expected)
r = ReleaseGroup(1)
r._parse_versions(rlist)
self.assertEqual(r.versions[0]['name'],
'5 / 2009 / FR / CD / label A / cat 123 / 0123456789')
self.assertEqual(r.versions[1]['name'],
'5 / 2009 / FR / CD / label A / cat 123 / [no barcode]')
@patch('picard.releasegroup.VERSIONS_MAX_TRACKS', 2)
def test_4(self):
self.set_config_values(settings)
rlist = load_test_json('release_group_5.json')
releases = list(prepare_releases_for_versions(rlist['releases']))
expected = [
{'id': '789', 'year': '2009', 'country': 'FR', 'format': '3×CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '2+3+…', 'barcode': '0123456789', 'packaging': '??', 'disambiguation': '', '_disambiguate_name': [], 'totaltracks': 9, 'countries': [], 'formats': ['CD', 'CD', 'CD']},
]
self.assertEqual(releases, expected)
@patch('picard.releasegroup.VERSIONS_MAX_TRACKS', 3)
def test_5(self):
self.set_config_values(settings)
rlist = load_test_json('release_group_5.json')
releases = list(prepare_releases_for_versions(rlist['releases']))
expected = [
{'id': '789', 'year': '2009', 'country': 'FR', 'format': '3×CD', 'label': 'label A', 'catnum': 'cat 123', 'tracks': '2+3+4', 'barcode': '0123456789', 'packaging': '??', 'disambiguation': '', '_disambiguate_name': [], 'totaltracks': 9, 'countries': [], 'formats': ['CD', 'CD', 'CD']},
]
self.assertEqual(releases, expected)
| 6,557
|
Python
|
.py
| 106
| 54.226415
| 295
| 0.597669
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,824
|
test_util_lrucache.py
|
metabrainz_picard/test/test_util_lrucache.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
# Copyright (C) 2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util.lrucache import LRUCache
class LRUCacheTest(PicardTestCase):
def test_simple_getset(self):
lrucache = LRUCache(3)
lrucache['test'] = 1
self.assertEqual(lrucache['test'], 1)
self.assertIn('test', lrucache._ordered_keys)
def test_simple_del(self):
lrucache = LRUCache(3)
lrucache['test'] = 1
del lrucache['test']
self.assertNotIn('test', lrucache)
self.assertNotIn('test', lrucache._ordered_keys)
def test_max_size(self):
lrucache = LRUCache(3)
lrucache['test1'] = 1
lrucache['test2'] = 2
lrucache['test3'] = 3
lrucache['test4'] = 4
self.assertNotIn('test1', lrucache)
def test_lru(self):
lrucache = LRUCache(3)
lrucache['test1'] = 1
lrucache['test2'] = 2
lrucache['test3'] = 3
self.assertEqual(len(lrucache._ordered_keys), 3)
self.assertEqual('test3', lrucache._ordered_keys[0])
self.assertEqual('test2', lrucache._ordered_keys[1])
self.assertEqual('test1', lrucache._ordered_keys[2])
self.assertEqual(2, lrucache['test2'])
self.assertEqual('test2', lrucache._ordered_keys[0])
self.assertEqual('test3', lrucache._ordered_keys[1])
self.assertEqual('test1', lrucache._ordered_keys[2])
lrucache['test1'] = 4
self.assertEqual('test1', lrucache._ordered_keys[0])
self.assertEqual('test2', lrucache._ordered_keys[1])
self.assertEqual('test3', lrucache._ordered_keys[2])
def test_dict_like_init(self):
lrucache = LRUCache(3, [('test1', 1), ('test2', 2)])
self.assertEqual(lrucache['test1'], 1)
self.assertEqual(lrucache['test2'], 2)
def test_get_keyerror(self):
lrucache = LRUCache(3)
with self.assertRaises(KeyError):
value = lrucache['notakey'] # noqa: F841
def test_del_keyerror(self):
lrucache = LRUCache(3)
with self.assertRaises(KeyError):
del lrucache['notakey']
| 2,955
|
Python
|
.py
| 70
| 35.957143
| 80
| 0.671076
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,825
|
test_track.py
|
metabrainz_picard/test/test_track.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021-2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from collections import Counter
from test.picardtestcase import PicardTestCase
from picard.track import Track
class TrackTest(PicardTestCase):
def test_can_link_fingerprint(self):
track = Track('123')
self.assertTrue(track.can_link_fingerprint)
class TrackGenres2MetadataTest(PicardTestCase):
def test_empty(self):
genres = Counter()
ret = Track._genres_to_metadata(genres)
self.assertEqual(ret, [])
def test_basic(self):
genres = Counter(pop=6, rock=7, blues=2)
ret = Track._genres_to_metadata(genres)
self.assertEqual(ret, ['Blues', 'Pop', 'Rock'])
def test_negative_zero(self):
genres = Counter(pop=-6, rock=0, blues=-2)
ret = Track._genres_to_metadata(genres)
self.assertEqual(ret, [])
genres = Counter(pop=-6, rock=1, blues=-2)
ret = Track._genres_to_metadata(genres)
self.assertEqual(ret, ['Rock'])
def test_limit(self):
genres = Counter(pop=6, rock=7, blues=2)
ret = Track._genres_to_metadata(genres, limit=2)
self.assertEqual(ret, ['Pop', 'Rock'])
def test_limit_0(self):
genres = Counter(pop=6, rock=7, blues=2)
ret = Track._genres_to_metadata(genres, limit=0)
self.assertEqual(ret, [])
def test_limit_after_filter(self):
genres = Counter(rock=5, blues=7, pop=1, psychedelic=3)
filters = '-rock'
ret = Track._genres_to_metadata(genres, limit=3, filters=filters)
self.assertEqual(ret, ['Blues', 'Pop', 'Psychedelic'])
def test_minusage(self):
genres = Counter(pop=6, rock=7, blues=2)
ret = Track._genres_to_metadata(genres, minusage=10)
self.assertEqual(ret, ['Blues', 'Pop', 'Rock'])
ret = Track._genres_to_metadata(genres, minusage=50)
self.assertEqual(ret, ['Pop', 'Rock'])
ret = Track._genres_to_metadata(genres, minusage=90)
self.assertEqual(ret, ['Rock'])
def test_filters(self):
genres = Counter(pop=6, rock=7, blues=2)
ret = Track._genres_to_metadata(genres, filters="-blues")
self.assertEqual(ret, ['Pop', 'Rock'])
def test_join_with(self):
genres = Counter(pop=6, rock=7, blues=2)
ret = Track._genres_to_metadata(genres, join_with=",")
self.assertEqual(ret, ['Blues,Pop,Rock'])
| 3,208
|
Python
|
.py
| 72
| 38.666667
| 80
| 0.672115
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,826
|
test_imagelist.py
|
metabrainz_picard/test/test_imagelist.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018-2019 Wieland Hoffmann
# Copyright (C) 2018-2021 Laurent Monin
# Copyright (C) 2018-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import (
PicardTestCase,
create_fake_png,
)
from picard.album import Album
from picard.cluster import Cluster
from picard.coverart.image import CoverArtImage
from picard.file import File
from picard.track import Track
from picard.util.imagelist import ImageList
def create_test_files():
test_images = [
CoverArtImage(url='file://file1', data=create_fake_png(b'a')),
CoverArtImage(url='file://file2', data=create_fake_png(b'b')),
]
test_files = [
File('test1.flac'),
File('test2.flac'),
File('test2.flac')
]
test_files[0].metadata.images.append(test_images[0])
test_files[1].metadata.images.append(test_images[1])
test_files[2].metadata.images.append(test_images[1])
test_files[0].orig_metadata.images.append(test_images[0])
test_files[1].orig_metadata.images.append(test_images[1])
test_files[2].orig_metadata.images.append(test_images[1])
return (test_images, test_files)
class UpdateMetadataImagesTest(PicardTestCase):
def setUp(self):
super().setUp()
(self.test_images, self.test_files) = create_test_files()
def test_update_cluster_images(self):
cluster = Cluster('Test')
cluster.files = list(self.test_files)
self.assertTrue(cluster.update_metadata_images_from_children())
self.assertEqual(set(self.test_images), set(cluster.metadata.images))
self.assertFalse(cluster.metadata.has_common_images)
cluster.files.remove(self.test_files[2])
self.assertFalse(cluster.update_metadata_images_from_children())
self.assertEqual(set(self.test_images), set(cluster.metadata.images))
self.assertFalse(cluster.metadata.has_common_images)
cluster.files.remove(self.test_files[0])
self.assertTrue(cluster.update_metadata_images_from_children())
self.assertEqual(set(self.test_images[1:]), set(cluster.metadata.images))
self.assertTrue(cluster.metadata.has_common_images)
cluster.files.append(self.test_files[2])
self.assertFalse(cluster.update_metadata_images_from_children())
self.assertEqual(set(self.test_images[1:]), set(cluster.metadata.images))
self.assertTrue(cluster.metadata.has_common_images)
def test_update_track_images(self):
track = Track('00000000-0000-0000-0000-000000000000')
track.files = list(self.test_files)
self.assertTrue(track.update_metadata_images_from_children())
self.assertEqual(set(self.test_images), set(track.orig_metadata.images))
self.assertFalse(track.orig_metadata.has_common_images)
track.files.remove(self.test_files[2])
self.assertFalse(track.update_metadata_images_from_children())
self.assertEqual(set(self.test_images), set(track.orig_metadata.images))
self.assertFalse(track.orig_metadata.has_common_images)
track.files.remove(self.test_files[0])
self.assertTrue(track.update_metadata_images_from_children())
self.assertEqual(set(self.test_images[1:]), set(track.orig_metadata.images))
self.assertTrue(track.orig_metadata.has_common_images)
track.files.append(self.test_files[2])
self.assertFalse(track.update_metadata_images_from_children())
self.assertEqual(set(self.test_images[1:]), set(track.orig_metadata.images))
self.assertTrue(track.orig_metadata.has_common_images)
def test_update_album_images(self):
album = Album('00000000-0000-0000-0000-000000000000')
track1 = Track('00000000-0000-0000-0000-000000000001')
track1.files.append(self.test_files[0])
track2 = Track('00000000-0000-0000-0000-000000000002')
track2.files.append(self.test_files[1])
album.tracks = [track1, track2]
album.unmatched_files.files.append(self.test_files[2])
self.assertTrue(album.update_metadata_images_from_children())
self.assertEqual(set(self.test_images), set(album.orig_metadata.images))
self.assertFalse(album.orig_metadata.has_common_images)
album.tracks.remove(track2)
self.assertFalse(album.update_metadata_images_from_children())
self.assertEqual(set(self.test_images), set(album.orig_metadata.images))
self.assertFalse(album.orig_metadata.has_common_images)
album.tracks.remove(track1)
self.assertTrue(album.update_metadata_images_from_children())
self.assertEqual(set(self.test_images[1:]), set(album.orig_metadata.images))
self.assertTrue(album.orig_metadata.has_common_images)
album.tracks.append(track2)
self.assertFalse(album.update_metadata_images_from_children())
self.assertEqual(set(self.test_images[1:]), set(album.orig_metadata.images))
self.assertTrue(album.orig_metadata.has_common_images)
class RemoveMetadataImagesTest(PicardTestCase):
def setUp(self):
super().setUp()
(self.test_images, self.test_files) = create_test_files()
def test_remove_from_cluster(self):
cluster = Cluster('Test')
cluster.files = list(self.test_files)
self.assertTrue(cluster.update_metadata_images_from_children())
cluster.files.remove(self.test_files[0])
self.assertTrue(cluster.remove_metadata_images_from_children([self.test_files[0]]))
self.assertEqual(set(self.test_images[1:]), set(cluster.metadata.images))
self.assertTrue(cluster.metadata.has_common_images)
def test_remove_from_cluster_with_common_images(self):
cluster = Cluster('Test')
cluster.files = list(self.test_files[1:])
self.assertTrue(cluster.update_metadata_images_from_children())
cluster.files.remove(self.test_files[1])
self.assertFalse(cluster.remove_metadata_images_from_children([self.test_files[1]]))
self.assertEqual(set(self.test_images[1:]), set(cluster.metadata.images))
self.assertTrue(cluster.metadata.has_common_images)
def test_remove_from_empty_cluster(self):
cluster = Cluster('Test')
cluster.files.append(File('test1.flac'))
self.assertFalse(cluster.update_metadata_images_from_children())
self.assertFalse(cluster.remove_metadata_images_from_children([cluster.files[0]]))
self.assertEqual(set(), set(cluster.metadata.images))
self.assertTrue(cluster.metadata.has_common_images)
def test_remove_from_track(self):
track = Track('00000000-0000-0000-0000-000000000000')
track.files = list(self.test_files)
self.assertTrue(track.update_metadata_images_from_children())
track.files.remove(self.test_files[0])
self.assertTrue(track.remove_metadata_images_from_children([self.test_files[0]]))
self.assertEqual(set(self.test_images[1:]), set(track.orig_metadata.images))
self.assertTrue(track.orig_metadata.has_common_images)
def test_remove_from_track_with_common_images(self):
track = Track('00000000-0000-0000-0000-000000000000')
track.files = list(self.test_files[1:])
self.assertTrue(track.update_metadata_images_from_children())
track.files.remove(self.test_files[1])
self.assertFalse(track.remove_metadata_images_from_children([self.test_files[1]]))
self.assertEqual(set(self.test_images[1:]), set(track.orig_metadata.images))
self.assertTrue(track.orig_metadata.has_common_images)
def test_remove_from_empty_track(self):
track = Track('00000000-0000-0000-0000-000000000000')
track.files.append(File('test1.flac'))
self.assertFalse(track.update_metadata_images_from_children())
self.assertFalse(track.remove_metadata_images_from_children([track.files[0]]))
self.assertEqual(set(), set(track.orig_metadata.images))
self.assertTrue(track.orig_metadata.has_common_images)
def test_remove_from_album(self):
album = Album('00000000-0000-0000-0000-000000000000')
album.unmatched_files.files = list(self.test_files)
self.assertTrue(album.update_metadata_images_from_children())
album.unmatched_files.files.remove(self.test_files[0])
self.assertTrue(album.remove_metadata_images_from_children([self.test_files[0]]))
self.assertEqual(set(self.test_images[1:]), set(album.metadata.images))
self.assertEqual(set(self.test_images[1:]), set(album.orig_metadata.images))
self.assertTrue(album.metadata.has_common_images)
self.assertTrue(album.orig_metadata.has_common_images)
def test_remove_from_album_with_common_images(self):
album = Album('00000000-0000-0000-0000-000000000000')
album.unmatched_files.files = list(self.test_files[1:])
self.assertTrue(album.update_metadata_images_from_children())
album.unmatched_files.files.remove(self.test_files[1])
self.assertFalse(album.remove_metadata_images_from_children([self.test_files[1]]))
self.assertEqual(set(self.test_images[1:]), set(album.metadata.images))
self.assertEqual(set(self.test_images[1:]), set(album.orig_metadata.images))
self.assertTrue(album.metadata.has_common_images)
self.assertTrue(album.orig_metadata.has_common_images)
def test_remove_from_empty_album(self):
album = Album('00000000-0000-0000-0000-000000000000')
album.unmatched_files.files.append(File('test1.flac'))
self.assertFalse(album.update_metadata_images_from_children())
self.assertFalse(album.remove_metadata_images_from_children([album.unmatched_files.files[0]]))
self.assertEqual(set(), set(album.metadata.images))
self.assertEqual(set(), set(album.orig_metadata.images))
self.assertTrue(album.metadata.has_common_images)
self.assertTrue(album.orig_metadata.has_common_images)
class AddMetadataImagesTest(PicardTestCase):
def setUp(self):
super().setUp()
(self.test_images, self.test_files) = create_test_files()
def test_add_to_cluster(self):
cluster = Cluster('Test')
cluster.files = [self.test_files[0]]
self.assertTrue(cluster.update_metadata_images_from_children())
cluster.files += self.test_files[1:]
self.assertTrue(cluster.add_metadata_images_from_children(self.test_files[1:]))
self.assertEqual(set(self.test_images), set(cluster.metadata.images))
self.assertFalse(cluster.metadata.has_common_images)
def test_add_no_changes(self):
cluster = Cluster('Test')
cluster.files = self.test_files
self.assertTrue(cluster.update_metadata_images_from_children())
self.assertFalse(cluster.add_metadata_images_from_children([self.test_files[1]]))
self.assertEqual(set(self.test_images), set(cluster.metadata.images))
def test_add_nothing(self):
cluster = Cluster('Test')
cluster.files = self.test_files
self.assertTrue(cluster.update_metadata_images_from_children())
self.assertFalse(cluster.add_metadata_images_from_children([]))
class ImageListTest(PicardTestCase):
def setUp(self):
super().setUp()
self.imagelist = ImageList()
def create_image(name, types):
return CoverArtImage(
url='file://file' + name,
data=create_fake_png(name.encode('utf-8')),
types=types,
support_types=True,
support_multi_types=True
)
self.images = {
'a': create_image('a', ["booklet"]),
'b': create_image('b', ["booklet", "front"]),
'c': create_image('c', ["front", "booklet"]),
}
def test_append(self):
self.imagelist.append(self.images['a'])
self.assertEqual(self.imagelist[0], self.images['a'])
def test_eq(self):
list1 = ImageList()
list2 = ImageList()
list3 = ImageList()
list1.append(self.images['a'])
list1.append(self.images['b'])
list2.append(self.images['b'])
list2.append(self.images['a'])
list3.append(self.images['a'])
list3.append(self.images['c'])
self.assertEqual(list1, list2)
self.assertNotEqual(list1, list3)
def test_get_front_image(self):
self.imagelist.append(self.images['a'])
self.imagelist.append(self.images['b'])
self.assertEqual(self.imagelist.get_front_image(), self.images['b'])
def test_to_be_saved_to_tags(self):
def to_be_saved(settings):
return self.imagelist.to_be_saved_to_tags(settings=settings)
settings = {
"save_images_to_tags": True,
"embed_only_one_front_image": False,
}
# save all but no images
self.assertEqual(list(to_be_saved(settings)), [])
# save all, only one non-front image in the list
self.imagelist.append(self.images['a'])
self.assertEqual(list(to_be_saved(settings)), [self.images['a']])
# save all, 2 images, one of them is a front image (b)
self.imagelist.append(self.images['b'])
self.assertEqual(list(to_be_saved(settings)), [self.images['a'], self.images['b']])
# save only one front, 2 images, one of them is a front image (b)
settings["embed_only_one_front_image"] = True
self.assertEqual(list(to_be_saved(settings)), [self.images['b']])
# save only one front, 3 images, two of them have front type (b & c)
self.imagelist.append(self.images['c'])
self.assertEqual(list(to_be_saved(settings)), [self.images['b']])
# 3 images, but do not save
settings["save_images_to_tags"] = False
self.assertEqual(list(to_be_saved(settings)), [])
# settings is missing a setting
del settings["save_images_to_tags"]
with self.assertRaises(KeyError):
next(to_be_saved(settings))
def test_strip_front_images(self):
self.imagelist.append(self.images['a'])
self.imagelist.append(self.images['b'])
self.imagelist.append(self.images['c'])
# strip front images from list, only a isn't
self.assertEqual(len(self.imagelist), 3)
self.imagelist.strip_front_images()
self.assertNotIn(self.images['b'], self.imagelist)
self.assertNotIn(self.images['c'], self.imagelist)
self.assertIn(self.images['a'], self.imagelist)
self.assertEqual(len(self.imagelist), 1)
def test_imagelist_insert(self):
imagelist = ImageList()
imagelist.insert(0, 'a')
self.assertEqual(imagelist[0], 'a')
imagelist.insert(0, 'b')
self.assertEqual(imagelist[0], 'b')
self.assertEqual(imagelist[1], 'a')
def test_imagelist_clear(self):
imagelist = ImageList(['a', 'b'])
self.assertEqual(len(imagelist), 2)
imagelist.clear()
self.assertEqual(len(imagelist), 0)
def test_imagelist_copy(self):
imagelist1 = ImageList(['a', 'b'])
imagelist2 = imagelist1.copy()
imagelist3 = imagelist1
imagelist1[0] = 'c'
self.assertEqual(imagelist2[0], 'a')
self.assertEqual(imagelist3[0], 'c')
def test_imagelist_del(self):
imagelist = ImageList(['a', 'b'])
del imagelist[0]
self.assertEqual(imagelist[0], 'b')
self.assertEqual(len(imagelist), 1)
| 16,273
|
Python
|
.py
| 312
| 44.102564
| 102
| 0.684386
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,827
|
test_settingsoverride.py
|
metabrainz_picard/test/test_settingsoverride.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
# Copyright (C) 2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard import config
from picard.util.settingsoverride import SettingsOverride
class SettingsOverrideTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({'key1': 'origval1', 'key2': 'origval2'})
self.new_settings = {'key1': 'newval2'}
def test_read_orig_settings(self):
override = SettingsOverride(config.setting, self.new_settings)
self.assertEqual(override['key1'], 'newval2')
self.assertEqual(override['key2'], 'origval2')
with self.assertRaises(KeyError):
x = override['key3'] # noqa: F841
def test_read_orig_settings_kw(self):
override = SettingsOverride(config.setting, key1='newval2')
self.assertEqual(override['key1'], 'newval2')
self.assertEqual(override['key2'], 'origval2')
def test_write_orig_settings(self):
override = SettingsOverride(config.setting, self.new_settings)
override['key1'] = 'newval3'
self.assertEqual(override['key1'], 'newval3')
self.assertEqual(config.setting['key1'], 'origval1')
override['key2'] = 'newval4'
self.assertEqual(override['key2'], 'newval4')
self.assertEqual(config.setting['key2'], 'origval2')
override['key3'] = 'newval5'
self.assertEqual(override['key3'], 'newval5')
with self.assertRaises(KeyError):
x = config.setting['key3'] # noqa: F841
def test_del_orig_settings(self):
override = SettingsOverride(config.setting, self.new_settings)
override['key1'] = 'newval3'
self.assertEqual(override['key1'], 'newval3')
del override['key1']
self.assertEqual(override['key1'], 'origval1')
self.assertEqual(override['key2'], 'origval2')
del override['key2']
self.assertEqual(override['key2'], 'origval2')
| 2,766
|
Python
|
.py
| 59
| 41.101695
| 80
| 0.697364
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,828
|
test_util_bitreader.py
|
metabrainz_picard/test/test_util_bitreader.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from io import BytesIO
from test.picardtestcase import PicardTestCase
from picard.util.bitreader import (
LSBBitReader,
MSBBitReader,
)
class LsbBitReaderTest(PicardTestCase):
def test_msb_bit_reader(self):
data = BytesIO(b'\x8B\xC0\x17\x10')
reader = MSBBitReader(data)
self.assertEqual(8944, reader.bits(14))
self.assertEqual(369, reader.bits(14))
self.assertEqual(0, reader.bits(4))
def test_lsb_bit_reader(self):
data = BytesIO(b'\x8B\xC0\x17\x10')
reader = LSBBitReader(data)
self.assertEqual(139, reader.bits(14))
self.assertEqual(95, reader.bits(14))
self.assertEqual(1, reader.bits(4))
| 1,553
|
Python
|
.py
| 39
| 36.153846
| 80
| 0.73506
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,829
|
test_parsing_files_with_commands.py
|
metabrainz_picard/test/test_parsing_files_with_commands.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 skelly37
# Copyright (C) 2022 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util.remotecommands import RemoteCommands
class TestParsingFilesWithCommands(PicardTestCase):
TEST_FILE = 'test/data/test-command-file-1.txt'
def setUp(self):
super().setUp()
self.result = []
RemoteCommands.set_quit(False)
RemoteCommands.get_commands_from_file(self.TEST_FILE)
while not RemoteCommands.command_queue.empty():
(cmd, arg) = RemoteCommands.command_queue.get()
self.result.append(f"{cmd} {arg}")
RemoteCommands.command_queue.task_done()
def test_no_argument_command(self):
self.assertIn("CLUSTER ", self.result)
def test_no_argument_command_stripped_correctly(self):
self.assertIn("FINGERPRINT ", self.result)
def test_single_argument_command(self):
self.assertIn("LOAD file3.mp3", self.result)
def test_multiple_arguments_command(self):
self.assertIn("LOAD file1.mp3", self.result)
self.assertIn("LOAD file2.mp3", self.result)
def test_from_file_command_parsed(self):
self.assertNotIn("FROM_FILE command_file.txt", self.result)
self.assertNotIn("FROM_FILE test/data/test-command-file-1.txt", self.result)
self.assertNotIn("FROM_FILE test/data/test-command-file-2.txt", self.result)
def test_noting_added_after_quit(self):
self.assertNotIn("LOOKUP clustered", self.result)
def test_empty_lines(self):
self.assertNotIn(" ", self.result)
self.assertNotIn("", self.result)
self.assertEqual(len(self.result), 7)
def test_commented_lines(self):
self.assertNotIn("#commented command", self.result)
| 2,542
|
Python
|
.py
| 54
| 41.740741
| 84
| 0.720695
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,830
|
picardtestcase.py
|
metabrainz_picard/test/picardtestcase.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2019-2024 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
# Copyright (C) 2021 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify 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.
import json
import logging
import os
import shutil
import struct
from tempfile import (
mkdtemp,
mkstemp,
)
import unittest
from unittest.mock import (
MagicMock,
Mock,
)
from PyQt6 import QtCore
from picard import (
config,
log,
)
from picard.i18n import setup_gettext
from picard.releasegroup import ReleaseGroup
class FakeThreadPool(QtCore.QObject):
def start(self, runnable, priority):
runnable.run()
class FakeTagger(QtCore.QObject):
tagger_stats_changed = QtCore.pyqtSignal()
def __init__(self):
super().__init__()
self.tagger_stats_changed.connect(self.emit)
self.exit_cleanup = []
self.files = {}
self.stopping = False
self.thread_pool = FakeThreadPool()
self.priority_thread_pool = FakeThreadPool()
self.window = MagicMock()
self.webservice = MagicMock()
def register_cleanup(self, func):
self.exit_cleanup.append(func)
def run_cleanup(self):
for f in self.exit_cleanup:
f()
def emit(self, *args):
pass
def get_release_group_by_id(self, rg_id): # pylint: disable=no-self-use
return ReleaseGroup(rg_id)
class PicardTestCase(unittest.TestCase):
def setUp(self):
log.set_level(logging.DEBUG)
setup_gettext(None, 'C')
self.tagger = FakeTagger()
QtCore.QCoreApplication.instance = lambda: self.tagger
self.addCleanup(self.tagger.run_cleanup)
self.init_config()
@staticmethod
def init_config():
fake_config = Mock()
fake_config.setting = {}
fake_config.persist = {}
fake_config.profiles = {}
# Make config object available for legacy use
config.config = fake_config
config.setting = fake_config.setting
config.persist = fake_config.persist
config.profiles = fake_config.profiles
@staticmethod
def set_config_values(setting=None, persist=None, profiles=None):
if setting:
for key, value in setting.items():
config.config.setting[key] = value
if persist:
for key, value in persist.items():
config.config.persist[key] = value
if profiles:
for key, value in profiles.items():
config.config.profiles[key] = value
def mktmpdir(self, ignore_errors=False):
tmpdir = mkdtemp(suffix=self.__class__.__name__)
self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=ignore_errors)
return tmpdir
def copy_file_tmp(self, filepath, ext):
fd, copy = mkstemp(suffix=ext)
os.close(fd)
self.addCleanup(self.remove_file_tmp, copy)
shutil.copy(filepath, copy)
return copy
@staticmethod
def remove_file_tmp(filepath):
if os.path.isfile(filepath):
os.unlink(filepath)
def get_test_data_path(*paths):
return os.path.join('test', 'data', *paths)
def create_fake_png(extra):
"""Creates fake PNG data that satisfies Picard's internal image type detection"""
return b'\x89PNG\x0D\x0A\x1A\x0A' + (b'a' * 4) + b'IHDR' + struct.pack('>LL', 100, 100) + extra
def load_test_json(filename):
with open(get_test_data_path('ws_data', filename), encoding='utf-8') as f:
return json.load(f)
| 4,263
|
Python
|
.py
| 119
| 29.983193
| 99
| 0.677357
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,831
|
test_util_pipe.py
|
metabrainz_picard/test/test_util_pipe.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 skelly37
# Copyright (C) 2023 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import concurrent.futures
from platform import python_version
import time
import uuid
from test.picardtestcase import PicardTestCase
from picard.util import pipe
def pipe_listener(pipe_handler):
while True:
for message in pipe_handler.read_from_pipe():
if message and message != pipe.Pipe.NO_RESPONSE_MESSAGE:
return message
class TestPipe(PicardTestCase):
# some random name that is different on each run
NAME = str(uuid.uuid4())
VERSION = python_version()
def test_invalid_args(self):
# Pipe should be able to make args iterable (last argument)
self.assertRaises(pipe.PipeErrorInvalidArgs, pipe.Pipe, self.NAME, self.VERSION, 1)
self.assertRaises(pipe.PipeErrorInvalidAppData, pipe.Pipe, 21, self.VERSION, None)
self.assertRaises(pipe.PipeErrorInvalidAppData, pipe.Pipe, self.NAME, 21, None)
def test_pipe_protocol(self):
message = "foo"
__pool = concurrent.futures.ThreadPoolExecutor()
pipe_handler = pipe.Pipe(self.NAME, self.VERSION)
try:
plistener = __pool.submit(pipe_listener, pipe_handler)
time.sleep(.2)
res = ""
# handle the write/read processes
try:
pipe_handler.send_to_pipe(message)
res = plistener.result(timeout=6)
except concurrent.futures._base.TimeoutError:
pass
self.assertEqual(res, message,
"Data is sent and read correctly")
finally:
time.sleep(.2)
pipe_handler.stop()
__pool.shutdown()
| 2,500
|
Python
|
.py
| 60
| 35
| 91
| 0.687397
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,832
|
test_taggenrefilter.py
|
metabrainz_picard/test/test_taggenrefilter.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Wieland Hoffmann
# Copyright (C) 2019-2021 Laurent Monin
# Copyright (C) 2020-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from collections import Counter
from test.picardtestcase import PicardTestCase
from picard.track import TagGenreFilter
class TagGenreFilterTest(PicardTestCase):
def test_no_filter(self):
tag_filter = TagGenreFilter("# comment")
self.assertFalse(tag_filter.skip('jazz'))
def test_strict_filter(self):
tag_filter = TagGenreFilter("-jazz")
self.assertTrue(tag_filter.skip('jazz'))
def test_strict_filter_allowlist(self):
filters = """
+jazz
-jazz
"""
tag_filter = TagGenreFilter(filters)
self.assertFalse(tag_filter.skip('jazz'))
def test_strict_filter_allowlist_reverseorder(self):
filters = """
-jazz
+jazz
"""
tag_filter = TagGenreFilter(filters)
self.assertFalse(tag_filter.skip('jazz'))
def test_wildcard_filter_all_but(self):
filters = """
-*
+blues
"""
tag_filter = TagGenreFilter(filters)
self.assertTrue(tag_filter.skip('jazz'))
self.assertTrue(tag_filter.skip('rock'))
self.assertFalse(tag_filter.skip('blues'))
def test_wildcard_filter(self):
filters = """
-jazz*
-*rock
-*disco*
-a*b
"""
tag_filter = TagGenreFilter(filters)
self.assertTrue(tag_filter.skip('jazz'))
self.assertTrue(tag_filter.skip('jazz blues'))
self.assertFalse(tag_filter.skip('blues jazz'))
self.assertTrue(tag_filter.skip('rock'))
self.assertTrue(tag_filter.skip('blues rock'))
self.assertFalse(tag_filter.skip('rock blues'))
self.assertTrue(tag_filter.skip('disco'))
self.assertTrue(tag_filter.skip('xdisco'))
self.assertTrue(tag_filter.skip('discox'))
self.assertTrue(tag_filter.skip('ab'))
self.assertTrue(tag_filter.skip('axb'))
self.assertTrue(tag_filter.skip('axxb'))
self.assertFalse(tag_filter.skip('xab'))
def test_regex_filter(self):
filters = """
-/^j.zz/
-/r[io]ck$/
-/disco+/
+/discoooo/
"""
tag_filter = TagGenreFilter(filters)
self.assertTrue(tag_filter.skip('jazz'))
self.assertTrue(tag_filter.skip('jizz'))
self.assertTrue(tag_filter.skip('jazz blues'))
self.assertFalse(tag_filter.skip('blues jazz'))
self.assertTrue(tag_filter.skip('rock'))
self.assertTrue(tag_filter.skip('blues rock'))
self.assertTrue(tag_filter.skip('blues rick'))
self.assertFalse(tag_filter.skip('rock blues'))
self.assertTrue(tag_filter.skip('disco'))
self.assertTrue(tag_filter.skip('xdiscox'))
self.assertTrue(tag_filter.skip('xdiscooox'))
self.assertFalse(tag_filter.skip('xdiscoooox'))
def test_regex_filter_keep_all(self):
filters = """
-/^j.zz/
-/r[io]ck$/
-/disco+/
+/discoooo/
+/.*/
"""
tag_filter = TagGenreFilter(filters)
self.assertFalse(tag_filter.skip('jazz'))
self.assertFalse(tag_filter.skip('jizz'))
self.assertFalse(tag_filter.skip('jazz blues'))
self.assertFalse(tag_filter.skip('blues jazz'))
self.assertFalse(tag_filter.skip('rock'))
self.assertFalse(tag_filter.skip('blues rock'))
self.assertFalse(tag_filter.skip('blues rick'))
self.assertFalse(tag_filter.skip('rock blues'))
self.assertFalse(tag_filter.skip('disco'))
self.assertFalse(tag_filter.skip('xdiscox'))
self.assertFalse(tag_filter.skip('xdiscooox'))
self.assertFalse(tag_filter.skip('xdiscoooox'))
def test_uppercased_filter(self):
filters = """
-JAZZ*
-ROCK
-/^DISCO$/
"""
tag_filter = TagGenreFilter(filters)
self.assertTrue(tag_filter.skip('jazz blues'))
self.assertTrue(tag_filter.skip('JAZZ BLUES'))
self.assertTrue(tag_filter.skip('rock'))
self.assertTrue(tag_filter.skip('ROCK'))
self.assertTrue(tag_filter.skip('disco'))
self.assertTrue(tag_filter.skip('DISCO'))
def test_whitespaces_filter(self):
filters = """
- jazz b*
- * ro ck
- /^di sco$/
"""
tag_filter = TagGenreFilter(filters)
self.assertTrue(tag_filter.skip('jazz blues'))
self.assertTrue(tag_filter.skip('blues ro ck'))
self.assertTrue(tag_filter.skip('di sco'))
self.assertFalse(tag_filter.skip('bluesro ck'))
def test_filter_method(self):
tag_filter = TagGenreFilter("-a*")
genres = Counter(ax=1, bx=2, ay=3, by=4)
result = tag_filter.filter(genres)
self.assertEqual([('bx', 2), ('by', 4)], list(result.items()))
def test_filter_method_minusage(self):
tag_filter = TagGenreFilter("-a*")
genres = Counter(ax=4, bx=5, ay=20, by=10, bz=4)
result = tag_filter.filter(genres, minusage=50)
self.assertEqual([('bx', 5), ('by', 10)], list(result.items()))
def test_filter_method_empty_input(self):
tag_filter = TagGenreFilter("")
genres = Counter()
result = tag_filter.filter(genres)
self.assertEqual([], list(result.items()))
def test_filter_method_empty_result(self):
tag_filter = TagGenreFilter("-*")
genres = Counter(ax=1, bx=2, ay=3, by=4)
result = tag_filter.filter(genres)
self.assertEqual([], list(result.items()))
| 6,500
|
Python
|
.py
| 160
| 32.4
| 80
| 0.62603
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,833
|
test_textencoding.py
|
metabrainz_picard/test/test_textencoding.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2015, 2018, 2020-2021 Laurent Monin
# Copyright (C) 2017 Ville Skyttä
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2019, 2021 Philipp Wolfer
# Copyright (C) 2020 Undearius
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard import util
from picard.const.sys import IS_WIN
# Set the value to true below to show the coverage of Latin characters
show_latin2ascii_coverage = False
compatibility_from = (
"\u0132\u0133\u017F\u01C7\u01C8\u01C9\u01CA\u01CB\u01CC\u01F1" # IJijſLJLjljNJNjnjDZ
"\u01F2\u01F3\uFB00\uFB01\uFB02\uFB03\uFB04\uFB05\uFB06\uFF21" # DzdzfffiflffifflſtstA
"\uFF22\uFF23\uFF24\uFF25\uFF26\uFF27\uFF28\uFF29\uFF2A\uFF2B" # BCDEFGHIJK
"\uFF2C\uFF2D\uFF2E\uFF2F\uFF30\uFF31\uFF32\uFF33\uFF34\uFF35" # LMNOPQRSTU
"\uFF36\uFF37\uFF38\uFF39\uFF3A\uFF41\uFF42\uFF43\uFF44\uFF45" # VWXYZabcde
"\uFF46\uFF47\uFF48\uFF49\uFF4A\uFF4B\uFF4C\uFF4D\uFF4E\uFF4F" # fghijklmno
"\uFF50\uFF51\uFF52\uFF53\uFF54\uFF55\uFF56\uFF57\uFF58\uFF59" # pqrstuvwxy
"\uFF5A\u2100\u2101\u2102\u2105\u2106\u210A\u210B\u210C\u210D" # z℀℁ℂ℅℆ℊℋℌℍ
"\u210E\u2110\u2111\u2112\u2113\u2115\u2116\u2119\u211A\u211B" # ℎℐℑℒℓℕ№ℙℚℛ
"\u211C\u211D\u2121\u2124\u2128\u212C\u212D\u212F\u2130\u2131" # ℜℝ℡ℤℨℬℭℯℰℱ
"\u2133\u2134\u2139\u213B\u2145\u2146\u2147\u2148\u2149\u3371" # ℳℴℹ℻ⅅⅆⅇⅈⅉ㍱
"\u3372\u3373\u3374\u3375\u3376\u3377\u337A\u3380\u3381\u3383" # ㍲㍳㍴㍵㍶㍷㍺㎀㎁㎃
"\u3384\u3385\u3386\u3387\u3388\u3389\u338A\u338B\u338E\u338F" # ㎄㎅㎆㎇㎈㎉㎊㎋㎎㎏
"\u3390\u3391\u3392\u3393\u3394\u3399\u339A\u339C\u339D\u339E" # ㎐㎑㎒㎓㎔㎙㎚㎜㎝㎞
"\u33A9\u33AA\u33AB\u33AC\u33AD\u33B0\u33B1\u33B3\u33B4\u33B5" # ㎩㎪㎫㎬㎭㎰㎱㎳㎴㎵
"\u33B7\u33B8\u33B9\u33BA\u33BB\u33BD\u33BE\u33BF\u33C2\u33C3" # ㎷㎸㎹㎺㎻㎽㎾㎿㏂㏃
"\u33C4\u33C5\u33C7\u33C8\u33C9\u33CA\u33CB\u33CC\u33CD\u33CE" # ㏄㏅㏇㏈㏉㏊㏋㏌㏍㏎
"\u33CF\u33D0\u33D1\u33D2\u33D3\u33D4\u33D5\u33D6\u33D7\u33D8" # ㏏㏐㏑㏒㏓㏔㏕㏖㏗㏘
"\u33D9\u33DA\u33DB\u33DC\u33DD\u249C\u249D\u249E\u249F\u24A0" # ㏙㏚㏛㏜㏝⒜⒝⒞⒟⒠
"\u24A1\u24A2\u24A3\u24A4\u24A5\u24A6\u24A7\u24A8\u24A9\u24AA" # ⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪
"\u24AB\u24AC\u24AD\u24AE\u24AF\u24B0\u24B1\u24B2\u24B3\u24B4" # ⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴
"\u24B5\u2160\u2161\u2162\u2163\u2164\u2165\u2166\u2167\u2168" # ⒵ⅠⅡⅢⅣⅤⅥⅦⅧⅨ
"\u2169\u216A\u216B\u216C\u216D\u216E\u216F\u2170\u2171\u2172" # ⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲ
"\u2173\u2174\u2175\u2176\u2177\u2178\u2179\u217A\u217B\u217C" # ⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼ
"\u217D\u217E\u217F\u2474\u2475\u2476\u2477\u2478\u2479\u247A" # ⅽⅾⅿ⑴⑵⑶⑷⑸⑹⑺
"\u247B\u247C\u247D\u247E\u247F\u2480\u2481\u2482\u2483\u2484" # ⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄
"\u2485\u2486\u2487\u2488\u2489\u248A\u248B\u248C\u248D\u248E" # ⒅⒆⒇⒈⒉⒊⒋⒌⒍⒎
"\u248F\u2490\u2491\u2492\u2493\u2494\u2495\u2496\u2497\u2498" # ⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘
"\u2499\u249A\u249B\uFF10\uFF11\uFF12\uFF13\uFF14\uFF15\uFF16" # ⒙⒚⒛0123456
"\uFF17\uFF18\uFF19\u2002\u2003\u2004\u2005\u2006\u2007\u2008" # 789\u2002\u2003\u2004\u2005\u2006\u2007\u2008
"\u2009\u200A\u205F\uFF02\uFF07\uFE63\uFF0D\u2024\u2025\u2026" # \u2009\u200A\u205F"'﹣-․‥…
"\u203C\u2047\u2048\u2049\uFE10\uFE13\uFE14\uFE15\uFE16\uFE19" # ‼⁇⁈⁉︐︓︔︕︖︙
"\uFE30\uFE35\uFE36\uFE37\uFE38\uFE47\uFE48\uFE50\uFE52\uFE54" # ︰︵︶︷︸﹇﹈﹐﹒﹔
"\uFE55\uFE56\uFE57\uFE59\uFE5A\uFE5B\uFE5C\uFE5F\uFE60\uFE61" # ﹕﹖﹗﹙﹚﹛﹜﹟﹠﹡
"\uFE62\uFE64\uFE65\uFE66\uFE68\uFE69\uFE6A\uFE6B\uFF01\uFF03" # ﹢﹤﹥﹦﹨﹩﹪﹫!#
"\uFF04\uFF05\uFF06\uFF08\uFF09\uFF0A\uFF0B\uFF0C\uFF0E\uFF0F" # $%&()*+,./
"\uFF1A\uFF1B\uFF1C\uFF1D\uFF1E\uFF1F\uFF20\uFF3B\uFF3C\uFF3D" # :;<=>?@[\]
"\uFF3E\uFF3F\uFF40\uFF5B\uFF5C\uFF5D\uFF5E\u2A74\u2A75\u2A76" # ^_`{|}~⩴⩵⩶
)
compatibility_to = (
"IJijsLJLjljNJNjnjDZDzdzfffiflffifflststABCDEFGHIJKLMNOPQRSTU"
"VWXYZabcdefghijklmnopqrstuvwxyza/ca/sCc/oc/ugHHH"
"hIILlNNoPQRRRTELZZBCeEFMoiFAXDdeijhPadaAUbaroVpcdmIUpAnAmA"
"kAKBMBGBcalkcalpFnFmgkgHzkHzMHzGHzTHzfmnmmmcmkmPakPaMPaGParadpsnsmspVnVmVkVMVpWnWmWkWMWa.m.Bq"
"cccdCo.dBGyhaHPinKKKMktlmlnloglxmbmilmolPHp.m.PPMPRsrSvWb(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)"
"(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)IIIIIIIVVVIVIIVIIIIXXXIXIILCDMiiiiiiivvviviiviiiixxxixiil"
"cdm(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17."
"18.19.20.0123456789 \"'--......!!???!!?,:;!?..."
"..(){}[],.;:?!(){}#&*+<>=\\$%@!#$%&()*+,./"
":;<=>?@[\\]^_`{|}~::======"
)
compatibility_from += (
"\u1D00\u1D04\u1D05\u1D07\u1D0A\u1D0B\u1D0D\u1D0F\u1D18\u1D1B" # ᴀᴄᴅᴇᴊᴋᴍᴏᴘᴛ
"\u1D1C\u1D20\u1D21\u1D22\u3007\u00A0\u3000" # ᴜᴠᴡᴢ〇\u00A0\u3000
)
compatibility_to += "ACDEJKMOPTUVWZ0 "
punctuation_from = (
"\u2018\u2019\u201A\u201B\u201C\u201D\u201E\u201F\u2032\u301D" # ‘’‚‛“”„‟′〝
"\u301E\u00AB\u00BB\u2039\u203A\u00AD\u2010\u2012\u2013\u2014" # 〞«»‹›\u00AD‐‒–—
"\u2015\u2016\u2044\u2045\u2046\u204E\u3008\u3009\u300A\u300B" # ―‖⁄⁅⁆⁎〈〉《》
"\u3014\u3015\u3018\u3019\u301A\u301B\u2212\u2215\u2216\u2223" # 〔〕〘〙〚〛−∕∖∣
"\u2225\u226A\u226B\u2985\u2986\u2022\u200B" # ∥≪≫⦅⦆•·
)
punctuation_to = "''''\"\"\"\"'\"\"<<>><>-----||/[]*<><<>>[][][]-/\\|||<<>>(())-"
combinations_from = (
"\u00C6\u00D0\u00D8\u00DE\u00DF\u00E6\u00F0\u00F8\u00FE\u0110" # ÆÐØÞßæðøþĐ
"\u0111\u0126\u0127\u0131\u0138\u0141\u0142\u014A\u014B\u0152" # đĦħıĸŁłŊŋŒ
"\u0153\u0166\u0167\u0180\u0181\u0182\u0183\u0187\u0188\u0189" # œŦŧƀƁƂƃƇƈƉ
"\u018A\u018B\u018C\u0190\u0191\u0192\u0193\u0195\u0196\u0197" # ƊƋƌƐƑƒƓƕƖƗ
"\u0198\u0199\u019A\u019D\u019E\u01A2\u01A3\u01A4\u01A5\u01AB" # ƘƙƚƝƞƢƣƤƥƫ
"\u01AC\u01AD\u01AE\u01B2\u01B3\u01B4\u01B5\u01B6\u01E4\u01E5" # ƬƭƮƲƳƴƵƶǤǥ
"\u0221\u0224\u0225\u0234\u0235\u0236\u0237\u0238\u0239\u023A" # ȡȤȥȴȵȶȷȸȹȺ
"\u023B\u023C\u023D\u023E\u023F\u0240\u0243\u0244\u0246\u0247" # ȻȼȽȾȿɀɃɄɆɇ
"\u0248\u0249\u024C\u024D\u024E\u024F\u0253\u0255\u0256\u0257" # ɈɉɌɍɎɏɓɕɖɗ
"\u025B\u025F\u0260\u0261\u0262\u0266\u0267\u0268\u026A\u026B" # ɛɟɠɡɢɦɧɨɪɫ
"\u026C\u026D\u0271\u0272\u0273\u0274\u027C\u027D\u027E\u0280" # ɬɭɱɲɳɴɼɽɾʀ
"\u0282\u0288\u0289\u028B\u028F\u0290\u0291\u0299\u029B\u029C" # ʂʈʉʋʏʐʑʙʛʜ
"\u029D\u029F\u02A0\u02A3\u02A5\u02A6\u02AA\u02AB\u1D03\u1D06" # ʝʟʠʣʥʦʪʫᴃᴆ
"\u1D0C\u1D6B\u1D6C\u1D6D\u1D6E\u1D6F\u1D70\u1D71\u1D72\u1D73" # ᴌᵫᵬᵭᵮᵯᵰᵱᵲᵳ
"\u1D74\u1D75\u1D76\u1D7A\u1D7B\u1D7D\u1D7E\u1D80\u1D81\u1D82" # ᵴᵵᵶᵺᵻᵽᵾᶀᶁᶂ
"\u1D83\u1D84\u1D85\u1D86\u1D87\u1D88\u1D89\u1D8A\u1D8C\u1D8D" # ᶃᶄᶅᶆᶇᶈᶉᶊᶌᶍ
"\u1D8E\u1D8F\u1D91\u1D92\u1D93\u1D96\u1D99\u1E9C\u1E9D\u1E9E" # ᶎᶏᶑᶒᶓᶖᶙẜẝẞ
"\u1EFA\u1EFB\u1EFC\u1EFD\u1EFE\u1EFF\u00A9\u00AE\u20A0\u20A2" # ỺỻỼỽỾỿ©®₠₢
"\u20A3\u20A4\u20A7\u20BA\u20B9\u211E\u3001\u3002\u00D7\u00F7" # ₣₤₧₺₹℞、。×÷
"\u00B7\u1E9F\u0184\u0185\u01BE" # ·ẟƄƅƾ
)
combinations_to = (
"AEDOETHssaedoethDdHhiqLlNnOEoeTtbBBbCcDDDdEFfGhvII"
"KklNnGHghPptTtTVYyZzGgdZzlntjdbqpACcLTszBUEe"
"JjRrYybcddejggGhhiIlllmnnNrrrRstuvYzzBGH"
"jLqdzdztslslzBDLuebdfmnprrstzthIpUbdfgklmnprsvx"
"zadeeiussSSLLllVvYy(C)(R)CECrFr.L.PtsTLRsRx,.x/.ddHhts"
)
ascii_chars = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
class CompatibilityTest(PicardTestCase):
def test_correct(self):
self.maxDiff = None
self.assertEqual(util.textencoding.unicode_simplify_compatibility(compatibility_from), compatibility_to)
self.assertEqual(util.textencoding.unicode_simplify_compatibility(punctuation_from), punctuation_from)
self.assertEqual(util.textencoding.unicode_simplify_compatibility(combinations_from), combinations_from)
self.assertEqual(util.textencoding.unicode_simplify_compatibility(ascii_chars), ascii_chars)
def test_pathsave(self):
self.assertEqual(util.textencoding.unicode_simplify_compatibility('\uff0f', pathsave=True), '_')
def test_incorrect(self):
pass
class PunctuationTest(PicardTestCase):
def test_correct(self):
self.maxDiff = None
self.assertEqual(util.textencoding.unicode_simplify_punctuation(compatibility_from), compatibility_from)
self.assertEqual(util.textencoding.unicode_simplify_punctuation(punctuation_from), punctuation_to)
self.assertEqual(util.textencoding.unicode_simplify_punctuation(combinations_from), combinations_from)
self.assertEqual(util.textencoding.unicode_simplify_punctuation(ascii_chars), ascii_chars)
def test_pathsave(self):
self.assertEqual(util.textencoding.unicode_simplify_punctuation('\u2215\u2216', True), '__' if IS_WIN else '_\\')
self.assertEqual(util.textencoding.unicode_simplify_punctuation('/\\\u2215\u2216', True), '/\\__' if IS_WIN else '/\\_\\')
def test_pathsave_win_compat(self):
self.assertEqual(util.textencoding.unicode_simplify_punctuation('\u2215\u2216', True, True), '__')
self.assertEqual(util.textencoding.unicode_simplify_punctuation('/\\\u2215\u2216', True, True), '/\\__')
def test_incorrect(self):
pass
class CombinationsTest(PicardTestCase):
def test_correct(self):
self.maxDiff = None
self.assertEqual(util.textencoding.unicode_simplify_combinations(combinations_from), combinations_to)
self.assertEqual(util.textencoding.unicode_simplify_combinations(compatibility_from), compatibility_from)
self.assertEqual(util.textencoding.unicode_simplify_combinations(punctuation_from), punctuation_from)
self.assertEqual(util.textencoding.unicode_simplify_combinations(ascii_chars), ascii_chars)
def test_pathsave(self):
self.assertEqual(util.textencoding.unicode_simplify_combinations('8½', True), '8 1_2')
self.assertEqual(util.textencoding.unicode_simplify_combinations('8/\\½', True), '8/\\ 1_2')
def test_incorrect(self):
pass
class AsciiPunctTest(PicardTestCase):
def test_correct(self):
self.assertEqual(util.textencoding.asciipunct("‘Test’"), "'Test'") # Quotations
self.assertEqual(util.textencoding.asciipunct("“Test”"), "\"Test\"") # Quotations
self.assertEqual(util.textencoding.asciipunct("1′6″"), "1'6\"") # Quotations
self.assertEqual(util.textencoding.asciipunct("…"), "...") # Ellipses
self.assertEqual(util.textencoding.asciipunct("\u2024"), ".") # ONE DOT LEADER
self.assertEqual(util.textencoding.asciipunct("\u2025"), "..") # TWO DOT LEADER
def test_incorrect(self):
pass
class UnaccentTest(PicardTestCase):
def test_correct(self):
self.assertEqual(util.textencoding.unaccent("Lukáš"), "Lukas")
self.assertEqual(util.textencoding.unaccent("Björk"), "Bjork")
self.assertEqual(util.textencoding.unaccent("小室哲哉"), "小室哲哉")
def test_incorrect(self):
self.assertNotEqual(util.textencoding.unaccent("Björk"), "Björk")
self.assertNotEqual(util.textencoding.unaccent("小室哲哉"), "Tetsuya Komuro")
self.assertNotEqual(util.textencoding.unaccent("Trentemøller"), "Trentemoller")
self.assertNotEqual(util.textencoding.unaccent("Ænima"), "AEnima")
self.assertNotEqual(util.textencoding.unaccent("ænima"), "aenima")
class ReplaceNonAsciiTest(PicardTestCase):
def test_correct(self):
self.assertEqual(util.textencoding.replace_non_ascii("Lukáš"), "Lukas")
self.assertEqual(util.textencoding.replace_non_ascii("Björk"), "Bjork")
self.assertEqual(util.textencoding.replace_non_ascii("Trentemøller"), "Trentemoeller")
self.assertEqual(util.textencoding.replace_non_ascii("Ænima"), "AEnima")
self.assertEqual(util.textencoding.replace_non_ascii("ænima"), "aenima")
self.assertEqual(util.textencoding.replace_non_ascii("小室哲哉"), "____")
self.assertEqual(util.textencoding.replace_non_ascii("ᴀᴄᴇ"), "ACE") # Latin Letter Small
self.assertEqual(util.textencoding.replace_non_ascii("Abc"), "Abc") # Fullwidth Latin
self.assertEqual(util.textencoding.replace_non_ascii("500㎏,2㎓"), "500kg,2GHz") # Technical
self.assertEqual(util.textencoding.replace_non_ascii("⒜⒝⒞"), "(a)(b)(c)") # Parenthesised Latin
self.assertEqual(util.textencoding.replace_non_ascii("ⅯⅯⅩⅣ"), "MMXIV") # Roman numerals
self.assertEqual(util.textencoding.replace_non_ascii("ⅿⅿⅹⅳ"), "mmxiv") # Roman numerals small
self.assertEqual(util.textencoding.replace_non_ascii("⑴⑵⑶"), "(1)(2)(3)") # Parenthesised numbers
self.assertEqual(util.textencoding.replace_non_ascii("⒈ ⒉ ⒊"), "1. 2. 3.") # Digit full stop
self.assertEqual(util.textencoding.replace_non_ascii("123"), "123") # Fullwidth digits
self.assertEqual(util.textencoding.replace_non_ascii("\u2216\u2044\u2215\uff0f"), "\\///") # Slashes
def test_pathsave(self):
expected = '____/8 1_2\\' if IS_WIN else '\\___/8 1_2\\'
self.assertEqual(util.textencoding.replace_non_ascii('\u2216\u2044\u2215\uff0f/8½\\', pathsave=True), expected)
def test_win_compat(self):
self.assertEqual(util.textencoding.replace_non_ascii('\u2216\u2044\u2215\uff0f/8½\\', pathsave=True, win_compat=True), '____/8 1_2\\')
def test_incorrect(self):
self.assertNotEqual(util.textencoding.replace_non_ascii("Lukáš"), "Lukáš")
self.assertNotEqual(util.textencoding.replace_non_ascii("Lukáš"), "Luk____")
if show_latin2ascii_coverage:
# The following code set blocks are taken from:
# http://en.wikipedia.org/wiki/Latin_script_in_Unicode
latin_1 = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
latin_a = "ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿ" \
"ŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽž"
latin_b = "ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿ" \
"ǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿ" \
"ȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿ" \
"ɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏ"
ipa_ext = "ɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏ" \
"ʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯ"
phonetic = "ᴀᴁᴂᴃᴄᴅᴆᴇᴈᴉᴊᴋᴌᴍᴎᴏᴐᴑᴒᴓᴔᴕᴖᴗᴘᴙᴚᴛᴜᴝᴞᴟᴠᴡᴢᴣᴤᴥᴦᴧᴨᴩᴪᴫᴬᴭᴮᴯᴰᴱᴲᴳᴴᴵᴶᴷᴸᴹᴺᴻᴼᴽᴾᴿ" \
"ᵀᵁᵂᵃᵄᵅᵆᵇᵈᵉᵊᵋᵌᵍᵎᵏᵐᵑᵒᵓᵔᵕᵖᵗᵘᵙᵚᵛᵜᵝᵞᵟᵠᵡᵢᵣᵤᵥᵦᵧᵨᵩᵪᵫᵬᵭᵮᵯᵰᵱᵲᵳᵴᵵᵶᵷᵸᵹᵺᵻᵼᵽᵾᵿ" \
"ᶀᶁᶂᶃᶄᶅᶆᶇᶈᶉᶊᶋᶌᶍᶎᶏᶐᶑᶒᶓᶔᶕᶖᶗᶘᶙᶚᶛᶜᶝᶞᶟᶠᶡᶢᶣᶤᶥᶦᶧᶨᶩᶪᶫᶬᶭᶮᶯᶰᶱᶲᶳᶴᶵᶶᶷᶸᶹᶺᶻᶼᶽᶾᶿ"
latin_ext_add = "ḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḤḦḧḨḩḪḫḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿ" \
"ṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿ" \
"ẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕẖẗẘẙẚẛẜẝẞẟẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾế" \
"ỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹỺỻỼỽỾỿ"
letter_like = "℀℁ℂ℃℄℅℆ℇ℈℉ℊℋℌℍℎℏℐℑℒℓ℔ℕ№℗℘ℙℚℛℜℝ℞℟℠℡™℣ℤ℥Ω℧ℨ℩KÅℬℭ℮ℯℰℱℲℳℴℵℶℷℸℹ℺℻ℼℽℾℿ" \
"⅀⅁⅂⅃⅄ⅅⅆⅇⅈⅉ⅊⅋⅌⅍ⅎ⅏"
enclosed = "⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ" \
"ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ⓪⓫⓬⓭⓮⓯"
print("The following lines show the coverage of Latin characters conversion to ascii.")
print("Underscores are characters which currently do not have an ASCII representation.")
print()
print("latin-1: ", util.textencoding.replace_non_ascii(latin_1))
print("latin-1: ", util.textencoding.replace_non_ascii(latin_1))
print("latin-a: ", util.textencoding.replace_non_ascii(latin_a))
print("latin-b: ", util.textencoding.replace_non_ascii(latin_b))
print("ipa-ext: ", util.textencoding.replace_non_ascii(ipa_ext))
print("phonetic: ", util.textencoding.replace_non_ascii(phonetic))
print("latin-ext-add: ", util.textencoding.replace_non_ascii(latin_ext_add))
print("letter-like: ", util.textencoding.replace_non_ascii(letter_like))
print("enclosed: ", util.textencoding.replace_non_ascii(enclosed))
print()
| 19,648
|
Python
|
.py
| 245
| 62.15102
| 142
| 0.705911
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,834
|
test_amazon_urls.py
|
metabrainz_picard/test/test_amazon_urls.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2018, 2020-2021 Laurent Monin
# Copyright (C) 2016 barami
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util import parse_amazon_url
class ParseAmazonUrlTest(PicardTestCase):
def test_1(self):
url = 'http://www.amazon.com/dp/020530902X'
expected = {'asin': '020530902X', 'host': 'amazon.com'}
r = parse_amazon_url(url)
self.assertEqual(r, expected)
def test_2(self):
url = 'http://ec1.amazon.co.jp/gp/product/020530902X'
expected = {'asin': '020530902X', 'host': 'ec1.amazon.co.jp'}
r = parse_amazon_url(url)
self.assertEqual(r, expected)
def test_3(self):
url = 'http://amazon.com/Dark-Side-Moon-Pink-Floyd/dp/B004ZN9RWK/ref=sr_1_1?s=music&ie=UTF8&qid=1372605047&sr=1-1&keywords=pink+floyd+dark+side+of+the+moon'
expected = {'asin': 'B004ZN9RWK', 'host': 'amazon.com'}
r = parse_amazon_url(url)
self.assertEqual(r, expected)
def test_4(self):
url = 'https://www.amazon.co.jp/gp/product/B00005FMYV'
expected = {'asin': 'B00005FMYV', 'host': 'amazon.co.jp'}
r = parse_amazon_url(url)
self.assertEqual(r, expected)
def test_incorrect_asin_1(self):
url = 'http://www.amazon.com/dp/A20530902X'
expected = None
r = parse_amazon_url(url)
self.assertEqual(r, expected)
def test_incorrect_asin_2(self):
url = 'http://www.amazon.com/dp/020530902x'
expected = None
r = parse_amazon_url(url)
self.assertEqual(r, expected)
def test_incorrect_url_scheme(self):
url = 'httpsa://www.amazon.co.jp/gp/product/B00005FMYV'
expected = None
r = parse_amazon_url(url)
self.assertEqual(r, expected)
| 2,633
|
Python
|
.py
| 60
| 38.483333
| 164
| 0.684889
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,835
|
test_versions.py
|
metabrainz_picard/test/test_versions.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013-2014, 2018-2020 Laurent Monin
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import unittest
from test.picardtestcase import PicardTestCase
from picard import (
api_versions,
api_versions_tuple,
)
from picard.version import (
Version,
VersionError,
)
class VersionsTest(PicardTestCase):
def test_version_conversion(self):
versions = (
(Version(1, 1, 0, 'final', 0), '1.1.0.final0'),
(Version(0, 0, 1, 'dev', 1), '0.0.1.dev1'),
(Version(1, 1, 0, 'dev', 0), '1.1.0.dev0'),
(Version(999, 999, 999, 'dev', 999), '999.999.999.dev999'),
(Version(1, 1, 2, 'alpha', 2), '1.1.2.alpha2'),
(Version(1, 1, 2, 'a', 2), '1.1.2.alpha2'),
(Version(1, 1, 2, 'beta', 2), '1.1.2.beta2'),
(Version(1, 1, 2, 'b', 2), '1.1.2.beta2'),
(Version(1, 1, 2, 'rc', 2), '1.1.2.rc2'),
)
for v, s in versions:
self.assertEqual(str(v), s)
self.assertEqual(v, Version.from_string(s))
def test_version_conversion_short(self):
versions = (
(Version(1, 1, 0, 'final', 0), '1.1'),
(Version(1, 1, 1, 'final', 0), '1.1.1'),
(Version(0, 0, 1, 'dev', 1), '0.0.1.dev1'),
(Version(1, 1, 0, 'dev', 0), '1.1.0.dev0'),
(Version(1, 1, 2, 'alpha', 2), '1.1.2a2'),
(Version(1, 1, 2, 'a', 2), '1.1.2a2'),
(Version(1, 1, 2, 'beta', 2), '1.1.2b2'),
(Version(1, 1, 2, 'b', 2), '1.1.2b2'),
(Version(1, 1, 2, 'rc', 2), '1.1.2rc2'),
)
for v, s in versions:
self.assertEqual(v.short_str(), s)
self.assertEqual(v, Version.from_string(s))
def test_version_from_string_underscores(self):
l, s = (1, 1, 0, 'dev', 0), '1_1_0_dev_0'
self.assertEqual(l, Version.from_string(s))
def test_version_from_string_prefixed_with_num(self):
self.assertRaises(VersionError, Version.from_string, '8_1_1_0_dev_0')
def test_version_from_string_suffixed_with_num(self):
self.assertRaises(VersionError, Version.from_string, '1_1_0_dev_0_8')
def test_version_from_string_prefixed_with_alpha(self):
self.assertRaises(VersionError, Version.from_string, 'a_1_1_0_dev_0')
def test_version_from_string_suffixed_with_alpha(self):
self.assertRaises(VersionError, Version.from_string, '1_1_0_dev_0_a')
def test_version_single_digit(self):
l, s = (2, 0, 0, 'final', 0), '2'
self.assertEqual(l, Version.from_string(s))
self.assertEqual(l, Version(2))
def test_from_string_invalid_identifier(self):
self.assertRaises(VersionError, Version.from_string, '1.1.0dev')
self.assertRaises(VersionError, Version.from_string, '1.1.0devx')
def test_version_from_string_invalid_partial(self):
self.assertRaises(VersionError, Version.from_string, '1dev')
self.assertRaises(VersionError, Version.from_string, '1.0dev')
self.assertRaises(VersionError, Version.from_string, '123.')
@unittest.skipUnless(len(api_versions) > 1, "api_versions do not have enough elements")
def test_api_versions_1(self):
"""Check api versions format and order (from oldest to newest)"""
for i in range(len(api_versions) - 1):
a = Version.from_string(api_versions[i])
b = Version.from_string(api_versions[i+1])
self.assertLess(a, b)
@unittest.skipUnless(len(api_versions_tuple) > 1, "api_versions_tuple do not have enough elements")
def test_api_versions_tuple_1(self):
"""Check api versions format and order (from oldest to newest)"""
for i in range(len(api_versions_tuple) - 1):
a = api_versions_tuple[i]
b = api_versions_tuple[i+1]
self.assertLess(a, b)
def test_version_invalid_new(self):
self.assertRaises(VersionError, Version, '1', 'a')
self.assertRaises(VersionError, Version, None, 0)
self.assertRaises(VersionError, Version, 1, 0, 0, 'final', None)
self.assertRaises(VersionError, Version, 1, 0, 0, 'invalid', 0)
def test_sortkey(self):
self.assertEqual((2, 1, 3, 4, 2), Version(2, 1, 3, 'final', 2).sortkey)
self.assertEqual((2, 0, 0, 1, 0), Version(2, 0, 0, 'a', 0).sortkey)
self.assertEqual((2, 0, 0, 1, 0), Version(2, 0, 0, 'alpha', 0).sortkey)
def test_lt(self):
v1 = Version(2, 3, 0, 'dev', 1)
v2 = Version(2, 3, 0, 'alpha', 1)
self.assertLess(v1, v2)
self.assertFalse(v2 < v2)
v1 = Version(2, 3, 0, 'final', 1)
v2 = Version(2, 10, 0, 'final', 1)
self.assertLess(v1, v2)
def test_le(self):
v1 = Version(2, 3, 0, 'dev', 1)
v2 = Version(2, 3, 0, 'alpha', 1)
self.assertLessEqual(v1, v2)
self.assertLessEqual(v2, v2)
def test_gt(self):
v1 = Version(2, 3, 0, 'alpha', 1)
v2 = Version(2, 3, 0, 'dev', 1)
self.assertGreater(v1, v2)
self.assertFalse(v2 > v2)
def test_ge(self):
v1 = Version(2, 3, 0, 'alpha', 1)
v2 = Version(2, 3, 0, 'dev', 1)
self.assertGreaterEqual(v1, v2)
self.assertGreaterEqual(v2, v2)
def test_eq(self):
v1 = Version(2, 3, 0, 'alpha', 1)
v2 = Version(2, 3, 0, 'a', 1)
v3 = Version(2, 3, 0, 'final', 1)
self.assertEqual(v1, v1)
self.assertEqual(v1, v2)
self.assertFalse(v1 == v3)
def test_ne(self):
v1 = Version(2, 3, 0, 'alpha', 1)
v2 = Version(2, 3, 0, 'a', 1)
v3 = Version(2, 3, 0, 'final', 1)
self.assertFalse(v1 != v1)
self.assertFalse(v1 != v2)
self.assertTrue(v1 != v3)
| 6,619
|
Python
|
.py
| 145
| 37.993103
| 103
| 0.601707
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,836
|
test_tagsfromfilenames.py
|
metabrainz_picard/test/test_tagsfromfilenames.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.ui.tagsfromfilenames import TagMatchExpression
class TagMatchExpressionTest(PicardTestCase):
def test_parse_tags(self):
expression = TagMatchExpression(r'%tracknumber% - %title%')
expected_tags = ['tracknumber', 'title']
self.assertEqual(expected_tags, expression.matched_tags)
files = [
'042 - The Title',
'042 - The Title.mp3',
'/foo/042 - The Title'
'/foo/042 - The Title.mp3'
'/042 - The Title'
'/042 - The Title.mp3'
'C:\\foo\\042 - The Title.mp3'
]
for filename in files:
matches = expression.match_file(filename)
self.assertEqual(['42'], matches['tracknumber'])
self.assertEqual(['The Title'], matches['title'])
def test_parse_tags_with_path(self):
expression = TagMatchExpression(r'%artist%/%album%/%tracknumber% - %title%')
expected_tags = ['artist', 'album', 'tracknumber', 'title']
self.assertEqual(expected_tags, expression.matched_tags)
files = [
'The Artist/The Album/01 - The Title',
'The Artist/The Album/01 - The Title.wv',
'C:\\foo\\The Artist\\The Album\\01 - The Title.wv',
]
for filename in files:
matches = expression.match_file(filename)
self.assertEqual(['The Artist'], matches['artist'])
self.assertEqual(['The Album'], matches['album'])
self.assertEqual(['1'], matches['tracknumber'])
self.assertEqual(['The Title'], matches['title'])
def test_parse_replace_underscores(self):
expression = TagMatchExpression(r'%artist%-%title%', replace_underscores=True)
matches = expression.match_file('Some_Artist-Some_Title.ogg')
self.assertEqual(['Some Artist'], matches['artist'])
self.assertEqual(['Some Title'], matches['title'])
def test_parse_tags_duplicates(self):
expression = TagMatchExpression(r'%dummy% %title% %dummy%')
expected_tags = ['dummy', 'title']
self.assertEqual(expected_tags, expression.matched_tags)
matches = expression.match_file('foo title bar')
self.assertEqual(['title'], matches['title'])
self.assertEqual(['foo', 'bar'], matches['dummy'])
def test_parse_tags_hidden(self):
expression = TagMatchExpression(r'%_dummy% %title% %_dummy%')
expected_tags = ['~dummy', 'title']
self.assertEqual(expected_tags, expression.matched_tags)
matches = expression.match_file('foo title bar')
self.assertEqual(['title'], matches['title'])
self.assertEqual(['foo', 'bar'], matches['~dummy'])
def test_parse_empty(self):
expression = TagMatchExpression(r'')
expected_tags = []
self.assertEqual(expected_tags, expression.matched_tags)
| 3,739
|
Python
|
.py
| 77
| 41.077922
| 86
| 0.656532
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,837
|
test_audit.py
|
metabrainz_picard/test/test_audit.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2023 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
import sys
import unittest
from unittest.mock import patch
from test.picardtestcase import PicardTestCase
from picard.audit import (
is_matching_a_prefix,
list_from_prefixes_string,
make_prefixes_dict,
prefixes_candidates_for_length,
setup_audit,
)
class AuditTest(PicardTestCase):
def test_list_from_prefixes_string(self):
def f(s):
return list(list_from_prefixes_string(s))
self.assertEqual(f(''), [])
self.assertEqual(f('a'), [('a',)])
self.assertEqual(f('a,b'), [('a',), ('b',)])
self.assertEqual(f('a,,b'), [('a',), ('b',)])
self.assertEqual(f('a.c,,b.d.f'), [('a', 'c'), ('b', 'd', 'f')])
self.assertEqual(f('b.d.f,a.c,'), [('a', 'c'), ('b', 'd', 'f')])
def test_make_prefixes_dict(self):
d = dict(make_prefixes_dict(''))
self.assertEqual(d, {})
d = dict(make_prefixes_dict('a'))
self.assertEqual(d, {1: [('a',)]})
d = dict(make_prefixes_dict('a.b'))
self.assertEqual(d, {2: [('a', 'b')]})
d = dict(make_prefixes_dict('a.b,c.d,a.b'))
self.assertEqual(d, {2: [('a', 'b'), ('c', 'd')]})
d = dict(make_prefixes_dict('a,a.b,,a.b.c'))
self.assertEqual(d, {1: [('a',)], 2: [('a', 'b')], 3: [('a', 'b', 'c')]})
def test_prefixes_candidates_for_length(self):
d = make_prefixes_dict('a,a.b,c.d,a.b.c,d.e.f,g.h.i')
self.assertEqual(list(prefixes_candidates_for_length(0, d)), [])
self.assertEqual(list(prefixes_candidates_for_length(1, d)), [('a',)])
self.assertEqual(list(prefixes_candidates_for_length(2, d)), [('a',), ('a', 'b'), ('c', 'd')])
expected = [('a',), ('a', 'b'), ('c', 'd'), ('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
self.assertEqual(list(prefixes_candidates_for_length(3, d)), expected)
self.assertEqual(list(prefixes_candidates_for_length(4, d)), expected)
def test_is_matching_a_prefix(self):
d = make_prefixes_dict('a.b')
self.assertEqual(is_matching_a_prefix('a', d), False)
self.assertEqual(is_matching_a_prefix('a.b', d), ('a', 'b'))
self.assertEqual(is_matching_a_prefix('a.b.c', d), ('a', 'b'))
self.assertEqual(is_matching_a_prefix('b.c', d), False)
@unittest.skipUnless(sys.version_info[:3] > (3, 8), "sys.addaudithook() available since Python 3.8")
class AuditHookTest(PicardTestCase):
def test_setup_audit_1(self):
with patch('sys.addaudithook') as mock:
setup_audit('a,b.c')
self.assertTrue(mock.called)
def test_setup_audit_2(self):
with patch('sys.addaudithook') as mock:
setup_audit('')
self.assertFalse(mock.called)
| 3,537
|
Python
|
.py
| 75
| 41.306667
| 102
| 0.617101
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,838
|
test_util_time.py
|
metabrainz_picard/test/test_util_time.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util.time import (
get_timestamp,
seconds_to_dhms,
)
class UtilTimeTest(PicardTestCase):
def test_seconds_to_dhms(self):
self.assertTupleEqual(seconds_to_dhms(0), (0, 0, 0, 0))
self.assertTupleEqual(seconds_to_dhms(1), (0, 0, 0, 1))
self.assertTupleEqual(seconds_to_dhms(60), (0, 0, 1, 0))
self.assertTupleEqual(seconds_to_dhms(61), (0, 0, 1, 1))
self.assertTupleEqual(seconds_to_dhms(120), (0, 0, 2, 0))
self.assertTupleEqual(seconds_to_dhms(3599), (0, 0, 59, 59))
self.assertTupleEqual(seconds_to_dhms(3600), (0, 1, 0, 0))
self.assertTupleEqual(seconds_to_dhms(3601), (0, 1, 0, 1))
self.assertTupleEqual(seconds_to_dhms(3660), (0, 1, 1, 0))
self.assertTupleEqual(seconds_to_dhms(3661), (0, 1, 1, 1))
self.assertTupleEqual(seconds_to_dhms(86399), (0, 23, 59, 59))
self.assertTupleEqual(seconds_to_dhms(86400), (1, 0, 0, 0))
def test_get_timestamp(self):
self.assertEqual(get_timestamp(0), "")
self.assertEqual(get_timestamp(1), "01s")
self.assertEqual(get_timestamp(60), "01m 00s")
self.assertEqual(get_timestamp(61), "01m 01s")
self.assertEqual(get_timestamp(120), "02m 00s")
self.assertEqual(get_timestamp(3599), "59m 59s")
self.assertEqual(get_timestamp(3600), "01h 00m")
self.assertEqual(get_timestamp(3601), "01h 00m")
self.assertEqual(get_timestamp(3660), "01h 01m")
self.assertEqual(get_timestamp(3661), "01h 01m")
self.assertEqual(get_timestamp(86399), "23h 59m")
self.assertEqual(get_timestamp(86400), "01d 00h")
| 2,590
|
Python
|
.py
| 53
| 43.811321
| 80
| 0.694862
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,839
|
test_util_thread.py
|
metabrainz_picard/test/test_util_thread.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Giorgio Fontanive
#
# This program is free software; you can redistribute it and/or
# modify 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.
from functools import partial
from queue import (
Empty,
Queue,
)
from PyQt6.QtCore import (
QCoreApplication,
QObject,
QThreadPool,
)
from PyQt6.QtTest import QTest
from test.picardtestcase import PicardTestCase
from picard.util import thread
def mock_function():
return 1
def mock_exception():
raise Exception
class MainEventInterceptor(QObject):
def eventFilter(self, obj, event):
if isinstance(event, thread.ProxyToMainEvent):
event.run()
event.accept()
return True
return super().eventFilter(obj, event)
class ThreadTest(PicardTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.app = QCoreApplication([])
cls.threadpool = QThreadPool()
cls.event_interceptor = MainEventInterceptor()
def setUp(self):
super().setUp()
self.tagger.installEventFilter(self.event_interceptor)
self.result_queue = Queue()
def tearDown(self):
super().tearDown()
self.tagger.removeEventFilter(self.event_interceptor)
def _send_task_result(self, result=None, error=None):
if not result and not error:
return
self.result_queue.put((result, error))
def _get_task_result(self):
while True:
try:
return self.result_queue.get_nowait()
except Empty:
# necessary to process Qt events sent by other threads
QTest.qWait(100)
def test_run_task(self):
thread.run_task(mock_function, self._send_task_result, thread_pool=self.threadpool)
result, error = self._get_task_result()
self.assertEqual(result, 1)
self.assertIsNone(error)
thread.run_task(mock_exception, self._send_task_result, thread_pool=self.threadpool)
result, error = self._get_task_result()
self.assertIsNone(result)
self.assertIsInstance(error, Exception)
def test_to_main(self):
thread.to_main(self._send_task_result, result="test", error=None)
result, error = self._get_task_result()
self.assertEqual(result, "test")
self.assertIsNone(error)
thread.to_main(self._send_task_result, result=None, error=Exception())
result, error = self._get_task_result()
self.assertIsNone(result)
self.assertIsInstance(error, Exception)
def test_to_main_with_blocking(self):
func = partial(thread.to_main_with_blocking, self._send_task_result, result="test", error=None)
thread.run_task(func, thread_pool=self.threadpool)
result, error = self._get_task_result()
self.assertEqual(result, "test")
self.assertIsNone(error)
func = partial(thread.to_main_with_blocking, self._send_task_result, result=None, error=Exception())
thread.run_task(func, thread_pool=self.threadpool)
result, error = self._get_task_result()
self.assertIsNone(result)
self.assertIsInstance(error, Exception)
def test_task_counter(self):
task_counter = thread.TaskCounter()
self.assertEqual(task_counter.count, 0)
for i in range(3):
thread.run_task(self._get_task_result, thread_pool=self.threadpool, task_counter=task_counter)
self.assertEqual(task_counter.count, i + 1)
for i in range(3):
self.result_queue.put(i)
task_counter.wait_for_tasks()
self.assertEqual(task_counter.count, 0)
| 4,330
|
Python
|
.py
| 107
| 33.700935
| 108
| 0.683484
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,840
|
test_util_cdrom.py
|
metabrainz_picard/test/test_util_cdrom.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import io
from typing import Iterable
import unittest
from test.picardtestcase import PicardTestCase
from picard.const.defaults import DEFAULT_DRIVES
from picard.const.sys import IS_WIN
from picard.util import cdrom
MOCK_CDROM_INFO = """CD-ROM information, Id: cdrom.c 3.20 2003/12/17
drive name: sr1 sr0
drive speed: 24 24
drive # of slots: 1 1
Can close tray: 0 1
Can open tray: 1 1
Can lock tray: 1 1
Can change speed: 1 1
Can select disk: 0 0
Can read multisession: 1 1
Can read MCN: 1 1
Reports media changed: 1 1
Can play audio: 1 0
Can write CD-R: 1 1
Can write CD-RW: 1 1
Can read DVD: 1 1
Can write DVD-R: 1 1
Can write DVD-RAM: 1 1
Can read MRW: 1 1
Can write MRW: 1 1
Can write RAM: 1 1
"""
MOCK_CDROM_INFO_EMPTY = """CD-ROM information, Id: cdrom.c 3.20 2003/12/17
drive name:
drive speed:
drive # of slots:
Can close tray:
Can open tray:
Can lock tray:
Can change speed:
Can select disk:
Can read multisession:
Can read MCN:
Reports media changed:
Can play audio:
Can write CD-R:
Can write CD-RW:
Can read DVD:
Can write DVD-R:
Can write DVD-RAM:
Can read MRW:
Can write MRW:
Can write RAM:
"""
class LinuxParseCdromInfoTest(PicardTestCase):
def test_drives(self):
with io.StringIO(MOCK_CDROM_INFO) as f:
drives = list(cdrom._parse_linux_cdrom_info(f))
self.assertEqual([('sr1', True), ('sr0', False)], drives)
def test_empty(self):
with io.StringIO(MOCK_CDROM_INFO_EMPTY) as f:
drives = list(cdrom._parse_linux_cdrom_info(f))
self.assertEqual([], drives)
def test_empty_string(self):
with io.StringIO("") as f:
drives = list(cdrom._parse_linux_cdrom_info(f))
self.assertEqual([], drives)
class GetCdromDrivesTest(PicardTestCase):
def test_get_cdrom_drives(self):
self.set_config_values({"cd_lookup_device": "/dev/cdrom"})
# Independent of the implementation get_cdrom_drives must not rais
# and return an Iterable.
drives = cdrom.get_cdrom_drives()
self.assertIsInstance(drives, Iterable)
self.assertTrue(set(DEFAULT_DRIVES).issubset(drives))
def test_generic_iter_drives(self):
self.set_config_values({"cd_lookup_device": "/dev/cdrom"})
self.assertEqual(["/dev/cdrom"], list(cdrom._generic_iter_drives()))
self.set_config_values({"cd_lookup_device": "/dev/cdrom, /dev/sr0"})
self.assertEqual(["/dev/cdrom", "/dev/sr0"], list(cdrom._generic_iter_drives()))
self.set_config_values({"cd_lookup_device": ""})
self.assertEqual([], list(cdrom._generic_iter_drives()))
self.set_config_values({"cd_lookup_device": " ,, ,\t, "})
self.assertEqual([], list(cdrom._generic_iter_drives()))
@unittest.skipUnless(IS_WIN, "windows test")
class WindowsGetCdromDrivesTest(PicardTestCase):
def test_autodetect(self):
self.assertTrue(cdrom.AUTO_DETECT_DRIVES)
def test_iter_drives(self):
drives = cdrom._iter_drives()
self.assertIsInstance(drives, Iterable)
# This should not raise
list(drives)
| 3,920
|
Python
|
.py
| 109
| 32.229358
| 88
| 0.708894
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,841
|
test_ui_options_plugins.py
|
metabrainz_picard/test/test_ui_options_plugins.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.ui.options.plugins import PluginsOptionsPage
class PluginsOptionsPageTest(PicardTestCase):
def test_link_authors(self):
self.assertEqual(
'<a href="mailto:coyote@acme.com">Wile E. Coyote</a>, Road <Runner>',
PluginsOptionsPage.link_authors('Wile E. Coyote <coyote@acme.com>, Road <Runner>'),
)
| 1,228
|
Python
|
.py
| 27
| 42.666667
| 95
| 0.755017
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,842
|
test_ratecontrol.py
|
metabrainz_picard/test/test_ratecontrol.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from collections import defaultdict
from test.picardtestcase import PicardTestCase
from picard.webservice import ratecontrol
class RateControlTest(PicardTestCase):
def setUp(self):
super().setUp()
ratecontrol.REQUEST_DELAY_MINIMUM = defaultdict(lambda: 1000)
def test_set_minimum_delay(self):
hostkey = ('example.com', 80)
ratecontrol.set_minimum_delay(hostkey, 200)
self.assertEqual(200, ratecontrol.REQUEST_DELAY_MINIMUM[hostkey])
def test_set_minimum_delay_with_float(self):
hostkey = ('example.com', 80)
ratecontrol.set_minimum_delay(hostkey, 33.8)
self.assertEqual(33, ratecontrol.REQUEST_DELAY_MINIMUM[hostkey])
def test_set_minimum_delay_for_url(self):
hostkey = ('example.com', 443)
ratecontrol.set_minimum_delay_for_url('https://example.com', 300)
self.assertEqual(300, ratecontrol.REQUEST_DELAY_MINIMUM[hostkey])
| 1,756
|
Python
|
.py
| 38
| 42.236842
| 80
| 0.74605
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,843
|
test_similarity.py
|
metabrainz_picard/test/test_similarity.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006 Lukáš Lalinský
# Copyright (C) 2013, 2018-2021 Laurent Monin
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.similarity import (
similarity,
similarity2,
)
class SimilarityTest(PicardTestCase):
def test_correct(self):
self.assertEqual(similarity("K!", "K!"), 1.0)
self.assertEqual(similarity("BBB", "AAA"), 0.0)
self.assertAlmostEqual(similarity("ABC", "ABB"), 0.7, 1)
class Similarity2Test(PicardTestCase):
def test_full_match(self):
a = b = "a b c"
self.assertEqual(similarity2(a, b), 1.0)
def test_match_various_separators_1(self):
a = "a b c"
b = "A,B•C"
self.assertEqual(similarity2(a, b), 1.0)
def test_match_various_separators_2(self):
a = "a b c"
b = ",A, B •C•"
self.assertEqual(similarity2(a, b), 1.0)
def test_a_b_order(self):
a = "a b c"
b = "c a b"
self.assertEqual(similarity2(a, b), 1.0)
def test_a_similar_b_1(self):
a = "a b c"
b = "a b d"
self.assertAlmostEqual(similarity2(a, b), 0.6, 1)
def test_a_similar_b_2(self):
a = "a b c"
b = "a f d"
self.assertAlmostEqual(similarity2(a, b), 0.3, 1)
def test_a_b_totally_different(self):
a = "abc"
b = "def"
self.assertEqual(similarity2(a, b), 0.0)
def test_not_a(self):
a = ""
b = "def"
self.assertEqual(similarity2(a, b), 0.0)
def test_not_b(self):
a = "abc"
b = ""
self.assertEqual(similarity2(a, b), 0.0)
def test_not_a_and_not_b(self):
a = ""
b = ""
self.assertEqual(similarity2(a, b), 0.0)
def test_empty_lists(self):
a = " "
b = " "
self.assertEqual(similarity2(a, b), 0.0)
def test_a_longer_than_b(self):
a = "a b c d"
b = "a d c"
self.assertAlmostEqual(similarity2(a, b), 0.88, 1)
| 2,834
|
Python
|
.py
| 80
| 29.525
| 80
| 0.629861
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,844
|
test_debug_opt.py
|
metabrainz_picard/test/test_debug_opt.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.debug_opts import DebugOptEnum
class DebugOptTestCase(DebugOptEnum):
A = 1, 'titleA', 'descriptionA'
B = 2, 'titleB', 'descriptionB'
class TestDebugOpt(PicardTestCase):
def setUp(self):
DebugOptTestCase.set_registry(set())
def test_enabled(self):
self.assertFalse(DebugOptTestCase.A.enabled)
self.assertFalse(DebugOptTestCase.B.enabled)
DebugOptTestCase.A.enabled = True
self.assertTrue(DebugOptTestCase.A.enabled)
def test_optname(self):
self.assertEqual(DebugOptTestCase.A.optname, 'a')
self.assertEqual(DebugOptTestCase.B.optname, 'b')
def test_title(self):
self.assertEqual(DebugOptTestCase.A.title, 'titleA')
self.assertEqual(DebugOptTestCase.B.title, 'titleB')
def test_description(self):
self.assertEqual(DebugOptTestCase.A.description, 'descriptionA')
self.assertEqual(DebugOptTestCase.B.description, 'descriptionB')
def test_opt_names(self):
self.assertEqual(DebugOptTestCase.opt_names(), 'a,b')
def test_from_string_simple(self):
DebugOptTestCase.from_string('a')
self.assertTrue(DebugOptTestCase.A.enabled)
self.assertFalse(DebugOptTestCase.B.enabled)
DebugOptTestCase.from_string('a,b')
self.assertTrue(DebugOptTestCase.A.enabled)
self.assertTrue(DebugOptTestCase.B.enabled)
def test_from_string_complex(self):
DebugOptTestCase.from_string('something, A,x,b')
self.assertTrue(DebugOptTestCase.A.enabled)
self.assertTrue(DebugOptTestCase.B.enabled)
def test_from_string_remove(self):
DebugOptTestCase.set_registry({DebugOptTestCase.B})
self.assertTrue(DebugOptTestCase.B.enabled)
DebugOptTestCase.from_string('A')
self.assertTrue(DebugOptTestCase.A.enabled)
self.assertFalse(DebugOptTestCase.B.enabled)
def test_to_string(self):
self.assertEqual('', DebugOptTestCase.to_string())
DebugOptTestCase.A.enabled = True
self.assertEqual('a', DebugOptTestCase.to_string())
DebugOptTestCase.B.enabled = True
self.assertEqual('a,b', DebugOptTestCase.to_string())
def test_set_get_registry(self):
old_set = DebugOptTestCase.get_registry()
DebugOptTestCase.A.enabled = True
self.assertTrue(DebugOptTestCase.A.enabled)
new_set = set()
DebugOptTestCase.set_registry(new_set)
self.assertFalse(DebugOptTestCase.A.enabled)
DebugOptTestCase.B.enabled = True
self.assertFalse(DebugOptTestCase.A.enabled)
self.assertTrue(DebugOptTestCase.B.enabled)
DebugOptTestCase.set_registry(old_set)
self.assertTrue(DebugOptTestCase.A.enabled)
self.assertFalse(DebugOptTestCase.B.enabled)
def test_invalid(self):
with self.assertRaises(ValueError):
class BuggyOpt(DebugOptEnum):
C = "x", "x", "x"
def test_invalid2(self):
with self.assertRaises(TypeError):
class BuggyOpt(DebugOptEnum):
C = 1, "x"
| 3,950
|
Python
|
.py
| 87
| 38.724138
| 80
| 0.716775
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,845
|
test_log.py
|
metabrainz_picard/test/test_log.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2021, 2024 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
# Copyright (C) 2024 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify 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.
from collections import deque
from dataclasses import dataclass
from pathlib import (
PurePosixPath,
PureWindowsPath,
)
import unittest
from unittest.mock import patch
from test.picardtestcase import PicardTestCase
from picard.const.sys import IS_WIN
from picard.debug_opts import DebugOpt
from picard.log import (
_calculate_bounds,
name_filter,
)
class MockLogItem:
def __init__(self, pos=0):
self.pos = pos
class MockLogItemQueue:
def __init__(self):
self._log_queue = deque(maxlen=10)
def contents(self, prev=-1):
if not self._log_queue:
return []
offset, length = _calculate_bounds(prev, self._log_queue[0].pos, self._log_queue[-1].pos, len(self._log_queue))
if offset >= 0:
return (self._log_queue[i] for i in range(offset, length))
# If offset < 0, there is a discontinuity in the queue positions
# Use a slower approach to get the new content.
else:
return (x for x in self._log_queue if x.pos > prev)
def push(self, item):
self._log_queue.append(item)
class LogQueueCommonTest(PicardTestCase):
def setUp(self):
super().setUp()
self.item_queue = MockLogItemQueue()
class LogQueueBoundsTestCase(LogQueueCommonTest):
def test_1(self):
# Common case where the item positions are within the max size of the queue
# [0,1,2,3,4,5,6,7], len = 8, maxlen = 10, offset = 0
for i in range(8):
self.item_queue.push(MockLogItem(i))
content_list = self.item_queue.contents()
self.assertListEqual([x.pos for x in content_list], list(range(0, 8)))
def test_2(self):
# Common case where the item positions are outside the max size of the queue
# Which means the positions do not match the index of items in the queue
# [5,6,7,8,9,10,11,12,13,14], len = 10, offset = len - (last - prev) = 10 - (14-7) = 3
for i in range(15):
self.item_queue.push(MockLogItem(i))
content_list = self.item_queue.contents(7) # prev value
self.assertListEqual([x.pos for x in content_list], list(range(8, 15)))
def test_3(self):
# Previous case but the previous item (2) was already removed from the queue
# So we pick the first item in the queue in its place
# [5,6,7,8,9,10,11,12,13,14], len = 10, maxlen = 10, prev = 5-1 = 4, offset = 0
for i in range(15):
self.item_queue.push(MockLogItem(i))
content_list = self.item_queue.contents(2)
self.assertListEqual([x.pos for x in content_list], list(range(5, 15)))
def test_4(self):
# In case we have only one element but use different prev values
self.item_queue.push(MockLogItem(10))
content_list = self.item_queue.contents() # prev = -1 is smaller than 10, so we update prev from -1 to 10-1 = 9
self.assertListEqual([x.pos for x in content_list], [10])
content_list = self.item_queue.contents(2) # prev = 2 is smaller than 10, so we update prev from 2 to 10-1 = 9
self.assertListEqual([x.pos for x in content_list], [10])
content_list = self.item_queue.contents(9) # prev = 9 is smaller than 10, so we update prev from 9 to 10-1 = 9
self.assertListEqual([x.pos for x in content_list], [10])
content_list = self.item_queue.contents(10) # prev = 10 is equal to 10, so we use it as is
self.assertListEqual([x.pos for x in content_list], [])
content_list = self.item_queue.contents(20) # prev = 20 is bigger than 10, so we use it as is
self.assertListEqual([x.pos for x in content_list], [])
def test_5(self):
# This shouldn't really happen, but here is a test for it
# In case of a discontinuity e.g. [4,5,11], we have len = 3, prev = 3, last_pos=11,
# which results in offset = 3 - (11-4) = -4, which is completely absurd offset, when the correct would be 0
self.item_queue.push(MockLogItem(4))
self.item_queue.push(MockLogItem(5))
self.item_queue.push(MockLogItem(11))
content_list = self.item_queue.contents(3)
self.assertListEqual([x.pos for x in content_list], [4, 5, 11])
@dataclass
class FakeRecord:
pathname: str
name: str
@unittest.skipIf(IS_WIN, "Posix test")
@patch('picard.log.picard_module_path', PurePosixPath('/path1/path2'))
@patch('picard.log.USER_PLUGIN_DIR', PurePosixPath('/user/picard/plugins'))
class NameFilterTestRel(PicardTestCase):
def test_1(self):
record = FakeRecord(name=None, pathname='/path1/path2/module/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'module/file')
def test_2(self):
record = FakeRecord(name=None, pathname='/path1/path2/module/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'module')
def test_3(self):
record = FakeRecord(name=None, pathname='/path1/path2/module/subpath/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'module/subpath/file')
def test_4(self):
record = FakeRecord(name=None, pathname='')
with self.assertRaises(ValueError):
name_filter(record)
def test_5(self):
record = FakeRecord(name=None, pathname='/path1/path2/__init__/module/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '__init__/module')
def test_plugin_path_long_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='/user/picard/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/user/picard/plugins/plugin')
def test_plugin_path_long_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='/user/picard/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/user/picard/plugins/plugin.zip/xxx')
def test_plugin_path_short_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/user/picard/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/plugin')
def test_plugin_path_short_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/user/picard/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/plugin.zip/xxx')
def test_plugin_path_short_3(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/user/picard/plugins/myplugin.zip/myplugin.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/myplugin.zip')
def test_plugin_path_short_4(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/user/picard/plugins/myplugin.zip/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/myplugin.zip')
@unittest.skipIf(IS_WIN, "Posix test")
@patch('picard.log.picard_module_path', PurePosixPath('/picard'))
@patch('picard.log.USER_PLUGIN_DIR', PurePosixPath('/user/picard/plugins/'))
class NameFilterTestAbs(PicardTestCase):
def test_1(self):
record = FakeRecord(name=None, pathname='/path/module/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path/module/file')
def test_2(self):
record = FakeRecord(name=None, pathname='/path/module/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path/module')
def test_3(self):
record = FakeRecord(name=None, pathname='/path/module/subpath/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path/module/subpath/file')
def test_4(self):
record = FakeRecord(name=None, pathname='')
with self.assertRaises(ValueError):
name_filter(record)
def test_plugin_path_long_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='/path1/path2/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin')
def test_plugin_path_long_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='/path1/path2/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin.zip/xxx')
def test_plugin_path_long_3(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='/path1/path2/plugins/plugin.zip/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin.zip')
def test_plugin_path_short_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/path1/path2/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin')
def test_plugin_path_short_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/path1/path2/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin.zip/xxx')
def test_plugin_path_short_3(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/path1/path2/plugins/myplugin.zip/myplugin.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/myplugin.zip')
def test_plugin_path_short_4(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='/path1/path2/plugins/myplugin.zip/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/myplugin.zip')
@unittest.skipIf(IS_WIN, "Posix test")
@patch('picard.log.picard_module_path', PurePosixPath('/path1/path2/')) # incorrect, but testing anyway
@patch('picard.log.USER_PLUGIN_DIR', PurePosixPath('/user/picard/plugins'))
class NameFilterTestEndingSlash(PicardTestCase):
def test_1(self):
record = FakeRecord(name=None, pathname='/path3/module/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path3/module/file')
@unittest.skipUnless(IS_WIN, "Windows test")
@patch('picard.log.picard_module_path', PureWindowsPath('C:\\path1\\path2'))
@patch('picard.log.USER_PLUGIN_DIR', PurePosixPath('C:\\user\\picard\\plugins'))
class NameFilterTestRelWin(PicardTestCase):
def test_1(self):
record = FakeRecord(name=None, pathname='C:/path1/path2/module/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'module/file')
def test_2(self):
record = FakeRecord(name=None, pathname='C:/path1/path2/module/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'module')
def test_3(self):
record = FakeRecord(name=None, pathname='C:/path1/path2/module/subpath/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'module/subpath/file')
def test_4(self):
record = FakeRecord(name=None, pathname='')
with self.assertRaises(ValueError):
name_filter(record)
def test_5(self):
record = FakeRecord(name=None, pathname='C:/path1/path2/__init__/module/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '__init__/module')
def test_plugin_path_long_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='C:/user/picard/plugins/path3/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/user/picard/plugins/path3/plugins/plugin')
def test_plugin_path_long_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='C:/user/picard/plugins/path3/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/user/picard/plugins/path3/plugins/plugin.zip/xxx')
def test_plugin_path_short_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/user/picard/plugins/path3/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/path3/plugins/plugin')
def test_plugin_path_short_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/user/picard/plugins/path3/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/path3/plugins/plugin.zip/xxx')
def test_plugin_path_short_3(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/user/picard/plugins/path3/plugins/myplugin.zip/myplugin.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/path3/plugins/myplugin.zip')
def test_plugin_path_short_4(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/user/picard/plugins/path3/plugins/myplugin.zip/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, 'plugins/path3/plugins/myplugin.zip')
@unittest.skipUnless(IS_WIN, "Windows test")
@patch('picard.log.picard_module_path', PureWindowsPath('C:\\picard'))
@patch('picard.log.USER_PLUGIN_DIR', PurePosixPath('C:\\user\\picard/plugins'))
class NameFilterTestAbsWin(PicardTestCase):
def test_1(self):
record = FakeRecord(name=None, pathname='C:/path/module/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path/module/file')
def test_2(self):
record = FakeRecord(name=None, pathname='C:/path/module/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path/module')
def test_3(self):
record = FakeRecord(name=None, pathname='C:/path/module/subpath/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path/module/subpath/file')
def test_4(self):
record = FakeRecord(name=None, pathname='')
with self.assertRaises(ValueError):
name_filter(record)
def test_plugin_path_long_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='C:/path1/path2/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin')
def test_plugin_path_long_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = True
record = FakeRecord(name=None, pathname='C:/path1/path2/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin.zip/xxx')
def test_plugin_path_short_1(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/path1/path2/plugins/plugin.zip')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin')
def test_plugin_path_short_2(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/path1/path2/plugins/plugin.zip/xxx.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/plugin.zip/xxx')
def test_plugin_path_short_3(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/path1/path2/plugins/myplugin.zip/myplugin.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/myplugin.zip')
def test_plugin_path_short_4(self):
DebugOpt.PLUGIN_FULLPATH.enabled = False
record = FakeRecord(name=None, pathname='C:/path1/path2/plugins/myplugin.zip/__init__.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path1/path2/plugins/myplugin.zip')
@unittest.skipUnless(IS_WIN, "Windows test")
@patch('picard.log.picard_module_path', PureWindowsPath('C:\\path1\\path2\\')) # incorrect, but testing anyway
@patch('picard.log.USER_PLUGIN_DIR', PurePosixPath('C:\\user\\picard\\plugins'))
class NameFilterTestEndingSlashWin(PicardTestCase):
def test_1(self):
record = FakeRecord(name=None, pathname='C:/path3/module/file.py')
self.assertTrue(name_filter(record))
self.assertEqual(record.name, '/path3/module/file')
| 18,197
|
Python
|
.py
| 338
| 46.66568
| 120
| 0.689768
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,846
|
test_collection.py
|
metabrainz_picard/test/test_collection.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from unittest.mock import (
ANY,
MagicMock,
)
from test.picardtestcase import (
PicardTestCase,
load_test_json,
)
import picard.collection
from picard.collection import (
Collection,
add_release_to_user_collections,
get_user_collection,
load_user_collections,
)
from picard.webservice.api_helpers import MBAPIHelper
def fake_request_handler(collection_id, releases, handler):
handler(None, None, None)
def fake_get_collection_list(handler):
document = load_test_json('collection_list.json')
handler(document, None, None)
mb_api = MagicMock(auto_spec=MBAPIHelper)
mb_api.put_to_collection.side_effect = fake_request_handler
mb_api.delete_from_collection.side_effect = fake_request_handler
mb_api.get_collection_list.side_effect = fake_get_collection_list
class CollectionTest(PicardTestCase):
def setUp(self):
super().setUp()
self.tagger.mb_api = mb_api
picard.collection.user_collections = {}
def test_collection_init(self):
collection = Collection('foo', mb_api)
self.assertEqual('foo', collection.id)
self.assertEqual('', collection.name)
self.assertEqual(0, collection.size)
self.assertEqual(set(), collection.pending_releases)
self.assertEqual(set(), collection.releases)
self.assertEqual(mb_api, collection._mb_api)
def test_collection_size(self):
collection = Collection('foo', mb_api)
self.assertEqual(0, collection.size)
collection.size = 2
self.assertEqual(2, collection.size)
collection.size = '10'
self.assertEqual(10, collection.size)
def test_collection_add_releases(self):
releases = {
'963a7d48-5995-4751-aef8-6727cb879b9c',
'54292079-790c-4e99-bf8d-12efa29fa3e9',
}
collection = Collection('foo', mb_api)
callback = MagicMock()
collection.add_releases(releases, callback)
mb_api.put_to_collection.assert_called_once_with(
'foo', list(releases), ANY)
self.assertEqual(2, collection.size)
self.assertEqual(releases, collection.releases)
collection.tagger.window.set_statusbar_message.assert_called_once()
def test_collection_remove_releases(self):
releases = [
'963a7d48-5995-4751-aef8-6727cb879b9c',
'54292079-790c-4e99-bf8d-12efa29fa3e9',
'd0e5212c-d463-4810-ab0b-a33431b38008',
]
releases_to_remove = set(releases[:2])
collection = Collection('foo', mb_api)
collection.releases = set(releases)
collection.size = len(releases)
callback = MagicMock()
collection.remove_releases(releases_to_remove, callback)
mb_api.delete_from_collection.assert_called_once_with(
'foo', list(releases_to_remove), ANY)
self.assertEqual(1, collection.size)
self.assertEqual({releases[2]}, collection.releases)
collection.tagger.window.set_statusbar_message.assert_called_once()
def test_get_user_collection(self):
self.assertEqual({}, picard.collection.user_collections)
collection1 = get_user_collection('foo')
self.assertIsInstance(collection1, Collection)
self.assertEqual('foo', collection1.id)
self.assertEqual(collection1, get_user_collection('foo'))
collection2 = get_user_collection('bar')
self.assertNotEqual(collection1, collection2)
self.assertEqual(
{'foo': collection1, 'bar': collection2},
picard.collection.user_collections,
)
def test_add_release_to_user_collections(self):
self.set_config_values(persist={'oauth_username': 'theuser'})
release_node = {
'id': '54292079-790c-4e99-bf8d-12efa29fa3e9',
'collections': [{
'id': '00000000-0000-0000-0000-000000000001',
'name': 'collection1',
'editor': 'theuser',
'release-count': 42
}, {
'id': '00000000-0000-0000-0000-000000000002',
'name': 'collection2',
'editor': 'otheruser',
'release-count': 12
}, {
'id': '00000000-0000-0000-0000-000000000003',
'name': 'collection3',
'editor': 'theuser',
'release-count': 0
}]
}
add_release_to_user_collections(release_node)
self.assertEqual(2, len(picard.collection.user_collections))
collection1 = picard.collection.user_collections['00000000-0000-0000-0000-000000000001']
collection3 = picard.collection.user_collections['00000000-0000-0000-0000-000000000003']
self.assertEqual('collection1', collection1.name)
self.assertIn(release_node['id'], collection1.releases)
self.assertEqual(42, collection1.size)
self.assertEqual('collection3', collection3.name)
self.assertIn(release_node['id'], collection3.releases)
self.assertEqual(0, collection3.size)
def test_load_user_collections(self):
self.tagger.webservice.oauth_manager.is_authorized.return_value = True
picard.collection.user_collections['old-collection'] = Collection('old-collection', mb_api)
callback = MagicMock()
load_user_collections(callback)
callback.assert_called_once_with()
self.assertEqual(3, len(picard.collection.user_collections))
self.assertNotIn('old-collection', picard.collection.user_collections)
collection1 = picard.collection.user_collections['40734348-a970-491a-a160-722246cfadf4']
self.assertEqual(collection1.name, 'My Collection')
self.assertEqual(collection1.size, 402)
def test_load_user_collections_not_authorized(self):
self.tagger.webservice.oauth_manager.is_authorized.return_value = False
picard.collection.user_collections['old-collection'] = Collection('old-collection', mb_api)
callback = MagicMock()
load_user_collections(callback)
callback.assert_not_called()
self.assertEqual(0, len(picard.collection.user_collections))
| 6,995
|
Python
|
.py
| 155
| 37.290323
| 99
| 0.679472
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,847
|
test_util_tags.py
|
metabrainz_picard/test/test_util_tags.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2020 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util.tags import (
display_tag_name,
parse_comment_tag,
parse_subtag,
)
class UtilTagsTest(PicardTestCase):
def test_display_tag_name(self):
self.assertEqual('Artist', display_tag_name('artist'))
self.assertEqual('Lyrics', display_tag_name('lyrics:'))
self.assertEqual('Comment [Foo]', display_tag_name('comment:Foo'))
def test_parse_comment_tag(self):
self.assertEqual(('XXX', 'foo'), parse_comment_tag('comment:XXX:foo'))
self.assertEqual(('eng', 'foo'), parse_comment_tag('comment:foo'))
self.assertEqual(('XXX', ''), parse_comment_tag('comment:XXX'))
self.assertEqual(('eng', ''), parse_comment_tag('comment'))
def test_parse_lyrics_tag(self):
self.assertEqual(('eng', ''), parse_subtag('lyrics'))
self.assertEqual(('XXX', 'foo'), parse_subtag('lyrics:XXX:foo'))
self.assertEqual(('XXX', ''), parse_subtag('lyrics:XXX'))
self.assertEqual(('eng', 'foo'), parse_subtag('lyrics::foo'))
| 1,930
|
Python
|
.py
| 41
| 43.170732
| 80
| 0.70882
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,848
|
test_coverart_image.py
|
metabrainz_picard/test/test_coverart_image.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019, 2021-2024 Philipp Wolfer
# Copyright (C) 2019-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from collections import Counter
import os.path
from tempfile import TemporaryDirectory
import unittest
from test.picardtestcase import (
PicardTestCase,
create_fake_png,
)
from picard.const.defaults import DEFAULT_COVER_IMAGE_FILENAME
from picard.const.sys import IS_WIN
from picard.coverart.image import (
CoverArtImage,
LocalFileCoverArtImage,
TagCoverArtImage,
)
from picard.coverart.utils import (
Id3ImageType,
types_from_id3,
)
from picard.file import File
from picard.metadata import Metadata
from picard.util import encode_filename
from picard.util.filenaming import WinPathTooLong
def create_image(extra_data, types=None, support_types=False,
support_multi_types=False, comment=None, id3_type=None):
return CoverArtImage(
data=create_fake_png(extra_data),
types=types,
comment=comment,
support_types=support_types,
support_multi_types=support_multi_types,
id3_type=id3_type,
)
class TagCoverArtImageTest(PicardTestCase):
def test_repr_str_1(self):
image_type = Id3ImageType.COVER_FRONT
image = TagCoverArtImage(
file='testfilename',
tag='tag',
types=types_from_id3(image_type),
comment='description',
support_types=True,
data=None,
id3_type=image_type,
is_front=True,
)
expected = "TagCoverArtImage('testfilename', tag='tag', types=['front'], support_types=True, support_multi_types=False, is_front=True, comment='description')"
self.assertEqual(expected, repr(image))
expected = "TagCoverArtImage from 'testfilename' of type front and comment 'description'"
self.assertEqual(expected, str(image))
class CoverArtImageTest(PicardTestCase):
def test_repr_str_1(self):
image = CoverArtImage(
url='url', types=["booklet", "front"],
comment='comment', support_types=True,
support_multi_types=True
)
expected = "CoverArtImage(url='url', types=['booklet', 'front'], support_types=True, support_multi_types=True, comment='comment')"
self.assertEqual(expected, repr(image))
expected = "CoverArtImage from url of type booklet,front and comment 'comment'"
self.assertEqual(expected, str(image))
def test_repr_str_2(self):
image = CoverArtImage()
expected = "CoverArtImage(support_types=False, support_multi_types=False)"
self.assertEqual(expected, repr(image))
expected = "CoverArtImage"
self.assertEqual(expected, str(image))
def test_is_front_image_no_types(self):
image = create_image(b'a')
self.assertTrue(image.is_front_image())
self.assertEqual(Id3ImageType.COVER_FRONT, image.id3_type)
image.can_be_saved_to_metadata = False
self.assertFalse(image.is_front_image())
def test_is_front_image_types_supported(self):
image = create_image(b'a', types=["booklet", "front"], support_types=True)
self.assertTrue(image.is_front_image())
image.is_front = False
self.assertFalse(image.is_front_image())
image = create_image(b'a', support_types=True)
self.assertFalse(image.is_front_image())
def test_is_front_image_no_types_supported(self):
image = create_image(b'a', types=["back"], support_types=False)
self.assertTrue(image.is_front_image())
self.assertEqual(Id3ImageType.COVER_FRONT, image.id3_type)
def test_maintype(self):
self.assertEqual("front", create_image(b'a').maintype)
self.assertEqual("front", create_image(b'a', support_types=True).maintype)
self.assertEqual("front", create_image(b'a', types=["back", "front"], support_types=True).maintype)
self.assertEqual("back", create_image(b'a', types=["back", "medium"], support_types=True).maintype)
self.assertEqual("front", create_image(b'a', types=["back", "medium"], support_types=False).maintype)
def test_normalized_types(self):
self.assertEqual(("front",), create_image(b'a').normalized_types())
self.assertEqual(("-",), create_image(b'a', support_types=True).normalized_types())
self.assertEqual(("front",), create_image(b'a', types=["front"], support_types=True).normalized_types())
self.assertEqual(("front", "back",), create_image(b'a', types=["back", "front"], support_types=True).normalized_types())
self.assertEqual(("back", "medium",), create_image(b'a', types=["medium", "back"], support_types=True).normalized_types())
self.assertEqual(("front",), create_image(b'a', types=["back", "medium"], support_types=False).normalized_types())
def test_id3_type_derived(self):
self.assertEqual(Id3ImageType.COVER_FRONT, create_image(b'a').id3_type)
self.assertEqual(Id3ImageType.COVER_FRONT, create_image(b'a', support_types=True).id3_type)
self.assertEqual(Id3ImageType.COVER_FRONT, create_image(b'a', types=["back", "front"], support_types=True).id3_type)
self.assertEqual(Id3ImageType.COVER_BACK, create_image(b'a', types=["back", "medium"], support_types=True).id3_type)
self.assertEqual(Id3ImageType.COVER_FRONT, create_image(b'a', types=["back", "medium"], support_types=False).id3_type)
self.assertEqual(Id3ImageType.MEDIA, create_image(b'a', types=["medium"], support_types=True).id3_type)
self.assertEqual(Id3ImageType.LEAFLET_PAGE, create_image(b'a', types=["booklet"], support_types=True).id3_type)
self.assertEqual(Id3ImageType.OTHER, create_image(b'a', types=["spine"], support_types=True).id3_type)
self.assertEqual(Id3ImageType.OTHER, create_image(b'a', types=["sticker"], support_types=True).id3_type)
def test_id3_type_explicit(self):
image = create_image(b'a', types=["back"], support_types=True)
for id3_type in Id3ImageType:
image.id3_type = id3_type
self.assertEqual(id3_type, image.id3_type)
image.id3_type = None
self.assertEqual(Id3ImageType.COVER_BACK, image.id3_type)
def test_id3_type_value_error(self):
image = create_image(b'a')
for invalid_value in ('foo', 200, -1):
with self.assertRaises(ValueError):
image.id3_type = invalid_value
def test_init_invalid_id3_type(self):
cases = (
(CoverArtImage, []),
(TagCoverArtImage, [File('test.mp3')]),
)
for image_class, args in cases:
image = image_class(*args, id3_type=255)
self.assertEqual(image.id3_type, Id3ImageType.OTHER)
def test_compare_without_type(self):
image1 = create_image(b'a', types=["front"])
image2 = create_image(b'a', types=["back"])
image3 = create_image(b'a', types=["back"], support_types=True)
image4 = create_image(b'b', types=["front"])
self.assertEqual(image1, image2)
self.assertEqual(image1, image3)
self.assertNotEqual(image1, image4)
def test_compare_with_primary_type(self):
image1 = create_image(b'a', types=["front"], support_types=True)
image2 = create_image(b'a', types=["front", "booklet"], support_types=True, support_multi_types=True)
image3 = create_image(b'a', types=["back"], support_types=True)
image4 = create_image(b'b', types=["front"], support_types=True)
image5 = create_image(b'a', types=[], support_types=True)
image6 = create_image(b'a', types=[], support_types=True)
self.assertEqual(image1, image2)
self.assertNotEqual(image1, image3)
self.assertNotEqual(image1, image4)
self.assertNotEqual(image3, image5)
self.assertEqual(image5, image6)
def test_compare_with_multiple_types(self):
image1 = create_image(b'a', types=["front"], support_types=True, support_multi_types=True)
image2 = create_image(b'a', types=["front", "booklet"], support_types=True, support_multi_types=True)
image3 = create_image(b'a', types=["front", "booklet"], support_types=True, support_multi_types=True)
image4 = create_image(b'b', types=["front", "booklet"], support_types=True, support_multi_types=True)
self.assertNotEqual(image1, image2)
self.assertEqual(image2, image3)
self.assertNotEqual(image2, image4)
def test_lt_type1(self):
image1 = create_image(b'a', types=["front"], support_types=True, support_multi_types=True)
image2 = create_image(b'b', types=["booklet"], support_types=True, support_multi_types=True)
self.assertLess(image1, image2)
def test_lt_type2(self):
image1 = create_image(b'a', types=["front"], support_types=True, support_multi_types=True)
image2 = create_image(b'b', types=["booklet", "front"], support_types=True, support_multi_types=True)
self.assertLess(image1, image2)
def test_lt_type3(self):
image1 = create_image(b'a', types=["back"], support_types=True, support_multi_types=True)
image2 = create_image(b'b', types=["-"], support_types=True, support_multi_types=True)
self.assertLess(image1, image2)
def test_lt_comment1(self):
image1 = create_image(b'a', types=["front"], support_types=True, support_multi_types=True)
image2 = create_image(b'b', types=["front"], support_types=True, support_multi_types=True, comment='b')
self.assertLess(image1, image2)
def test_lt_comment2(self):
image1 = create_image(b'a', types=["front"], support_types=True, support_multi_types=True, comment='a')
image2 = create_image(b'b', types=["front"], support_types=True, support_multi_types=True, comment='b')
self.assertLess(image1, image2)
def test_lt_comment3(self):
image1 = create_image(b'b', types=["back"], support_types=False, comment='a') # not supporting types = front
image2 = create_image(b'a', types=["front"], support_types=True, support_multi_types=True, comment='b')
self.assertLess(image1, image2)
def test_lt_datahash(self):
image1 = create_image(b'zz', types=["front"], support_types=True, support_multi_types=True, comment='a')
image2 = create_image(b'xx', types=["front"], support_types=True, support_multi_types=True, comment='a')
self.assertLess(image1, image2)
def test_sorted_images(self):
image1 = create_image(b'a', types=["front"], support_types=True, support_multi_types=True)
image2 = create_image(b'a', types=["booklet"], support_types=True, support_multi_types=True)
image3 = create_image(b'a', types=["front", "booklet"], support_types=True, support_multi_types=True, comment='a')
image4 = create_image(b'b', types=["front", "booklet"], support_types=True, support_multi_types=True, comment='b')
result = sorted([image4, image3, image2, image1])
self.maxDiff = None
self.assertEqual(result, [image1, image3, image4, image2])
def test_set_data(self):
imgdata = create_fake_png(b'a')
imgdata2 = create_fake_png(b'xxx')
# set data once
coverartimage = CoverArtImage(data=imgdata2)
tmp_file = coverartimage.tempfile_filename
filesize = os.path.getsize(tmp_file)
# ensure file was written, and check its length
self.assertEqual(filesize, len(imgdata2))
self.assertEqual(coverartimage.data, imgdata2)
# set data again, with another payload
coverartimage.set_tags_data(imgdata)
tmp_file = coverartimage.tempfile_filename
filesize = os.path.getsize(tmp_file)
# check file length again
self.assertEqual(filesize, len(imgdata))
self.assertEqual(coverartimage.data, imgdata)
def test_save(self):
self.set_config_values({
'image_type_as_filename': True,
'windows_compatibility': True,
'win_compat_replacements': {},
'windows_long_paths': False,
'replace_spaces_with_underscores': False,
'replace_dir_separator': '_',
'enabled_plugins': [],
'ascii_filenames': False,
'save_images_overwrite': False,
})
metadata = Metadata()
counters = Counter()
with TemporaryDirectory() as d:
image1 = create_image(b'a', types=['back'], support_types=True)
expected_filename = os.path.join(d, 'back.png')
counter_filename = encode_filename(os.path.join(d, 'back'))
image1.save(d, metadata, counters)
self.assertTrue(os.path.exists(expected_filename))
self.assertEqual(len(image1.data), os.path.getsize(expected_filename))
self.assertEqual(1, counters[counter_filename])
image2 = create_image(b'bb', types=['back'], support_types=True)
image2.save(d, metadata, counters)
expected_filename_2 = os.path.join(d, 'back (1).png')
self.assertTrue(os.path.exists(expected_filename_2))
self.assertEqual(len(image2.data), os.path.getsize(expected_filename_2))
self.assertEqual(2, counters[counter_filename])
class CoverArtImageMakeFilenameTest(PicardTestCase):
def setUp(self):
super().setUp()
self.image = create_image(b'a', types=['back'], support_types=True)
self.metadata = Metadata()
self.set_config_values({
'windows_compatibility': False,
'win_compat_replacements': {},
'enabled_plugins': [],
'ascii_filenames': False,
'replace_spaces_with_underscores': False,
'replace_dir_separator': '_',
})
def compare_paths(self, path1, path2):
self.assertEqual(
encode_filename(os.path.normpath(path1)),
encode_filename(os.path.normpath(path2)),
)
def test_make_image_filename(self):
filename = self.image._make_image_filename('AlbumArt', '/music/albumart',
self.metadata, win_compat=False, win_shorten_path=False)
self.compare_paths('/music/albumart/AlbumArt', filename)
def test_make_image_filename_default(self):
filename = self.image._make_image_filename('$noop()', '/music/albumart',
self.metadata, win_compat=False, win_shorten_path=False)
self.compare_paths(
os.path.join('/music/albumart/', DEFAULT_COVER_IMAGE_FILENAME), filename)
def test_make_image_filename_relative_path(self):
self.metadata['album'] = 'TheAlbum'
filename = self.image._make_image_filename("../covers/%album%", "/music/album",
self.metadata, win_compat=False, win_shorten_path=False)
self.compare_paths('/music/covers/TheAlbum', filename)
def test_make_image_filename_absolute_path(self):
filename = self.image._make_image_filename('/foo/bar/AlbumArt', '/music/albumart',
self.metadata, win_compat=False, win_shorten_path=False)
self.compare_paths('/foo/bar/AlbumArt', filename)
@unittest.skipUnless(IS_WIN, "windows test")
def test_make_image_filename_absolute_path_no_common_base(self):
filename = self.image._make_image_filename('D:/foo/AlbumArt', 'C:/music',
self.metadata, win_compat=False, win_shorten_path=False)
self.compare_paths('D:\\foo\\AlbumArt', filename)
def test_make_image_filename_script(self):
cover_script = '%album%-$if($eq(%coverart_maintype%,front),cover,%coverart_maintype%)'
self.metadata['album'] = 'TheAlbum'
filename = self.image._make_image_filename(cover_script, "/music/",
self.metadata, win_compat=False, win_shorten_path=False)
self.compare_paths('/music/TheAlbum-back', filename)
def test_make_image_filename_save_path(self):
self.set_config_values({
'windows_compatibility': True,
})
filename = self.image._make_image_filename(".co:ver", "/music/albumart",
self.metadata, win_compat=True, win_shorten_path=False)
self.compare_paths('/music/albumart/_co_ver', filename)
def test_make_image_filename_win_shorten_path(self):
requested_path = "/" + 300 * "a" + "/cover"
expected_path = "/" + 226 * "a" + "/cover"
filename = self.image._make_image_filename(requested_path, "/music/albumart",
self.metadata, win_compat=False, win_shorten_path=True)
self.compare_paths(expected_path, filename)
def test_make_image_filename_win_shorten_path_too_long_base_path(self):
base_path = '/' + 244*'a'
with self.assertRaises(WinPathTooLong):
self.image._make_image_filename("cover", base_path,
self.metadata, win_compat=False, win_shorten_path=True)
class LocalFileCoverArtImageTest(PicardTestCase):
def test_set_file_url(self):
path = '/some/path/image.jpeg'
image = LocalFileCoverArtImage(path)
self.assertEqual(image.url.toString(), 'file://' + path)
def test_support_types(self):
path = '/some/path/image.jpeg'
image = LocalFileCoverArtImage(path)
self.assertFalse(image.support_types)
self.assertFalse(image.support_multi_types)
image = LocalFileCoverArtImage(path, support_types=True)
self.assertTrue(image.support_types)
self.assertFalse(image.support_multi_types)
image = LocalFileCoverArtImage(path, support_multi_types=True)
self.assertFalse(image.support_types)
self.assertTrue(image.support_multi_types)
@unittest.skipUnless(IS_WIN, "windows test")
def test_windows_path(self):
path = 'C:\\Music\\somefile.mp3'
image = LocalFileCoverArtImage(path)
self.assertEqual(image.url.toLocalFile(), 'C:/Music/somefile.mp3')
| 18,688
|
Python
|
.py
| 342
| 46.263158
| 166
| 0.665027
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,849
|
test_util_macos.py
|
metabrainz_picard/test/test_util_macos.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
import unittest
from unittest.mock import patch
from test.picardtestcase import PicardTestCase
from picard.const.sys import IS_MACOS
from picard.util.macos import (
extend_root_volume_path,
strip_root_volume_path,
)
def fake_os_scandir(path):
raise OSError('failed os.scandir')
@unittest.skipUnless(IS_MACOS, "macOS test")
class UtilMacosExtendRootVolumeTest(PicardTestCase):
def test_path_starts_with_volumes(self):
path = '/Volumes/path'
result = extend_root_volume_path(path)
self.assertEqual(result, path)
@patch('picard.util.macos._find_root_volume', lambda: '/Volumes/root_volume')
def test_path_donot_starts_with_volumes_abs(self):
path = '/test/path'
result = extend_root_volume_path(path)
self.assertEqual(result, '/Volumes/root_volume/test/path')
@patch('picard.util.macos._find_root_volume', lambda: '/Volumes/root_volume')
def test_path_donot_starts_with_volumes_rel(self):
path = 'test/path'
result = extend_root_volume_path(path)
self.assertEqual(result, '/Volumes/root_volume/test/path')
@patch('os.scandir', fake_os_scandir)
def test_path_donot_starts_with_volumes_failed(self):
path = '/test/path'
with patch('picard.log.warning') as mock:
result = extend_root_volume_path(path)
self.assertEqual(result, path)
self.assertTrue(mock.called)
@unittest.skipUnless(IS_MACOS, "macOS test")
class UtilMacosStripRootVolumeTest(PicardTestCase):
def test_path_starts_not_with_volumes(self):
path = '/Users/sandra'
result = strip_root_volume_path(path)
self.assertEqual(result, path)
@patch('picard.util.macos._find_root_volume', lambda: '/Volumes/root_volume')
def test_path_starts_not_with_root_volume(self):
path = '/Volumes/other_volume/foo/bar'
result = strip_root_volume_path(path)
self.assertEqual(result, path)
@patch('picard.util.macos._find_root_volume', lambda: '/Volumes/root_volume')
def test_path_starts_with_root_volume(self):
path = '/Volumes/root_volume/foo/bar'
result = strip_root_volume_path(path)
self.assertEqual(result, '/foo/bar')
| 3,052
|
Python
|
.py
| 68
| 39.882353
| 81
| 0.716644
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,850
|
test_util_imageinfo.py
|
metabrainz_picard/test/test_util_imageinfo.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2014, 2020 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import (
PicardTestCase,
get_test_data_path,
)
from picard.util import imageinfo
class IdentifyTest(PicardTestCase):
def test_gif(self):
file = get_test_data_path('mb.gif')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=140,
height=96,
mime='image/gif',
extension='.gif',
datalen=5806
)
)
def test_png(self):
file = get_test_data_path('mb.png')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=140,
height=96,
mime='image/png',
extension='.png',
datalen=11137
)
)
def test_jpeg(self):
file = get_test_data_path('mb.jpg')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=140,
height=96,
mime='image/jpeg',
extension='.jpg',
datalen=8550
)
)
def test_webp_vp8(self):
file = get_test_data_path('mb-vp8.webp')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=140,
height=96,
mime='image/webp',
extension='.webp',
datalen=6178
)
)
def test_webp_vp8l(self):
file = get_test_data_path('mb-vp8l.webp')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=140,
height=96,
mime='image/webp',
extension='.webp',
datalen=9432
)
)
def test_webp_vp8x(self):
file = get_test_data_path('mb-vp8x.webp')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=140,
height=96,
mime='image/webp',
extension='.webp',
datalen=6858
)
)
def test_webp_insufficient_data(self):
self.assertRaises(imageinfo.NotEnoughData, imageinfo.identify, b'RIFF\x00\x00\x00\x00WEBPVP8L')
self.assertRaises(imageinfo.NotEnoughData, imageinfo.identify, b'RIFF\x00\x00\x00\x00WEBPVP8X')
def test_tiff(self):
file = get_test_data_path('mb.tiff')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=140,
height=96,
mime='image/tiff',
extension='.tiff',
datalen=12509
)
)
def test_pdf(self):
file = get_test_data_path('mb.pdf')
with open(file, 'rb') as f:
self.assertEqual(
imageinfo.identify(f.read()),
imageinfo.ImageInfo(
width=0,
height=0,
mime='application/pdf',
extension='.pdf',
datalen=10362
)
)
def test_not_enough_data(self):
self.assertRaises(imageinfo.IdentificationError,
imageinfo.identify, "x")
self.assertRaises(imageinfo.NotEnoughData, imageinfo.identify, "x")
def test_invalid_data(self):
self.assertRaises(imageinfo.IdentificationError,
imageinfo.identify, "x" * 20)
self.assertRaises(imageinfo.UnrecognizedFormat,
imageinfo.identify, "x" * 20)
def test_invalid_png_data(self):
data = '\x89PNG\x0D\x0A\x1A\x0A' + "x" * 20
self.assertRaises(imageinfo.IdentificationError,
imageinfo.identify, data)
self.assertRaises(imageinfo.UnrecognizedFormat,
imageinfo.identify, data)
class SupportsMimeTypeTest(PicardTestCase):
def test_supported_mime_types(self):
self.assertTrue(imageinfo.supports_mime_type('application/pdf'))
self.assertTrue(imageinfo.supports_mime_type('image/gif'))
self.assertTrue(imageinfo.supports_mime_type('image/jpeg'))
self.assertTrue(imageinfo.supports_mime_type('image/png'))
self.assertTrue(imageinfo.supports_mime_type('image/tiff'))
self.assertTrue(imageinfo.supports_mime_type('image/webp'))
def test_unsupported_mime_types(self):
self.assertFalse(imageinfo.supports_mime_type('application/octet-stream'))
self.assertFalse(imageinfo.supports_mime_type('text/html'))
class GetSupportedExtensionsTest(PicardTestCase):
def test_supported_extensions(self):
extensions = list(imageinfo.get_supported_extensions())
self.assertIn('.jpeg', extensions)
self.assertIn('.jpg', extensions)
self.assertIn('.pdf', extensions)
self.assertIn('.png', extensions)
self.assertIn('.tif', extensions)
self.assertIn('.tiff', extensions)
self.assertIn('.webp', extensions)
| 6,632
|
Python
|
.py
| 169
| 26.798817
| 103
| 0.553569
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,851
|
test_browser.py
|
metabrainz_picard/test/test_browser.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018, 2020-2021 Laurent Monin
# Copyright (C) 2019, 2022, 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from unittest.mock import (
MagicMock,
Mock,
patch,
)
from urllib.parse import (
parse_qs,
urlparse,
)
from test.picardtestcase import PicardTestCase
from picard.browser.filelookup import FileLookup
from picard.util import webbrowser2
SERVER = 'musicbrainz.org'
PORT = 443
LOCAL_PORT = "8000"
class BrowserLookupTest(PicardTestCase):
def setUp(self):
super().setUp()
self.lookup = FileLookup(None, SERVER, PORT, LOCAL_PORT)
def assert_mb_url_matches(self, url, path, query_args=None):
parsed_url = urlparse(url)
expected_host = SERVER
self.assertEqual(expected_host, parsed_url.netloc, '"%s" hostname does not match "%s"' % (url, expected_host))
self.assertEqual('https' if PORT == 443 else 'http', parsed_url.scheme)
self.assertEqual(path, parsed_url.path, '"%s" path does not match "%s"' % (url, path))
if query_args is not None:
actual_query_args = {k: v[0] for k, v in parse_qs(parsed_url.query).items()}
self.assertEqual(query_args, actual_query_args)
def assert_mb_entity_url_matches(self, url, entity, mbid, query_args=None):
path = '/'.join(('', entity, mbid))
self.assert_mb_url_matches(url, path, query_args)
def test_entity_lookups(self):
lookups = (
{'function': self.lookup.recording_lookup, 'entity': 'recording'},
{'function': self.lookup.track_lookup, 'entity': 'track'},
{'function': self.lookup.album_lookup, 'entity': 'release'},
{'function': self.lookup.work_lookup, 'entity': 'work'},
{'function': self.lookup.artist_lookup, 'entity': 'artist'},
{'function': self.lookup.artist_lookup, 'entity': 'artist'},
{'function': self.lookup.release_group_lookup, 'entity': 'release-group'},
{'function': self.lookup.discid_lookup, 'entity': 'cdtoc'},
)
for case in lookups:
with patch.object(webbrowser2, 'open') as mock_open:
result = case['function']("123")
self.assertTrue(result)
mock_open.assert_called_once()
url = mock_open.call_args[0][0]
query_args = {'tport': '8000'}
self.assert_mb_entity_url_matches(url, case['entity'], '123', query_args)
@patch.object(webbrowser2, 'open')
def test_discid_submission(self, mock_open):
url = 'https://testmb.org/cdtoc/attach?id=123'
result = self.lookup.discid_submission(url)
self.assertTrue(result)
mock_open.assert_called_once()
url = mock_open.call_args[0][0]
self.assertEqual('https://testmb.org/cdtoc/attach?id=123&tport=8000', url)
@patch.object(webbrowser2, 'open')
def test_acoustid_lookup(self, mock_open):
result = self.lookup.acoust_lookup('123')
self.assertTrue(result)
mock_open.assert_called_once()
url = mock_open.call_args[0][0]
self.assertEqual('https://acoustid.org/track/123', url)
def test_mbid_lookup_invalid_url(self):
self.assertFalse(self.lookup.mbid_lookup('noentity:123'))
def test_mbid_lookup_no_entity(self):
self.assertFalse(self.lookup.mbid_lookup('F03D09B3-39DC-4083-AFD6-159E3F0D462F'))
@patch.object(webbrowser2, 'open')
def test_mbid_lookup_set_type(self, mock_open):
result = self.lookup.mbid_lookup('bd55aeb7-19d1-4607-a500-14b8479d3fed', 'place')
self.assertTrue(result)
mock_open.assert_called_once()
url = mock_open.call_args[0][0]
self.assert_mb_entity_url_matches(url, 'place', 'bd55aeb7-19d1-4607-a500-14b8479d3fed')
@patch.object(webbrowser2, 'open')
def test_mbid_lookup_matched_callback(self, mock_open):
mock_matched_callback = Mock()
result = self.lookup.mbid_lookup('area:F03D09B3-39DC-4083-AFD6-159E3F0D462F', mbid_matched_callback=mock_matched_callback)
self.assertTrue(result)
mock_open.assert_called_once()
url = mock_open.call_args[0][0]
self.assert_mb_entity_url_matches(url, 'area', 'f03d09b3-39dc-4083-afd6-159e3f0d462f')
def test_mbid_lookup_release(self):
self.tagger.load_album = MagicMock()
url = 'https://musicbrainz.org/release/60dbf818-3058-41b9-bb53-25dbdb9d9bad'
result = self.lookup.mbid_lookup(url)
self.assertTrue(result)
self.tagger.load_album.assert_called_once_with('60dbf818-3058-41b9-bb53-25dbdb9d9bad')
def test_mbid_lookup_recording(self):
self.tagger.load_nat = MagicMock()
url = 'https://musicbrainz.org/recording/511f3a33-ded8-4dc7-92d2-b913ec420dfc'
result = self.lookup.mbid_lookup(url)
self.assertTrue(result)
self.tagger.load_nat.assert_called_once_with('511f3a33-ded8-4dc7-92d2-b913ec420dfc')
@patch('picard.browser.filelookup.AlbumSearchDialog')
def test_mbid_lookup_release_group(self, mock_dialog):
url = 'https://musicbrainz.org/release-group/168615bf-f841-49f7-ac98-36a4eb25479c'
result = self.lookup.mbid_lookup(url)
self.assertTrue(result)
mock_dialog.show_releasegroup_search.assert_called_once_with('168615bf-f841-49f7-ac98-36a4eb25479c')
def test_mbid_lookup_browser_fallback(self):
mbid = '4836aa50-a9ae-490a-983b-cfc8efca92de'
for entity in {'area', 'artist', 'instrument', 'label', 'place', 'series', 'url', 'work'}:
with patch.object(webbrowser2, 'open') as mock_open:
uri = '%s:%s' % (entity, mbid)
result = self.lookup.mbid_lookup(uri)
self.assertTrue(result, 'lookup failed for %s' % uri)
mock_open.assert_called_once()
url = mock_open.call_args[0][0]
self.assert_mb_entity_url_matches(url, entity, mbid)
@patch.object(webbrowser2, 'open')
def test_mbid_lookup_browser_fallback_disabled(self, mock_open):
url = 'https://musicbrainz.org/artist/4836aa50-a9ae-490a-983b-cfc8efca92de'
result = self.lookup.mbid_lookup(url, browser_fallback=False)
self.assertFalse(result)
mock_open.assert_not_called()
@patch('picard.browser.filelookup.Disc')
def test_mbid_lookup_cdtoc(self, mock_disc):
url = 'https://musicbrainz.org/cdtoc/vtlGcbJUaP_IFdBUC10NGIhu2E0-'
result = self.lookup.mbid_lookup(url)
self.assertTrue(result)
mock_disc.assert_called_once_with(id='vtlGcbJUaP_IFdBUC10NGIhu2E0-')
instance = mock_disc.return_value
instance.lookup.assert_called_once()
@patch.object(webbrowser2, 'open')
def test_tag_lookup(self, mock_open):
args = {
'artist': 'Artist',
'release': 'Release',
'track': 'Track',
'tracknum': 'Tracknum',
'duration': 'Duration',
'filename': 'Filename',
}
result = self.lookup.tag_lookup(**args)
self.assertTrue(result)
url = mock_open.call_args[0][0]
args['tport'] = '8000'
self.assert_mb_url_matches(url, '/taglookup', args)
@patch.object(webbrowser2, 'open')
def test_collection_lookup(self, mock_open):
result = self.lookup.collection_lookup(123)
self.assertTrue(result)
url = mock_open.call_args[0][0]
self.assert_mb_url_matches(url, '/user/123/collections')
@patch.object(webbrowser2, 'open')
def test_search_entity(self, mock_open):
self.set_config_values({'query_limit': 25})
result = self.lookup.search_entity('foo', 'search:123')
self.assertTrue(result)
url = mock_open.call_args[0][0]
query_args = {
'type': 'foo',
'query': 'search:123',
'limit': '25',
'tport': '8000',
}
self.assert_mb_url_matches(url, '/search/textsearch', query_args)
@patch.object(webbrowser2, 'open')
def test_search_entity_advanced(self, mock_open):
self.set_config_values({'query_limit': 25})
result = self.lookup.search_entity('foo', 'search:123', adv=True)
self.assertTrue(result)
url = mock_open.call_args[0][0]
query_args = {
'type': 'foo',
'query': 'search:123',
'limit': '25',
'tport': '8000',
'adv': 'on',
}
self.assert_mb_url_matches(url, '/search/textsearch', query_args)
def test_search_entity_mbid_lookup(self):
with patch.object(self.lookup, 'mbid_lookup') as mock_lookup:
entity = 'artist'
mbid = '4836aa50-a9ae-490a-983b-cfc8efca92de'
callback = Mock()
result = self.lookup.search_entity(entity, mbid, mbid_matched_callback=callback)
self.assertTrue(result)
mock_lookup.assert_called_once_with(mbid, entity, mbid_matched_callback=callback)
@patch.object(webbrowser2, 'open')
def test_search_entity_mbid_lookup_force_browser(self, mock_open):
self.set_config_values({'query_limit': 25})
with patch.object(self.lookup, 'mbid_lookup') as mock_lookup:
entity = 'artist'
mbid = '4836aa50-a9ae-490a-983b-cfc8efca92de'
callback = Mock()
result = self.lookup.search_entity(entity, mbid, mbid_matched_callback=callback, force_browser=True)
self.assertTrue(result)
mock_lookup.assert_not_called()
url = mock_open.call_args[0][0]
query_args = {
'type': entity,
'query': mbid,
'limit': '25',
'tport': '8000',
}
self.assert_mb_url_matches(url, '/search/textsearch', query_args)
| 10,675
|
Python
|
.py
| 222
| 39.490991
| 130
| 0.642042
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,852
|
test_util_get_base_title.py
|
metabrainz_picard/test/test_util_get_base_title.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util import get_base_title_with_suffix
class GetBaseTitle(PicardTestCase):
def test_base_title_0(self):
# Test with no matching suffix
test_title = 'title'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, 'title')
def test_base_title_1(self):
# Test with matching suffix but no number section
test_title = 'title (copy)'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, 'title')
def test_base_title_2(self):
# Test with matching suffix and number
test_title = 'title (copy) (1)'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, 'title')
def test_base_title_3(self):
# Test with missing space between suffix and number section
test_title = 'title (copy)(1)'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, test_title)
def test_base_title_4(self):
# Test with missing space between suffix and number section (and missing number)
test_title = 'title (copy)()'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, test_title)
def test_base_title_5(self):
# Test with missing number
test_title = 'title (copy) ()'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, 'title')
def test_base_title_6(self):
# Test with invalid number
test_title = 'title (copy) (x)'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, test_title)
def test_base_title_7(self):
# Test with extra character after number section
test_title = 'title (copy) (1)x'
title = get_base_title_with_suffix(test_title, '(copy)', '{title} ({count})')
self.assertEqual(title, test_title)
def test_base_title_8(self):
# Test escaping of suffix
test_title = 'title (copy) (1)'
title = get_base_title_with_suffix(test_title, '(c?py)', '{title} ({count})')
self.assertEqual(title, 'title (copy)')
def test_base_title_9(self):
# Test with matching suffix but no number section
test_title = 'title (copy)'
title = get_base_title_with_suffix(test_title, '(copy)', '({count}) {title}')
self.assertEqual(title, 'title')
def test_base_title_10(self):
# Test with matching suffix and number section in wrong location
test_title = 'title (copy) (1)'
title = get_base_title_with_suffix(test_title, '(copy)', '({count}) {title}')
self.assertEqual(title, test_title)
def test_base_title_11(self):
# Test with matching suffix and number section
test_title = '(1) title (copy)'
title = get_base_title_with_suffix(test_title, '(copy)', '({count}) {title}')
self.assertEqual(title, 'title')
def test_base_title_12(self):
# Test with matching suffix and number section but with additional characters after suffix
test_title = '(1) title (copy) (1)'
title = get_base_title_with_suffix(test_title, '(copy)', '({count}) {title}')
self.assertEqual(title, 'title (copy) (1)')
| 4,331
|
Python
|
.py
| 87
| 43.206897
| 98
| 0.654601
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,853
|
test_util_astrcmp.py
|
metabrainz_picard/test/test_util_astrcmp.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Lukáš Lalinský
# Copyright (C) 2017 Sophist-UK
# Copyright (C) 2017-2018 Wieland Hoffmann
# Copyright (C) 2018, 2020-2021 Laurent Monin
# Copyright (C) 2018-2019, 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import unittest
from test.picardtestcase import PicardTestCase
from picard.util.astrcmp import astrcmp_py
try:
from picard.util.astrcmp import astrcmp_c
except ImportError:
astrcmp_c = None
class AstrcmpBase:
func = None
def test_astrcmp(self):
astrcmp = self.__class__.func
self.assertAlmostEqual(0.0, astrcmp("", ""))
self.assertAlmostEqual(0.0, astrcmp("a", ""))
self.assertAlmostEqual(0.0, astrcmp("", "a"))
self.assertAlmostEqual(1.0, astrcmp("a", "a"))
self.assertAlmostEqual(0.0, astrcmp("a", "b"))
self.assertAlmostEqual(0.0, astrcmp("ab", "ba"))
self.assertAlmostEqual(0.7083333333333333, astrcmp("The Great Gig in the Sky", "Great Gig In The sky"))
class AstrcmpCTest(AstrcmpBase, PicardTestCase):
func = astrcmp_c
@unittest.skipIf(astrcmp_c is None, "The _astrcmp C extension module has not been compiled")
def test_astrcmp(self):
super().test_astrcmp()
class AstrcmpPyTest(AstrcmpBase, PicardTestCase):
func = astrcmp_py
| 2,042
|
Python
|
.py
| 48
| 39.020833
| 111
| 0.734446
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,854
|
test_filesystem.py
|
metabrainz_picard/test/test_filesystem.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018 Antonio Larrosa
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2021 Laurent Monin
# Copyright (C) 2018-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from contextlib import suppress
import os.path
import shutil
from test.picardtestcase import PicardTestCase
from picard import config
import picard.formats
def prepare_files(src_dir, dst_dir, src_files=None, dst_files=None, src_rel_path='', dst_rel_path=''):
"""Prepare src files and dst filenames for a test."""
with suppress(FileExistsError):
os.mkdir(os.path.join(src_dir, src_rel_path))
# Prepare the source directory structure under src_dir
# <src_dir>/<src_rel_path>/test.mp3
# <src_dir>/<src_rel_path>/cover.jpg
def src_file(name, sample_name=None):
"""Copy file from samples and returns path to temporary file to be
used as source.
If sample_name isn't provided, it will use name for it
"""
if sample_name is None:
sample_name = name
sample = os.path.join('test', 'data', sample_name)
copy_to = os.path.join(src_dir, src_rel_path, name)
shutil.copy(sample, copy_to)
return copy_to
src = dict()
if src_files:
for filename, sample_name in src_files.items():
src[filename] = src_file(filename, sample_name)
with suppress(FileExistsError):
os.mkdir(os.path.join(dst_dir, dst_rel_path))
# Prepare the target filenames under dst_dir
# <dst_dir>/<dst_rel_path>/test.mp3
# <dst_dir>/<dst_rel_path>/cover.jpg
def dst_file(name):
"""Returns path to temporary target file"""
return os.path.join(dst_dir, dst_rel_path, name)
dst = dict()
if dst_files:
for filename in dst_files:
dst[filename] = dst_file(filename)
return src, dst
class SampleFileSystem(PicardTestCase):
settings = {
'enabled_plugins': '',
'move_files': True,
'move_additional_files': True,
'move_additional_files_pattern': 'cover.jpg',
}
src_files = {
'test.mp3': None,
'cover.jpg': 'mb.jpg',
'.hidden.jpg': 'mb.jpg',
}
dst_files = {
'test.mp3',
'cover.jpg',
'.hidden.jpg',
}
def setUp(self):
super().setUp()
self.src_directory = self.mktmpdir()
self.dst_directory = self.mktmpdir()
self.set_config_values(self.settings)
def _prepare_files(self, src_rel_path='', dst_rel_path=''):
"""Prepare src files and dst filenames for a test."""
return prepare_files(
self.src_directory, self.dst_directory,
self.src_files, self.dst_files,
src_rel_path=src_rel_path,
dst_rel_path=dst_rel_path
)
def _assertFile(self, path):
self.assertTrue(os.path.isfile(path))
def _assertNoFile(self, path):
self.assertFalse(os.path.isfile(path))
class TestAdditionalFilesMoves(SampleFileSystem):
src_files = {
'test.mp3': None,
'cover1.jpg': 'mb.jpg',
'cover2.JPG': 'mb.jpg',
'.hidden1.jpg': 'mb.jpg',
'.hidden2.JPG': 'mb.jpg',
}
dst_files = list(src_files)
def test_no_pattern(self):
src, dst = self._prepare_files()
f = picard.formats.open_(src['test.mp3'])
moves = set(f._get_additional_files_moves(self.src_directory, self.dst_directory, ()))
expected = set()
self.assertEqual(moves, expected)
def test_no_src_dir(self):
src, dst = self._prepare_files()
f = picard.formats.open_(src['test.mp3'])
patterns = f._compile_move_additional_files_pattern('*.jpg')
with self.assertRaises(FileNotFoundError):
moves = set(f._get_additional_files_moves(self.src_directory + 'donotexist', self.dst_directory, patterns))
del moves
def test_no_dst_dir(self):
src, dst = self._prepare_files()
f = picard.formats.open_(src['test.mp3'])
patterns = f._compile_move_additional_files_pattern('*.jpg')
suffix = 'donotexist'
moves = set(f._get_additional_files_moves(self.src_directory, self.dst_directory + suffix, patterns))
expected = {
(src['cover1.jpg'], os.path.join(self.dst_directory + suffix, 'cover1.jpg')),
(src['cover2.JPG'], os.path.join(self.dst_directory + suffix, 'cover2.JPG')),
}
self.assertEqual(moves, expected)
def test_all_jpg_no_hidden(self):
src, dst = self._prepare_files()
f = picard.formats.open_(src['test.mp3'])
patterns = f._compile_move_additional_files_pattern('*.j?g *.jpg')
moves = set(f._get_additional_files_moves(self.src_directory, self.dst_directory, patterns))
expected = {
(src['cover1.jpg'], dst['cover1.jpg']),
(src['cover2.JPG'], dst['cover2.JPG']),
}
self.assertEqual(moves, expected)
def test_all_hidden_jpg(self):
src, dst = self._prepare_files()
f = picard.formats.open_(src['test.mp3'])
patterns = f._compile_move_additional_files_pattern('.*.j?g .*.jpg')
moves = set(f._get_additional_files_moves(self.src_directory, self.dst_directory, patterns))
expected = {
(src['.hidden1.jpg'], dst['.hidden1.jpg']),
(src['.hidden2.JPG'], dst['.hidden2.JPG']),
}
self.assertEqual(moves, expected)
def test_one_only_jpg(self):
src, dst = self._prepare_files()
f = picard.formats.open_(src['test.mp3'])
patterns = f._compile_move_additional_files_pattern('.*1.j?g *1.jpg')
moves = set(f._get_additional_files_moves(self.src_directory, self.dst_directory, patterns))
expected = {
(src['.hidden1.jpg'], dst['.hidden1.jpg']),
(src['cover1.jpg'], dst['cover1.jpg']),
}
self.assertEqual(moves, expected)
class TestFileSystem(SampleFileSystem):
def _move_additional_files(self, src, dst):
f = picard.formats.open_(src['test.mp3'])
f._move_additional_files(src['test.mp3'], dst['test.mp3'], config)
def _assert_files_moved(self, src, dst):
self._move_additional_files(src, dst)
self._assertFile(dst['cover.jpg'])
self._assertNoFile(src['cover.jpg'])
def _assert_files_not_moved(self, src, dst):
self._move_additional_files(src, dst)
self._assertNoFile(dst['cover.jpg'])
self._assertFile(src['cover.jpg'])
def test_move_additional_files_source_unicode(self):
src, dst = self._prepare_files(src_rel_path='música')
self._assert_files_moved(src, dst)
def test_move_additional_files_target_unicode(self):
src, dst = self._prepare_files(dst_rel_path='música')
self._assert_files_moved(src, dst)
def test_move_additional_files_duplicate_patterns(self):
src, dst = self._prepare_files()
config.setting['move_additional_files_pattern'] = 'cover.jpg *.jpg'
self._assert_files_moved(src, dst)
def test_move_additional_files_hidden_nopattern(self):
src, dst = self._prepare_files()
config.setting['move_additional_files_pattern'] = '*.jpg'
self._assert_files_moved(src, dst)
self._assertNoFile(dst['.hidden.jpg'])
self._assertFile(src['.hidden.jpg'])
def test_move_additional_files_hidden_pattern(self):
src, dst = self._prepare_files()
config.setting['move_additional_files_pattern'] = '*.jpg .*.jpg'
self._assert_files_moved(src, dst)
self._assertFile(dst['.hidden.jpg'])
self._assertNoFile(src['.hidden.jpg'])
def test_move_additional_files_disabled(self):
config.setting['move_additional_files'] = False
src, dst = self._prepare_files(src_rel_path='música')
self._assert_files_not_moved(src, dst)
def test_move_files_disabled(self):
config.setting['move_files'] = False
src, dst = self._prepare_files(src_rel_path='música')
self._assert_files_not_moved(src, dst)
| 8,846
|
Python
|
.py
| 202
| 36.346535
| 119
| 0.638533
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,855
|
test_util_filenaming.py
|
metabrainz_picard/test/test_util_filenaming.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013-2014 Ionuț Ciocîrlan
# Copyright (C) 2016 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2021 Laurent Monin
# Copyright (C) 2019-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import os
import os.path
import sys
from tempfile import (
NamedTemporaryFile,
TemporaryDirectory,
)
import unittest
from test.picardtestcase import PicardTestCase
from picard.const.sys import (
IS_MACOS,
IS_WIN,
)
from picard.util.filenaming import (
ShortenMode,
WinPathTooLong,
get_available_filename,
make_save_path,
make_short_filename,
move_ensure_casing,
replace_extension,
samefile_different_casing,
shorten_path,
)
class ShortFilenameTest(PicardTestCase):
def __init__(self, *args, **kwargs):
self.maxDiff = None
self.root = os.path.join(IS_WIN and "X:\\" or "/", "x" * 10)
if IS_WIN:
self.max_len = 255
else:
self.max_len = os.statvfs("/").f_namemax
super().__init__(*args, **kwargs)
@unittest.skipUnless(IS_WIN or IS_MACOS, "windows / macOS test")
def test_bmp_unicode_on_unicode_fs(self):
char = "\N{LATIN SMALL LETTER SHARP S}"
fn = make_short_filename(self.root, os.path.join(*[char * 120] * 2))
self.assertEqual(fn, os.path.join(*[char * 120] * 2))
@unittest.skipUnless(not IS_WIN and not IS_MACOS, "non-windows, non-osx test")
def test_bmp_unicode_on_nix(self):
char = "\N{LATIN SMALL LETTER SHARP S}"
max_len = self.max_len
divisor = len(char.encode(sys.getfilesystemencoding()))
fn = make_short_filename(self.root, os.path.join(*[char * 200] * 2))
self.assertEqual(fn, os.path.join(*[char * (max_len // divisor)] * 2))
@unittest.skipUnless(IS_MACOS, "macOS test")
def test_precomposed_unicode_on_osx(self):
char = "\N{LATIN SMALL LETTER A WITH BREVE}"
max_len = self.max_len
fn = make_short_filename(self.root, os.path.join(*[char * 200] * 2))
self.assertEqual(fn, os.path.join(*[char * (max_len // 2)] * 2))
@unittest.skipUnless(IS_WIN, "windows test")
def test_nonbmp_unicode_on_windows(self):
char = "\N{MUSICAL SYMBOL G CLEF}"
remaining = 259 - (3 + 10 + 1 + 200 + 1)
fn = make_short_filename(self.root, os.path.join(*[char * 100] * 2), win_shorten_path=True)
self.assertEqual(fn, os.path.join(char * 100, char * (remaining // 2)))
@unittest.skipUnless(IS_MACOS, "macOS test")
def test_nonbmp_unicode_on_osx(self):
char = "\N{MUSICAL SYMBOL G CLEF}"
max_len = self.max_len
fn = make_short_filename(self.root, os.path.join(*[char * 200] * 2))
self.assertEqual(fn, os.path.join(*[char * (max_len // 2)] * 2))
@unittest.skipUnless(not IS_WIN and not IS_MACOS, "non-windows, non-osx test")
def test_nonbmp_unicode_on_nix(self):
char = "\N{MUSICAL SYMBOL G CLEF}"
max_len = self.max_len
divisor = len(char.encode(sys.getfilesystemencoding()))
fn = make_short_filename(self.root, os.path.join(*[char * 100] * 2))
self.assertEqual(fn, os.path.join(*[char * (max_len // divisor)] * 2))
@unittest.skipUnless(not IS_WIN and not IS_MACOS, "non-windows, non-osx test")
def test_nonbmp_unicode_on_nix_with_windows_compat(self):
char = "\N{MUSICAL SYMBOL G CLEF}"
max_len = self.max_len
remaining = 259 - (3 + 10 + 1 + 200 + 1)
divisor = len(char.encode(sys.getfilesystemencoding()))
fn = make_short_filename(self.root, os.path.join(*[char * 100] * 2), win_shorten_path=True)
self.assertEqual(fn, os.path.join(char * (max_len // divisor), char * (remaining // 2)))
def test_windows_shortening(self):
fn = make_short_filename(self.root, os.path.join("a" * 200, "b" * 200, "c" * 200 + ".ext"), win_shorten_path=True)
self.assertEqual(fn, os.path.join("a" * 116, "b" * 116, "c" * 7 + ".ext"))
@unittest.skipUnless(not IS_WIN, "non-windows test")
def test_windows_shortening_with_ancestor_on_nix(self):
root = os.path.join(self.root, "w" * 10, "x" * 10, "y" * 9, "z" * 9)
fn = make_short_filename(
root, os.path.join("b" * 200, "c" * 200, "d" * 200 + ".ext"),
win_shorten_path=True, relative_to=self.root)
self.assertEqual(fn, os.path.join("b" * 100, "c" * 100, "d" * 7 + ".ext"))
def test_windows_node_maxlength_shortening(self):
max_len = 226
remaining = 259 - (3 + 10 + 1 + max_len + 1)
fn = make_short_filename(self.root, os.path.join("a" * 300, "b" * 100 + ".ext"), win_shorten_path=True)
self.assertEqual(fn, os.path.join("a" * max_len, "b" * (remaining - 4) + ".ext"))
def test_windows_selective_shortening(self):
root = self.root + "x" * (44 - 10 - 3)
fn = make_short_filename(root, os.path.join(
os.path.join(*["a" * 9] * 10 + ["b" * 15] * 10), "c" * 10), win_shorten_path=True)
self.assertEqual(fn, os.path.join(os.path.join(*["a" * 9] * 10 + ["b" * 9] * 10), "c" * 10))
def test_windows_shortening_not_needed(self):
root = self.root + "x" * 33
fn = make_short_filename(root, os.path.join(
os.path.join(*["a" * 9] * 20), "b" * 10), win_shorten_path=True)
self.assertEqual(fn, os.path.join(os.path.join(*["a" * 9] * 20), "b" * 10))
def test_windows_path_too_long(self):
root = self.root + "x" * 230
self.assertRaises(WinPathTooLong, make_short_filename,
root, os.path.join("a", "b", "c", "d"), win_shorten_path=True)
@unittest.skipUnless(IS_WIN, "windows test")
def test_windows_long_path_allowed(self):
char = "Ä"
path = os.path.join(*[char * self.max_len] * 3)
fn = make_short_filename(self.root, path, win_shorten_path=False)
self.assertEqual(fn, path)
@unittest.skipUnless(IS_WIN, "windows test")
def test_windows_long_path_node_limit(self):
char = "Ä"
path = os.path.join(*[char * (self.max_len + 1)] * 3)
fn = make_short_filename(self.root, path, win_shorten_path=False)
expected_path = os.path.join(*[char * self.max_len] * 3)
self.assertEqual(fn, expected_path)
def test_windows_path_not_too_long(self):
root = self.root + "x" * 230
fn = make_short_filename(root, os.path.join("a", "b", "c"), win_shorten_path=True)
self.assertEqual(fn, os.path.join("a", "b", "c"))
def test_whitespace(self):
fn = make_short_filename(self.root, os.path.join("a1234567890 ", " b1234567890 "))
self.assertEqual(fn, os.path.join("a1234567890", "b1234567890"))
class SamefileDifferentCasingTest(PicardTestCase):
@unittest.skipUnless(IS_WIN, "windows test")
def test_samefile_different_casing(self):
with NamedTemporaryFile(prefix='Foo') as f:
real_name = f.name
lower_name = real_name.lower()
self.assertFalse(samefile_different_casing(real_name, real_name))
self.assertFalse(samefile_different_casing(lower_name, lower_name))
self.assertTrue(samefile_different_casing(real_name, lower_name))
def test_samefile_different_casing_non_existant_file(self):
self.assertFalse(samefile_different_casing("/foo/bar", "/foo/BAR"))
def test_samefile_different_casing_identical_path(self):
self.assertFalse(samefile_different_casing("/foo/BAR", "/foo/BAR"))
class MoveEnsureCasingTest(PicardTestCase):
def test_move_ensure_casing(self):
with TemporaryDirectory() as d:
file_path = os.path.join(d, 'foo')
target_path = os.path.join(d, 'FOO')
open(file_path, 'a').close()
move_ensure_casing(file_path, target_path)
files = os.listdir(d)
self.assertIn('FOO', files)
class MakeSavePathTest(PicardTestCase):
def test_replace_trailing_dots(self):
path = 'foo./bar.'
self.assertEqual(path, make_save_path(path))
self.assertEqual('foo_/bar_', make_save_path(path, win_compat=True))
def test_replace_leading_dots(self):
path = '.foo/.bar'
self.assertEqual('_foo/_bar', make_save_path(path))
def test_decompose_precomposed_chars(self):
path = 'foo/\u00E9bar' # é
self.assertEqual('foo/\u0065\u0301bar', make_save_path(path, mac_compat=True))
def test_remove_zero_length_space(self):
path = 'foo/\u200Bbar'
self.assertEqual('foo/bar', make_save_path(path))
class GetAvailableFilenameTest(PicardTestCase):
def _add_number(self, filename, number):
name, ext = os.path.splitext(filename)
return '%s (%i)%s' % (name, number, ext)
def test_append_number(self):
with NamedTemporaryFile(prefix='foo', suffix='.mp3') as f:
new_filename = get_available_filename(f.name)
self.assertEqual(self._add_number(f.name, 1), new_filename)
def test_do_not_append_number_on_same_file(self):
with NamedTemporaryFile(prefix='foo', suffix='.mp3') as f:
new_filename = get_available_filename(f.name, f.name)
self.assertEqual(f.name, new_filename)
def test_handle_non_existant_old_path(self):
with NamedTemporaryFile(prefix='foo', suffix='.mp3') as f:
new_filename = get_available_filename(f.name, '/foo/old.mp3')
self.assertEqual(self._add_number(f.name, 1), new_filename)
def test_append_additional_numbers(self):
with TemporaryDirectory() as d:
expected_number = 3
oldname = os.path.join(d, 'bar.mp3')
open(oldname, 'a').close()
filename = os.path.join(d, 'foo.mp3')
open(filename, 'a').close()
for i in range(1, expected_number):
open(self._add_number(filename, i), 'a').close()
new_filename = get_available_filename(filename, oldname)
self.assertEqual(self._add_number(filename, expected_number), new_filename)
def test_reuse_existing_number(self):
with TemporaryDirectory() as d:
expected_number = 2
filename = os.path.join(d, 'foo.mp3')
open(filename, 'a').close()
for i in range(1, 3):
open(self._add_number(filename, i), 'a').close()
oldname = self._add_number(filename, expected_number)
new_filename = get_available_filename(filename, oldname)
self.assertEqual(self._add_number(filename, expected_number), new_filename)
class ReplaceExtensionTest(PicardTestCase):
def test_replace(self):
self.assertEqual('foo/bar.wvc', replace_extension('foo/bar.wv', '.wvc'))
self.assertEqual('foo/bar.wvc', replace_extension('foo/bar.wv', 'wvc'))
self.assertEqual('foo/bar.wvc', replace_extension('foo/bar', 'wvc'))
class ShortenPathTest(PicardTestCase):
def test_shorten_path(self):
self.assertEqual(
os.path.join('aaaaa', 'bbbbb', 'c.mp3'),
shorten_path(os.path.join('a' * 6, 'b' * 6, 'cccccc.mp3'), 5, ShortenMode.BYTES))
self.assertEqual(
os.path.join('ä' * 255, 'ö' * 255, 'ü' * 251 + '.ext'),
shorten_path(os.path.join('ä' * 256, 'ö' * 256, 'ü' * 256 + '.ext'), 255, ShortenMode.UTF16))
| 12,123
|
Python
|
.py
| 236
| 43.618644
| 122
| 0.631258
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,856
|
test_utils.py
|
metabrainz_picard/test/test_utils.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007 Lukáš Lalinský
# Copyright (C) 2010 fatih
# Copyright (C) 2010-2011, 2014, 2018-2022 Philipp Wolfer
# Copyright (C) 2012, 2014, 2018 Wieland Hoffmann
# Copyright (C) 2013 Ionuț Ciocîrlan
# Copyright (C) 2013-2014, 2018-2021 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2016 Frederik “Freso” S. Olesen
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2017 Shen-Ta Hsieh
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Vladislav Karbovskii
#
# This program is free software; you can redistribute it and/or
# modify 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.
from collections import namedtuple
from collections.abc import Iterator
import os
import re
import subprocess # nosec: B404
from tempfile import NamedTemporaryFile
import unittest
from unittest.mock import (
Mock,
patch,
)
from test.picardtestcase import (
PicardTestCase,
get_test_data_path,
)
from picard import util
from picard.const import MUSICBRAINZ_SERVERS
from picard.const.sys import (
IS_MACOS,
IS_WIN,
)
from picard.i18n import gettext as _
from picard.util import (
IgnoreUpdatesContext,
album_artist_from_path,
any_exception_isinstance,
build_qurl,
detect as charset_detect,
detect_file_encoding,
encoded_queryargs,
extract_year_from_date,
find_best_match,
is_absolute_path,
iter_exception_chain,
iter_files_from_objects,
iter_unique,
limited_join,
make_filename_from_title,
normpath,
pattern_as_regex,
sort_by_similarity,
system_supports_long_paths,
tracknum_and_title_from_filename,
tracknum_from_filename,
uniqify,
wildcards_to_regex_pattern,
win_prefix_longpath,
)
class ReplaceWin32IncompatTest(PicardTestCase):
@unittest.skipUnless(IS_WIN, "windows test")
def test_correct_absolute_win32(self):
self.assertEqual(util.replace_win32_incompat('c:\\test\\te"st/2'),
'c:\\test\\te_st/2')
self.assertEqual(util.replace_win32_incompat('c:\\test\\d:/2'),
'c:\\test\\d_/2')
@unittest.skipUnless(not IS_WIN, 'non-windows test')
def test_correct_absolute_non_win32(self):
self.assertEqual(util.replace_win32_incompat('/test/te"st/2'),
'/test/te_st/2')
self.assertEqual(util.replace_win32_incompat('/test/d:/2'),
'/test/d_/2')
def test_correct_relative(self):
self.assertEqual(util.replace_win32_incompat('A"*:<>?|b'),
'A_______b')
self.assertEqual(util.replace_win32_incompat('d:tes<t'),
'd_tes_t')
def test_incorrect(self):
self.assertNotEqual(util.replace_win32_incompat('c:\\test\\te"st2'),
'c:\\test\\te"st2')
def test_custom_replacement_char(self):
self.assertEqual(util.replace_win32_incompat('A"*:<>?|b', repl='+'),
"A+++++++b")
def test_custom_replacement_map(self):
input = 'foo*:<>?|"'
replacments = {
'*': 'A',
':': 'B',
'<': 'C',
'>': 'D',
'?': 'E',
'|': 'F',
'"': 'G',
}
replaced = util.replace_win32_incompat(input, replacements=replacments)
self.assertEqual('fooABCDEFG', replaced)
def test_partial_replacement_map(self):
input = 'foo*:<>?|"'
replacments = {
'*': 'A',
'<': 'C',
}
replaced = util.replace_win32_incompat(input, repl='-', replacements=replacments)
self.assertEqual('fooA-C----', replaced)
def test_empty_string_replacement_map(self):
input = 'foo:bar'
replacments = {
':': '',
}
replaced = util.replace_win32_incompat(input, replacements=replacments)
self.assertEqual('foobar', replaced)
class MakeFilenameTest(PicardTestCase):
def test_filename_from_title(self):
self.assertEqual(make_filename_from_title(), _("No Title"))
self.assertEqual(make_filename_from_title(""), _("No Title"))
self.assertEqual(make_filename_from_title(" "), _("No Title"))
self.assertEqual(make_filename_from_title(default="New Default"), "New Default")
self.assertEqual(make_filename_from_title("", "New Default"), "New Default")
self.assertEqual(make_filename_from_title("/"), "_")
@unittest.skipUnless(IS_WIN, "windows test")
def test_filename_from_title_win32(self):
self.assertEqual(make_filename_from_title("\\"), "_")
self.assertEqual(make_filename_from_title(":"), "_")
@unittest.skipUnless(not IS_WIN, "non-windows test")
def test_filename_from_title_non_win32(self):
self.assertEqual(make_filename_from_title(":"), ":")
class ExtractYearTest(PicardTestCase):
def test_string(self):
self.assertEqual(extract_year_from_date(""), None)
self.assertEqual(extract_year_from_date(2020), None)
self.assertEqual(extract_year_from_date("2020"), 2020)
self.assertEqual(extract_year_from_date('2020-02-28'), 2020)
self.assertEqual(extract_year_from_date('2015.02'), 2015)
self.assertEqual(extract_year_from_date('2015; 2015'), None)
# test for the format as supported by ID3 (https://id3.org/id3v2.4.0-structure): yyyy-MM-ddTHH:mm:ss
self.assertEqual(extract_year_from_date('2020-07-21T13:00:00'), 2020)
def test_mapping(self):
self.assertEqual(extract_year_from_date({}), None)
self.assertEqual(extract_year_from_date({'year': 'abc'}), None)
self.assertEqual(extract_year_from_date({'year': '2020'}), 2020)
self.assertEqual(extract_year_from_date({'year': 2020}), 2020)
self.assertEqual(extract_year_from_date({'year': '2020-02-28'}), None)
class SanitizeDateTest(PicardTestCase):
def test_correct(self):
self.assertEqual(util.sanitize_date(""), "")
self.assertEqual(util.sanitize_date("0"), "")
self.assertEqual(util.sanitize_date("0000"), "")
self.assertEqual(util.sanitize_date("2006"), "2006")
self.assertEqual(util.sanitize_date("2006--"), "2006")
self.assertEqual(util.sanitize_date("2006-00-02"), "2006-00-02")
self.assertEqual(util.sanitize_date("2006 "), "2006")
self.assertEqual(util.sanitize_date("2006 02"), "")
self.assertEqual(util.sanitize_date("2006.02"), "")
self.assertEqual(util.sanitize_date("2006-02"), "2006-02")
self.assertEqual(util.sanitize_date("2006-02-00"), "2006-02")
self.assertEqual(util.sanitize_date("2006-00-00"), "2006")
self.assertEqual(util.sanitize_date("2006-02-23"), "2006-02-23")
self.assertEqual(util.sanitize_date("2006-00-23"), "2006-00-23")
self.assertEqual(util.sanitize_date("0000-00-23"), "0000-00-23")
self.assertEqual(util.sanitize_date("0000-02"), "0000-02")
self.assertEqual(util.sanitize_date("--23"), "0000-00-23")
def test_incorrect(self):
self.assertNotEqual(util.sanitize_date("2006--02"), "2006")
self.assertNotEqual(util.sanitize_date("2006.03.02"), "2006-03-02")
class SanitizeFilenameTest(PicardTestCase):
def test_replace_slashes(self):
self.assertEqual(util.sanitize_filename("AC/DC"), "AC_DC")
def test_custom_replacement(self):
self.assertEqual(util.sanitize_filename("AC/DC", "|"), "AC|DC")
def test_win_compat(self):
self.assertEqual(util.sanitize_filename("AC\\/DC", win_compat=True), "AC__DC")
@unittest.skipUnless(IS_WIN, "windows test")
def test_replace_backslashes(self):
self.assertEqual(util.sanitize_filename("AC\\DC"), "AC_DC")
@unittest.skipIf(IS_WIN, "non-windows test")
def test_keep_backslashes(self):
self.assertEqual(util.sanitize_filename("AC\\DC"), "AC\\DC")
class TranslateArtistTest(PicardTestCase):
def test_latin(self):
self.assertEqual("thename", util.translate_from_sortname("thename", "sort, name"))
def test_kanji(self):
self.assertEqual("Tetsuya Komuro", util.translate_from_sortname("小室哲哉", "Komuro, Tetsuya"))
# see _reverse_sortname(), cases with 3 or 4 chunks
self.assertEqual("c b a", util.translate_from_sortname("小室哲哉", "a, b, c"))
self.assertEqual("b a, d c", util.translate_from_sortname("小室哲哉", "a, b, c, d"))
def test_kanji2(self):
self.assertEqual("Ayumi Hamasaki & Keiko", util.translate_from_sortname("浜崎あゆみ & KEIKO", "Hamasaki, Ayumi & Keiko"))
def test_cyrillic(self):
self.assertEqual("Pyotr Ilyich Tchaikovsky", util.translate_from_sortname("Пётр Ильич Чайковский", "Tchaikovsky, Pyotr Ilyich"))
class FormatTimeTest(PicardTestCase):
def test(self):
self.assertEqual("?:??", util.format_time(0))
self.assertEqual("0:00", util.format_time(0, display_zero=True))
self.assertEqual("3:00", util.format_time(179750))
self.assertEqual("3:00", util.format_time(179500))
self.assertEqual("2:59", util.format_time(179499))
self.assertEqual("59:59", util.format_time(3599499))
self.assertEqual("1:00:00", util.format_time(3599500))
self.assertEqual("1:02:59", util.format_time(3779499))
class HiddenFileTest(PicardTestCase):
@unittest.skipUnless(not IS_WIN, "non-windows test")
def test(self):
self.assertTrue(util.is_hidden('/a/b/.c.mp3'))
self.assertTrue(util.is_hidden('/a/.b/.c.mp3'))
self.assertFalse(util.is_hidden('/a/.b/c.mp3'))
@unittest.skipUnless(IS_WIN, "windows test")
def test_windows(self):
from ctypes import windll
with NamedTemporaryFile() as f:
self.assertFalse(util.is_hidden(f.name), "%s expected not to be hidden" % f.name)
windll.kernel32.SetFileAttributesW(f.name, 2)
self.assertTrue(util.is_hidden(f.name), "%s expected to be hidden" % f.name)
@unittest.skipUnless(IS_MACOS, "macOS test")
def test_macos(self):
with NamedTemporaryFile() as f:
self.assertFalse(util.is_hidden(f.name), "%s expected not to be hidden" % f.name)
subprocess.run(('SetFile', '-a', 'V', f.name)) # nosec: B603
self.assertTrue(util.is_hidden(f.name), "%s expected to be hidden" % f.name)
class TagsTest(PicardTestCase):
def test_display_tag_name(self):
dtn = util.tags.display_tag_name
self.assertEqual(dtn('tag'), 'tag')
self.assertEqual(dtn('tag:desc'), 'tag [desc]')
self.assertEqual(dtn('tag:'), 'tag')
self.assertEqual(dtn('tag:de:sc'), 'tag [de:sc]')
self.assertEqual(dtn('originalyear'), 'Original Year')
self.assertEqual(dtn('originalyear:desc'), 'Original Year [desc]')
self.assertEqual(dtn('~length'), 'Length')
self.assertEqual(dtn('~lengthx'), '~lengthx')
self.assertEqual(dtn(''), '')
class LinearCombinationTest(PicardTestCase):
def test_0(self):
parts = []
self.assertEqual(util.linear_combination_of_weights(parts), 0.0)
def test_1(self):
parts = [(1.0, 1), (1.0, 1), (1.0, 1)]
self.assertEqual(util.linear_combination_of_weights(parts), 1.0)
def test_2(self):
parts = [(0.0, 1), (0.0, 0), (1.0, 0)]
self.assertEqual(util.linear_combination_of_weights(parts), 0.0)
def test_3(self):
parts = [(0.0, 1), (1.0, 1)]
self.assertEqual(util.linear_combination_of_weights(parts), 0.5)
def test_4(self):
parts = [(0.5, 4), (1.0, 1)]
self.assertEqual(util.linear_combination_of_weights(parts), 0.6)
def test_5(self):
parts = [(0.95, 100), (0.05, 399), (0.0, 1), (1.0, 0)]
self.assertEqual(util.linear_combination_of_weights(parts), 0.2299)
def test_6(self):
parts = [(-0.5, 4)]
self.assertRaises(ValueError, util.linear_combination_of_weights, parts)
def test_7(self):
parts = [(0.5, -4)]
self.assertRaises(ValueError, util.linear_combination_of_weights, parts)
def test_8(self):
parts = [(1.5, 4)]
self.assertRaises(ValueError, util.linear_combination_of_weights, parts)
def test_9(self):
parts = ((1.5, 4))
self.assertRaises(TypeError, util.linear_combination_of_weights, parts)
class AlbumArtistFromPathTest(PicardTestCase):
def test_album_artist_from_path(self):
aafp = album_artist_from_path
file_1 = r"/10cc/Original Soundtrack/02 I'm Not in Love.mp3"
file_2 = r"/10cc - Original Soundtrack/02 I'm Not in Love.mp3"
file_3 = r"/Original Soundtrack/02 I'm Not in Love.mp3"
file_4 = r"/02 I'm Not in Love.mp3"
file_5 = r"/10cc - Original Soundtrack - bonus/02 I'm Not in Love.mp3"
self.assertEqual(aafp(file_1, '', ''), ('Original Soundtrack', '10cc'))
self.assertEqual(aafp(file_2, '', ''), ('Original Soundtrack', '10cc'))
self.assertEqual(aafp(file_3, '', ''), ('Original Soundtrack', ''))
self.assertEqual(aafp(file_4, '', ''), ('', ''))
self.assertEqual(aafp(file_5, '', ''), ('Original Soundtrack - bonus', '10cc'))
self.assertEqual(aafp(file_1, 'album', ''), ('album', ''))
self.assertEqual(aafp(file_2, 'album', ''), ('album', ''))
self.assertEqual(aafp(file_3, 'album', ''), ('album', ''))
self.assertEqual(aafp(file_4, 'album', ''), ('album', ''))
self.assertEqual(aafp(file_1, '', 'artist'), ('Original Soundtrack', 'artist'))
self.assertEqual(aafp(file_2, '', 'artist'), ('Original Soundtrack', 'artist'))
self.assertEqual(aafp(file_3, '', 'artist'), ('Original Soundtrack', 'artist'))
self.assertEqual(aafp(file_4, '', 'artist'), ('', 'artist'))
self.assertEqual(aafp(file_1, 'album', 'artist'), ('album', 'artist'))
self.assertEqual(aafp(file_2, 'album', 'artist'), ('album', 'artist'))
self.assertEqual(aafp(file_3, 'album', 'artist'), ('album', 'artist'))
self.assertEqual(aafp(file_4, 'album', 'artist'), ('album', 'artist'))
def test_path_no_dirs(self):
for name in ('', 'x', '/', '\\', '///'):
self.assertEqual(('', 'artist'), album_artist_from_path(name, '', 'artist'))
def test_strip_disc_dir(self):
self.assertEqual(
('albumy', 'artistx'),
album_artist_from_path(r'/artistx/albumy/CD 1/file.flac', '', ''))
self.assertEqual(
('albumy', 'artistx'),
album_artist_from_path(r'/artistx/albumy/the DVD 23 B/file.flac', '', ''))
self.assertEqual(
('albumy', 'artistx'),
album_artist_from_path(r'/artistx/albumy/disc23/file.flac', '', ''))
self.assertNotEqual(
('albumy', 'artistx'),
album_artist_from_path(r'/artistx/albumy/disc/file.flac', '', ''))
@unittest.skipUnless(IS_WIN, "windows test")
def test_remove_windows_drive(self):
self.assertEqual(
('album1', None),
album_artist_from_path(r'C:\album1\foo.mp3', None, None))
self.assertEqual(
('album1', None),
album_artist_from_path(r'\\myserver\myshare\album1\foo.mp3', None, None))
class IsAbsolutePathTest(PicardTestCase):
def test_is_absolute(self):
self.assertTrue(is_absolute_path('/foo/bar'))
self.assertFalse(is_absolute_path('foo/bar'))
self.assertFalse(is_absolute_path('./foo/bar'))
self.assertFalse(is_absolute_path('../foo/bar'))
@unittest.skipUnless(IS_WIN, "windows test")
def test_is_absolute_windows(self):
self.assertTrue(is_absolute_path('D:/foo/bar'))
self.assertTrue(is_absolute_path('D:\\foo\\bar'))
self.assertTrue(is_absolute_path('\\foo\\bar'))
# Paths to Windows shares
self.assertTrue(is_absolute_path('\\\\foo\\bar'))
self.assertTrue(is_absolute_path('\\\\foo\\bar\\'))
self.assertTrue(is_absolute_path('\\\\foo\\bar\\baz'))
class CompareBarcodesTest(PicardTestCase):
def test_same(self):
self.assertTrue(util.compare_barcodes('0727361379704', '0727361379704'))
self.assertTrue(util.compare_barcodes('727361379704', '727361379704'))
self.assertTrue(util.compare_barcodes('727361379704', '0727361379704'))
self.assertTrue(util.compare_barcodes('0727361379704', '727361379704'))
self.assertTrue(util.compare_barcodes(None, None))
self.assertTrue(util.compare_barcodes('', ''))
self.assertTrue(util.compare_barcodes(None, ''))
self.assertTrue(util.compare_barcodes('', None))
def test_not_same(self):
self.assertFalse(util.compare_barcodes('0727361379704', '0727361379705'))
self.assertFalse(util.compare_barcodes('727361379704', '1727361379704'))
self.assertFalse(util.compare_barcodes('0727361379704', None))
self.assertFalse(util.compare_barcodes(None, '0727361379704'))
class MbidValidateTest(PicardTestCase):
def test_ok(self):
self.assertTrue(util.mbid_validate('2944824d-4c26-476f-a981-be849081942f'))
self.assertTrue(util.mbid_validate('2944824D-4C26-476F-A981-be849081942f'))
self.assertFalse(util.mbid_validate(''))
self.assertFalse(util.mbid_validate('Z944824d-4c26-476f-a981-be849081942f'))
self.assertFalse(util.mbid_validate('22944824d-4c26-476f-a981-be849081942f'))
self.assertFalse(util.mbid_validate('2944824d-4c26-476f-a981-be849081942ff'))
self.assertFalse(util.mbid_validate('2944824d-4c26.476f-a981-be849081942f'))
def test_not_ok(self):
self.assertRaises(TypeError, util.mbid_validate, 123)
self.assertRaises(TypeError, util.mbid_validate, None)
SimMatchTest = namedtuple('SimMatchTest', 'similarity name')
class SortBySimilarity(PicardTestCase):
def setUp(self):
super().setUp()
self.test_values = [
SimMatchTest(similarity=0.74, name='d'),
SimMatchTest(similarity=0.61, name='a'),
SimMatchTest(similarity=0.75, name='b'),
SimMatchTest(similarity=0.75, name='c'),
]
def test_sort_by_similarity(self):
results = [result.name for result in sort_by_similarity(self.test_values)]
self.assertEqual(results, ['b', 'c', 'd', 'a'])
def test_findbestmatch(self):
no_match = SimMatchTest(similarity=-1, name='no_match')
best_match = find_best_match(self.test_values, no_match)
self.assertEqual(best_match.result.name, 'b')
self.assertEqual(best_match.similarity, 0.75)
def test_findbestmatch_nomatch(self):
self.test_values = []
no_match = SimMatchTest(similarity=-1, name='no_match')
best_match = find_best_match(self.test_values, no_match)
self.assertEqual(best_match.result.name, 'no_match')
self.assertEqual(best_match.similarity, -1)
class LimitedJoin(PicardTestCase):
def setUp(self):
super().setUp()
self.list = [str(x) for x in range(0, 10)]
def test_1(self):
expected = '0+1+...+8+9'
result = limited_join(self.list, 5, '+', '...')
self.assertEqual(result, expected)
def test_2(self):
expected = '0+1+2+3+4+5+6+7+8+9'
result = limited_join(self.list, -1)
self.assertEqual(result, expected)
result = limited_join(self.list, len(self.list))
self.assertEqual(result, expected)
result = limited_join(self.list, len(self.list) + 1)
self.assertEqual(result, expected)
def test_3(self):
expected = '0,1,2,3,…,6,7,8,9'
result = limited_join(self.list, len(self.list) - 1, ',')
self.assertEqual(result, expected)
class IterFilesFromObjectsTest(PicardTestCase):
def test_iterate_only_unique(self):
f1 = Mock()
f2 = Mock()
f3 = Mock()
obj1 = Mock()
obj1.iterfiles = Mock(return_value=[f1, f2])
obj2 = Mock()
obj2.iterfiles = Mock(return_value=[f2, f3])
result = iter_files_from_objects([obj1, obj2])
self.assertTrue(isinstance(result, Iterator))
self.assertEqual([f1, f2, f3], list(result))
class IterUniqifyTest(PicardTestCase):
def test_unique(self):
items = [1, 2, 3, 2, 3, 4]
result = uniqify(items)
self.assertEqual([1, 2, 3, 4], result)
class IterUniqueTest(PicardTestCase):
def test_unique(self):
items = [1, 2, 3, 2, 3, 4]
result = iter_unique(items)
self.assertTrue(isinstance(result, Iterator))
self.assertEqual([1, 2, 3, 4], list(result))
class TracknumFromFilenameTest(PicardTestCase):
def test_returns_expected_tracknumber(self):
tests = (
(2, '2.mp3'),
(2, '02.mp3'),
(2, '002.mp3'),
(None, 'Foo.mp3'),
(1, 'Foo 0001.mp3'),
(1, '1 song.mp3'),
(99, '99 Foo.mp3'),
(42, '42. Foo.mp3'),
(None, '20000 Feet.mp3'),
(242, 'track no 242.mp3'),
(77, 'Track no. 77 .mp3'),
(242, 'track-242.mp3'),
(242, 'track nr 242.mp3'),
(242, 'track_242.mp3'),
(3, 'track003.mp3'),
(40, 'Track40.mp3'),
(None, 'UB40.mp3'),
(1, 'artist song 2004 track01 xxxx.ogg'),
(1, 'artist song 2004 track-no-01 xxxx.ogg'),
(1, 'artist song 2004 track-no_01 xxxx.ogg'),
(1, '01_foo.mp3'),
(1, '01ābc.mp3'),
(1, '01abc.mp3'),
(11, "11 Linda Jones - Things I've Been Through 08.flac"),
(1, "01 artist song [2004] (02).mp3"),
(1, "01 artist song [04].mp3"),
(7, "artist song [2004] [7].mp3"),
# (7, "artist song [2004] (7).mp3"),
(7, 'artist song [2004] [07].mp3'),
(7, 'artist song [2004] (07).mp3'),
(4, 'xx 01 artist song [04].mp3'),
(None, 'artist song-(666) (01) xxx.ogg'),
(None, 'song-70s 69 comment.mp3'),
(13, "2_13 foo.mp3"),
(13, "02-13 foo.mp3"),
(None, '1971.mp3'),
(42, '1971 Track 42.mp3'),
(None, "artist song [2004].mp3"),
(None, '0.mp3'),
(None, 'track00.mp3'),
(None, 'song [2004] [1000].mp3'),
(None, 'song 2015.mp3'),
(None, '2015 song.mp3'),
(None, '30,000 Pounds of Bananas.mp3'),
(None, 'Dalas 1 PM.mp3'),
(None, "Don't Stop the 80's.mp3"),
(None, 'Symphony no. 5 in D minor.mp3'),
(None, 'Song 2.mp3'),
(None, '80s best of.mp3'),
(None, 'best of 80s.mp3'),
# (None, '99 Luftballons.mp3'),
(7, '99 Luftballons Track 7.mp3'),
(None, 'Margin 0.001.mp3'),
(None, 'All the Small Things - blink‐182.mp3'),
(None, '99.99 Foo.mp3'),
(5, '٠٥ فاصله میان دو پرده.mp3'),
(23, '23 foo.mp3'),
(None, '²³ foo.mp3'),
)
for expected, filename in tests:
tracknumber = tracknum_from_filename(filename)
self.assertEqual(expected, tracknumber, filename)
class TracknumAndTitleFromFilenameTest(PicardTestCase):
def test_returns_expected_tracknumber(self):
tests = (
((None, 'Foo'), 'Foo.mp3'),
(('1', 'Track 0001'), 'Track 0001.mp3'),
(('42', 'Track-42'), 'Track-42.mp3'),
(('99', 'Foo'), '99 Foo.mp3'),
(('42', 'Foo'), '0000042 Foo.mp3'),
(('2', 'Foo'), '0000002 Foo.mp3'),
((None, '20000 Feet'), '20000 Feet.mp3'),
((None, '20,000 Feet'), '20,000 Feet.mp3'),
((None, 'Venus (Original 12" version)'), 'Venus (Original 12" version).mp3'),
((None, 'Vanity 6'), 'Vanity 6.mp3'),
((None, 'UB40 - Red Red Wine'), 'UB40 - Red Red Wine.mp3'),
((None, 'Red Red Wine - UB40'), 'Red Red Wine - UB40.mp3'),
((None, 'Symphony no. 5 in D minor'), 'Symphony no. 5 in D minor.mp3'),
)
for expected, filename in tests:
result = tracknum_and_title_from_filename(filename)
self.assertEqual(expected, result)
def test_namedtuple(self):
result = tracknum_and_title_from_filename('0000002 Foo.mp3')
self.assertEqual(result.tracknumber, '2')
self.assertEqual(result.title, 'Foo')
class PatternAsRegexTest(PicardTestCase):
def test_regex(self):
regex = pattern_as_regex(r'/^foo.*/')
self.assertEqual(r'^foo.*', regex.pattern)
self.assertFalse(regex.flags & re.IGNORECASE)
self.assertFalse(regex.flags & re.MULTILINE)
def test_regex_flags(self):
regex = pattern_as_regex(r'/^foo.*/', flags=re.MULTILINE | re.IGNORECASE)
self.assertEqual(r'^foo.*', regex.pattern)
self.assertTrue(regex.flags & re.IGNORECASE)
self.assertTrue(regex.flags & re.MULTILINE)
def test_regex_extra_flags(self):
regex = pattern_as_regex(r'/^foo.*/im', flags=re.VERBOSE)
self.assertEqual(r'^foo.*', regex.pattern)
self.assertTrue(regex.flags & re.VERBOSE)
self.assertTrue(regex.flags & re.IGNORECASE)
self.assertTrue(regex.flags & re.MULTILINE)
def test_regex_raises(self):
with self.assertRaises(re.error):
pattern_as_regex(r'/^foo(.*/')
def test_wildcard(self):
regex = pattern_as_regex(r'(foo?)\\*\?\*', allow_wildcards=True)
self.assertEqual(r'^\(foo.\)\\.*\?\*$', regex.pattern)
self.assertFalse(regex.flags & re.IGNORECASE)
self.assertFalse(regex.flags & re.MULTILINE)
def test_wildcard_flags(self):
regex = pattern_as_regex(r'(foo)*', allow_wildcards=True, flags=re.MULTILINE | re.IGNORECASE)
self.assertEqual(r'^\(foo\).*$', regex.pattern)
self.assertTrue(regex.flags & re.IGNORECASE)
self.assertTrue(regex.flags & re.MULTILINE)
def test_string_match(self):
regex = pattern_as_regex(r'(foo)*', allow_wildcards=False)
self.assertEqual(r'\(foo\)\*', regex.pattern)
self.assertFalse(regex.flags & re.IGNORECASE)
self.assertFalse(regex.flags & re.MULTILINE)
def test_string_match_flags(self):
regex = pattern_as_regex(r'(foo)*', allow_wildcards=False, flags=re.MULTILINE | re.IGNORECASE)
self.assertEqual(r'\(foo\)\*', regex.pattern)
self.assertTrue(regex.flags & re.IGNORECASE)
self.assertTrue(regex.flags & re.MULTILINE)
class WildcardsToRegexPatternTest(PicardTestCase):
def test_wildcard_pattern(self):
pattern = 'fo?o*'
regex = wildcards_to_regex_pattern(pattern)
self.assertEqual('fo.o.*', regex)
re.compile(regex)
def test_escape(self):
pattern = 'f\\?o\\*o?o*\\[o'
regex = wildcards_to_regex_pattern(pattern)
self.assertEqual('f\\?o\\*o.o.*\\[o', regex)
re.compile(regex)
def test_character_group(self):
pattern = '[abc*?xyz]]'
regex = wildcards_to_regex_pattern(pattern)
self.assertEqual('[abc*?xyz]\\]', regex)
re.compile(regex)
def test_character_group_escape_square_brackets(self):
pattern = '[a[b\\]c]'
regex = wildcards_to_regex_pattern(pattern)
self.assertEqual('[a[b\\]c]', regex)
re.compile(regex)
def test_open_character_group(self):
pattern = '[abc*?xyz['
regex = wildcards_to_regex_pattern(pattern)
self.assertEqual('\\[abc.*.xyz\\[', regex)
re.compile(regex)
def test_special_chars(self):
pattern = ']()\\^$|'
regex = wildcards_to_regex_pattern(pattern)
self.assertEqual(re.escape(pattern), regex)
re.compile(regex)
class BuildQUrlTest(PicardTestCase):
def test_path_and_querystring(self):
query = {'foo': 'x', 'bar': 'y'}
self.assertEqual('http://example.com/', build_qurl('example.com', path='/').toDisplayString())
self.assertEqual('http://example.com/foo/bar', build_qurl('example.com', path='/foo/bar').toDisplayString())
self.assertEqual('http://example.com/foo/bar?foo=x&bar=y', build_qurl('example.com', path='/foo/bar', queryargs=query).toDisplayString())
self.assertEqual('http://example.com?foo=x&bar=y', build_qurl('example.com', queryargs=query).toDisplayString())
def test_standard_ports(self):
self.assertEqual('http://example.com', build_qurl('example.com').toDisplayString())
self.assertEqual('http://example.com', build_qurl('example.com', port=80).toDisplayString())
self.assertEqual('https://example.com', build_qurl('example.com', port=443).toDisplayString())
def test_custom_port(self):
self.assertEqual('http://example.com:8080', build_qurl('example.com', port=8080).toDisplayString())
self.assertEqual('http://example.com:8080/', build_qurl('example.com', port=8080, path="/").toDisplayString())
self.assertEqual('http://example.com:8080?foo=x', build_qurl('example.com', port=8080, queryargs={'foo': 'x'}).toDisplayString())
def test_mb_server(self):
for host in MUSICBRAINZ_SERVERS:
expected = 'https://' + host
self.assertEqual(expected, build_qurl(host, port=80).toDisplayString())
self.assertEqual(expected, build_qurl(host, port=443).toDisplayString())
self.assertEqual(expected, build_qurl(host, port=8080).toDisplayString())
def test_encoded_queryargs(self):
query = encoded_queryargs({'foo': ' %20&;', 'bar': '=%+?abc'})
self.assertEqual('%20%2520%26%3B', query['foo'])
self.assertEqual('%3D%25%2B%3Fabc', query['bar'])
# spaces are decoded in displayed string
expected = 'http://example.com?foo= %2520%26%3B&bar=%3D%25%2B%3Fabc'
result = build_qurl('example.com', queryargs=query).toDisplayString()
self.assertEqual(expected, result)
class NormpathTest(PicardTestCase):
@unittest.skipIf(IS_WIN, "non-windows test")
def test_normpath(self):
self.assertEqual('/foo/bar', normpath('/foo//bar'))
self.assertEqual('/bar', normpath('/foo/../bar'))
@unittest.skipUnless(IS_WIN, "windows test")
def test_normpath_windows(self):
self.assertEqual(r'C:\Foo\Bar.baz', normpath('C:/Foo/Bar.baz'))
self.assertEqual(r'C:\Bar.baz', normpath('C:/Foo/../Bar.baz'))
@unittest.skipUnless(IS_WIN, "windows test")
@patch.object(util, 'system_supports_long_paths')
def test_normpath_windows_longpath(self, mock_system_supports_long_paths):
mock_system_supports_long_paths.return_value = False
path = rf'C:\foo\{252 * "a"}'
self.assertEqual(path, normpath(path))
path += 'a'
self.assertEqual(rf'\\?\{path}', normpath(path))
class WinPrefixLongpathTest(PicardTestCase):
def test_win_prefix_longpath_is_long(self):
path = rf'C:\foo\{253 * "a"}'
self.assertEqual(rf'\\?\{path}', win_prefix_longpath(path))
def test_win_prefix_longpath_is_short(self):
path = rf'C:\foo\{252 * "a"}'
self.assertEqual(path, win_prefix_longpath(path))
def test_win_prefix_longpath_unc(self):
path = rf'\\server\{251 * "a"}'
self.assertEqual(rf'\\?\UNC{path[1:]}', win_prefix_longpath(path))
def test_win_prefix_longpath_already_prefixed(self):
path = r'\\?\C:\foo'
self.assertEqual(path, win_prefix_longpath(path))
def test_win_prefix_longpath_already_prefixed_unc(self):
path = r'\\?\server\someshare'
self.assertEqual(path, win_prefix_longpath(path))
class SystemSupportsLongPathsTest(PicardTestCase):
def setUp(self):
super().setUp()
try:
del system_supports_long_paths._supported
except AttributeError:
pass
def test_system_supports_long_paths_returns_bool(self):
result = system_supports_long_paths()
self.assertTrue(isinstance(result, bool))
@unittest.skipIf(IS_WIN, "non-windows test")
def test_system_supports_long_paths(self):
self.assertTrue(system_supports_long_paths())
@unittest.skipUnless(IS_WIN, "windows test")
@patch('winreg.OpenKey')
@patch('winreg.QueryValueEx')
def test_system_supports_long_paths_windows_unsupported(self, mock_query_value, mock_open_key):
mock_query_value.return_value = [0]
self.assertFalse(system_supports_long_paths())
mock_open_key.assert_called_once()
mock_query_value.assert_called_once()
@unittest.skipUnless(IS_WIN, "windows test")
@patch('winreg.OpenKey')
@patch('winreg.QueryValueEx')
def test_system_supports_long_paths_windows_supported(self, mock_query_value, mock_open_key):
mock_query_value.return_value = [1]
self.assertTrue(system_supports_long_paths())
mock_open_key.assert_called_once()
mock_query_value.assert_called_once()
@unittest.skipUnless(IS_WIN, "windows test")
@patch('winreg.OpenKey')
@patch('winreg.QueryValueEx')
def test_system_supports_long_paths_cache(self, mock_query_value, mock_open_key):
mock_query_value.return_value = [1]
self.assertTrue(system_supports_long_paths())
self.assertTrue(system_supports_long_paths._supported)
mock_query_value.return_value = [0]
self.assertTrue(system_supports_long_paths())
mock_open_key.assert_called_once()
mock_query_value.assert_called_once()
class IterExceptionChainTest(PicardTestCase):
def test_iter_exception_chain(self):
e1 = Mock(name='e1')
e2 = Mock(name='e2')
e3 = Mock(name='e3')
e4 = Mock(name='e4')
e5 = Mock(name='e5')
e1.__context__ = e2
e2.__context__ = e3
e2.__cause__ = e4
e1.__cause__ = e5
self.assertEqual([e1, e2, e3, e4, e5], list(iter_exception_chain(e1)))
class AnyExceptionIsinstanceTest(PicardTestCase):
def test_any_exception_isinstance_itself(self):
ex = RuntimeError()
self.assertTrue(any_exception_isinstance(ex, RuntimeError))
def test_any_exception_isinstance_context(self):
ex = Mock()
self.assertFalse(any_exception_isinstance(ex, RuntimeError))
ex.__context__ = RuntimeError()
self.assertTrue(any_exception_isinstance(ex, RuntimeError))
def test_any_exception_isinstance_cause(self):
ex = Mock()
self.assertFalse(any_exception_isinstance(ex, RuntimeError))
ex.__cause__ = RuntimeError()
self.assertTrue(any_exception_isinstance(ex, RuntimeError))
def test_any_exception_isinstance_nested(self):
ex = Mock()
self.assertFalse(any_exception_isinstance(ex, RuntimeError))
ex.__cause__ = Mock()
ex.__cause__.__context__ = RuntimeError()
self.assertTrue(any_exception_isinstance(ex, RuntimeError))
class IgnoreUpdatesContextTest(PicardTestCase):
def test_enter_exit(self):
context = IgnoreUpdatesContext()
self.assertFalse(context)
with context:
self.assertTrue(context)
self.assertFalse(context)
def test_run_on_exit(self):
on_exit = Mock()
context = IgnoreUpdatesContext(on_exit=on_exit)
with context:
on_exit.assert_not_called()
on_exit.assert_called_once_with()
def test_run_on_exit_nested(self):
on_exit = Mock()
context = IgnoreUpdatesContext(on_exit=on_exit)
with context:
with context:
on_exit.assert_not_called()
self.assertEqual(len(on_exit.mock_calls), 1)
self.assertEqual(len(on_exit.mock_calls), 2)
def test_run_on_last_exit(self):
on_last_exit = Mock()
context = IgnoreUpdatesContext(on_last_exit=on_last_exit)
with context:
on_last_exit.assert_not_called()
on_last_exit.assert_called_once_with()
def test_run_on_last_exit_nested(self):
on_last_exit = Mock()
context = IgnoreUpdatesContext(on_last_exit=on_last_exit)
with context:
with context:
on_last_exit.assert_not_called()
on_last_exit.assert_not_called()
on_last_exit.assert_called_once_with()
def test_run_on_enter(self):
on_enter = Mock()
context = IgnoreUpdatesContext(on_enter=on_enter)
with context:
on_enter.assert_called()
on_enter.assert_called_once_with()
def test_run_on_enter_nested(self):
on_enter = Mock()
context = IgnoreUpdatesContext(on_enter=on_enter)
with context:
self.assertEqual(len(on_enter.mock_calls), 1)
with context:
self.assertEqual(len(on_enter.mock_calls), 2)
def test_run_on_first_enter(self):
on_first_enter = Mock()
context = IgnoreUpdatesContext(on_first_enter=on_first_enter)
with context:
on_first_enter.assert_called()
on_first_enter.assert_called_once_with()
def test_run_on_first_enter_nested(self):
on_first_enter = Mock()
context = IgnoreUpdatesContext(on_first_enter=on_first_enter)
with context:
on_first_enter.assert_called_once_with()
with context:
on_first_enter.assert_called_once_with()
def test_nested_with(self):
context = IgnoreUpdatesContext()
with context:
with context:
self.assertTrue(context)
self.assertTrue(context)
self.assertFalse(context)
class DetectUnicodeEncodingTest(PicardTestCase):
@unittest.skipUnless(charset_detect, "test requires charset_normalizer or chardet package")
def test_detect_file_encoding_bom(self):
boms = {
b'\xff\xfe': 'utf-16-le',
b'\xfe\xff': 'utf-16-be',
b'\xff\xfe\x00\x00': 'utf-32-le',
b'\x00\x00\xfe\xff': 'utf-32-be',
b'\xef\xbb\xbf': 'utf-8-sig',
b'': 'utf-8',
b'\00': 'utf-8',
b'no BOM, only ASCII': 'utf-8',
}
for bom, expected_encoding in boms.items():
try:
f = NamedTemporaryFile(delete=False)
f.write(bom)
f.close()
encoding = detect_file_encoding(f.name)
self.assertEqual(expected_encoding, encoding,
f'BOM {bom!r} detected as {encoding}, expected {expected_encoding}')
finally:
f.close()
os.remove(f.name)
def test_detect_file_encoding_eac_utf_16_le(self):
expected_encoding = 'utf-16-le'
file_path = get_test_data_path('eac-utf16le.log')
self.assertEqual(expected_encoding, detect_file_encoding(file_path))
def test_detect_file_encoding_eac_utf_32_le(self):
expected_encoding = 'utf-32-le'
file_path = get_test_data_path('eac-utf32le.log')
self.assertEqual(expected_encoding, detect_file_encoding(file_path))
@unittest.skipUnless(charset_detect, "test requires charset_normalizer or chardet package")
def test_detect_file_encoding_eac_windows_1251(self):
expected_encoding = 'windows-1251'
file_path = get_test_data_path('eac-windows1251.log')
self.assertEqual(expected_encoding, detect_file_encoding(file_path))
| 40,262
|
Python
|
.py
| 837
| 39.352449
| 145
| 0.625565
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,857
|
test_oauth.py
|
metabrainz_picard/test/test_oauth.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 Laurent Monin
# Copyright (C) 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.oauth import (
OAuthManager,
base64url_encode,
s256_encode,
)
class OAuthManagerTest(PicardTestCase):
def test_query_data(self):
params = {
'a&b': 'a b',
'c d': 'c&d',
'e=f': 'e=f',
'': '',
}
data = OAuthManager._query_data(params)
self.assertEqual(data, "a%26b=a+b&c+d=c%26d&e%3Df=e%3Df")
def test_s256_encode(self):
code_verifier = b'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
code_challenge = s256_encode(code_verifier)
self.assertEqual(b'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', code_challenge)
def test_base64url_encode(self):
b = bytes([116, 24, 223, 180, 151, 153, 224, 37, 79, 250, 96, 125, 216, 173,
187, 186, 22, 212, 37, 77, 105, 214, 191, 240, 91, 88, 5, 88, 83,
132, 141, 121])
encoded = base64url_encode(b)
self.assertEqual(b'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk', encoded)
| 1,900
|
Python
|
.py
| 46
| 36.304348
| 88
| 0.689057
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,858
|
test_item.py
|
metabrainz_picard/test/test_item.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018, 2021 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from unittest.mock import Mock
from test.picardtestcase import PicardTestCase
from picard import config
from picard.item import MetadataItem
class MetadataItemTest(PicardTestCase):
def setUp(self):
super().setUp()
self.obj = MetadataItem('id')
def test_set_genre_inc_params_no_genres(self):
inc = set()
config.setting['use_genres'] = False
require_auth = self.obj.set_genre_inc_params(inc)
self.assertEqual(set(), inc)
self.assertFalse(require_auth)
def test_set_genre_inc_params_with_genres(self):
inc = set()
config.setting['use_genres'] = True
config.setting['folksonomy_tags'] = False
config.setting['only_my_genres'] = False
require_auth = self.obj.set_genre_inc_params(inc)
self.assertIn('genres', inc)
self.assertFalse(require_auth)
def test_set_genre_inc_params_with_user_genres(self):
inc = set()
config.setting['use_genres'] = True
config.setting['folksonomy_tags'] = False
config.setting['only_my_genres'] = True
require_auth = self.obj.set_genre_inc_params(inc)
self.assertIn('user-genres', inc)
self.assertTrue(require_auth)
def test_set_genre_inc_params_with_tags(self):
inc = set()
config.setting['use_genres'] = True
config.setting['folksonomy_tags'] = True
config.setting['only_my_genres'] = False
require_auth = self.obj.set_genre_inc_params(inc)
self.assertIn('tags', inc)
self.assertFalse(require_auth)
def test_set_genre_inc_params_with_user_tags(self):
inc = set()
config.setting['use_genres'] = True
config.setting['folksonomy_tags'] = True
config.setting['only_my_genres'] = True
require_auth = self.obj.set_genre_inc_params(inc)
self.assertIn('user-tags', inc)
self.assertTrue(require_auth)
def test_add_genres(self):
self.obj.add_genre('genre1', 2)
self.assertEqual(self.obj.genres['genre1'], 2)
self.obj.add_genre('genre1', 5)
self.assertEqual(self.obj.genres['genre1'], 7)
def test_set_genre_inc_custom_config(self):
inc = set()
config.setting['use_genres'] = False
config.setting['folksonomy_tags'] = False
config.setting['only_my_genres'] = False
custom_config = Mock()
custom_config.setting = {
'use_genres': True,
'folksonomy_tags': True,
'only_my_genres': True,
}
require_auth = self.obj.set_genre_inc_params(inc, custom_config)
self.assertIn('user-tags', inc)
self.assertTrue(require_auth)
| 3,564
|
Python
|
.py
| 85
| 35.352941
| 80
| 0.669841
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,859
|
test_util_uniqnum_title.py
|
metabrainz_picard/test/test_util_uniqnum_title.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util import (
_regex_numbered_title_fmt,
unique_numbered_title,
)
class RegexNumberedTitleFmt(PicardTestCase):
def test_1(self):
fmt = ''
result = _regex_numbered_title_fmt(fmt, 'TITLE', 'COUNT')
self.assertEqual(result, '')
def test_2(self):
fmt = '{title} {count}'
result = _regex_numbered_title_fmt(fmt, 'TITLE', 'COUNT')
self.assertEqual(result, r'TITLE(?:\ COUNT)?')
def test_3(self):
fmt = 'x {count} {title} y'
result = _regex_numbered_title_fmt(fmt, 'TITLE', 'COUNT')
self.assertEqual(result, r'(?:x\ COUNT\ \ )?TITLE y')
def test_4(self):
fmt = 'x {title}{count} y'
result = _regex_numbered_title_fmt(fmt, 'TITLE', 'COUNT')
self.assertEqual(result, r'x TITLE(?:COUNT\ y)?')
class UniqueNumberedTitle(PicardTestCase):
def test_existing_titles_0(self):
title = unique_numbered_title('title', [], fmt='{title} ({count})')
self.assertEqual(title, 'title (1)')
def test_existing_titles_1(self):
title = unique_numbered_title('title', ['title'], fmt='{title} ({count})')
self.assertEqual(title, 'title (2)')
def test_existing_titles_2(self):
title = unique_numbered_title('title', ['title', 'title (2)'], fmt='{title} ({count})')
self.assertEqual(title, 'title (3)')
def test_existing_titles_3(self):
title = unique_numbered_title('title', ['title (1)', 'title (2)'], fmt='{title} ({count})')
self.assertEqual(title, 'title (3)')
def test_existing_titles_4(self):
title = unique_numbered_title('title', ['title', 'title'], fmt='{title} ({count})')
self.assertEqual(title, 'title (3)')
def test_existing_titles_5(self):
title = unique_numbered_title('title', ['x title', 'title y'], fmt='{title} ({count})')
self.assertEqual(title, 'title (1)')
def test_existing_titles_6(self):
title = unique_numbered_title('title', ['title (n)'], fmt='{title} ({count})')
self.assertEqual(title, 'title (1)')
def test_existing_titles_7(self):
title = unique_numbered_title('title', ['title ()'], fmt='{title} ({count})')
self.assertEqual(title, 'title (1)')
def test_existing_titles_8(self):
title = unique_numbered_title('title', ['title(2)'], fmt='{title} ({count})')
self.assertEqual(title, 'title (1)')
class UniqueNumberedTitleFmt(PicardTestCase):
def test_existing_titles_0(self):
title = unique_numbered_title('title', [], fmt='({count}) {title}')
self.assertEqual(title, '(1) title')
def test_existing_titles_1(self):
title = unique_numbered_title('title', ['title'], fmt='({count}) {title}')
self.assertEqual(title, '(2) title')
def test_existing_titles_2(self):
title = unique_numbered_title('title', ['title', '(2) title'], fmt='({count}) {title}')
self.assertEqual(title, '(3) title')
def test_existing_titles_3(self):
title = unique_numbered_title('title', ['(1) title', '(2) title'], fmt='({count}) {title}')
self.assertEqual(title, '(3) title')
def test_existing_titles_4(self):
title = unique_numbered_title('title', ['title', 'title'], fmt='({count}) {title}')
self.assertEqual(title, '(3) title')
def test_existing_titles_5(self):
title = unique_numbered_title('title', ['x title', 'title y'], fmt='({count}) {title}')
self.assertEqual(title, '(1) title')
def test_existing_titles_6(self):
title = unique_numbered_title('title', ['(n) title'], fmt='({count}) {title}')
self.assertEqual(title, '(1) title')
def test_existing_titles_7(self):
title = unique_numbered_title('title', ['() title'], fmt='({count}) {title}')
self.assertEqual(title, '(1) title')
def test_existing_titles_8(self):
title = unique_numbered_title('title', ['(2)title'], fmt='({count}) {title}')
self.assertEqual(title, '(1) title')
| 4,965
|
Python
|
.py
| 99
| 44.010101
| 99
| 0.638826
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,860
|
test_coverart_processing.py
|
metabrainz_picard/test/test_coverart_processing.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Giorgio Fontanive
#
# This program is free software; you can redistribute it and/or
# modify 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.
from copy import copy
from PyQt6.QtCore import QBuffer
from PyQt6.QtGui import QImage
from test.picardtestcase import PicardTestCase
from picard import config
from picard.album import Album
from picard.const.cover_processing import ResizeModes
from picard.coverart.image import CoverArtImage
from picard.coverart.processing import CoverArtImageProcessing
from picard.coverart.processing.filters import (
bigger_previous_image_filter,
image_types_filter,
size_filter,
size_metadata_filter,
)
from picard.coverart.processing.processors import (
ConvertImage,
ResizeImage,
)
from picard.extension_points.cover_art_processors import (
CoverArtProcessingError,
ProcessingImage,
ProcessingTarget,
)
from picard.util import imageinfo
from picard.util.imagelist import ImageList
def create_fake_image(width, height, image_format):
buffer = QBuffer()
image = QImage(width, height, QImage.Format.Format_ARGB32)
image.save(buffer, image_format)
buffer.close()
data = buffer.data()
try:
info = imageinfo.identify(data)
except imageinfo.IdentificationError:
info = None
return data, info
class ImageFiltersTest(PicardTestCase):
def setUp(self):
super().setUp()
settings = {
'filter_cover_by_size': True,
'cover_minimum_width': 500,
'cover_minimum_height': 500,
'dont_replace_with_smaller_cover': True,
'dont_replace_cover_of_types': True,
'dont_replace_included_types': ['front', 'booklet'],
'dont_replace_excluded_types': ['back'],
'save_images_to_tags': True,
}
self.set_config_values(settings)
def test_filter_by_size(self):
image1, info1 = create_fake_image(400, 600, 'png')
image2, info2 = create_fake_image(500, 500, 'jpeg')
image3, info3 = create_fake_image(600, 600, 'tiff')
self.assertFalse(size_filter(image1, info1, None, None))
self.assertTrue(size_filter(image2, info2, None, None))
self.assertTrue(size_filter(image3, info3, None, None))
def test_filter_by_size_metadata(self):
image_metadata1 = {'width': 400, 'height': 600}
image_metadata2 = {'width': 500, 'height': 500}
image_metadata3 = {'width': 600, 'height': 600}
self.assertFalse(size_metadata_filter(image_metadata1))
self.assertTrue(size_metadata_filter(image_metadata2))
self.assertTrue(size_metadata_filter(image_metadata3))
def _create_fake_album(self):
previous_coverartimage = CoverArtImage(types=['front'], support_types=True)
previous_coverartimage.width = 1000
previous_coverartimage.height = 1000
album = Album(None)
album.orig_metadata.images = ImageList([previous_coverartimage])
return album
def test_filter_by_previous_image_size(self):
album = self._create_fake_album()
image1, info1 = create_fake_image(500, 500, 'jpg')
image2, info2 = create_fake_image(2000, 2000, 'jpg')
coverartimage = CoverArtImage(types=['front'], support_types=True)
self.assertFalse(bigger_previous_image_filter(image1, info1, album, coverartimage))
self.assertTrue(bigger_previous_image_filter(image2, info2, album, coverartimage))
coverartimage = CoverArtImage(types=['back'], support_types=True)
self.assertTrue(bigger_previous_image_filter(image1, info1, album, coverartimage))
def test_filter_by_image_type(self):
album = self._create_fake_album()
image, info = create_fake_image(1000, 1000, 'jpg')
coverartimage1 = CoverArtImage(types=['front'], support_types=True)
coverartimage2 = CoverArtImage(types=['back'], support_types=True)
coverartimage3 = CoverArtImage(types=['front', 'back'], support_types=True)
coverartimage4 = CoverArtImage(types=['spine'], support_types=True)
coverartimage5 = CoverArtImage(types=['booklet', 'spine'], support_types=True)
self.assertFalse(image_types_filter(image, info, album, coverartimage1))
self.assertTrue(image_types_filter(image, info, album, coverartimage2))
self.assertTrue(image_types_filter(image, info, album, coverartimage3))
self.assertTrue(image_types_filter(image, info, album, coverartimage4))
self.assertTrue(image_types_filter(image, info, album, coverartimage5))
class ImageProcessorsTest(PicardTestCase):
def setUp(self):
super().setUp()
self.settings = {
'enabled_plugins': [],
'cover_tags_resize': True,
'cover_tags_enlarge': True,
'cover_tags_resize_target_width': 500,
'cover_tags_resize_target_height': 500,
'cover_tags_resize_mode': ResizeModes.MAINTAIN_ASPECT_RATIO,
'cover_tags_convert_images': False,
'cover_tags_convert_to_format': 'jpeg',
'cover_file_resize': True,
'cover_file_enlarge': True,
'cover_file_resize_target_width': 750,
'cover_file_resize_target_height': 750,
'cover_file_resize_mode': ResizeModes.MAINTAIN_ASPECT_RATIO,
'save_images_to_tags': True,
'save_images_to_files': True,
'cover_file_convert_images': False,
'cover_file_convert_to_format': 'jpeg',
}
def _check_image_processors(self, size, expected_tags_size, expected_file_size=None):
coverartimage = CoverArtImage()
image, info = create_fake_image(size[0], size[1], 'jpg')
album = Album(None)
image_processing = CoverArtImageProcessing(album)
image_processing.run_image_processors(coverartimage, image, info)
image_processing.wait_for_processing()
tags_size = (coverartimage.width, coverartimage.height)
if config.setting['save_images_to_tags']:
self.assertEqual(tags_size, expected_tags_size)
else:
self.assertEqual(tags_size, size)
if config.setting['save_images_to_files']:
external_cover = coverartimage.external_file_coverart
file_size = (external_cover.width, external_cover.height)
self.assertEqual(file_size, expected_file_size)
else:
self.assertIsNone(coverartimage.external_file_coverart)
extension = coverartimage.extension[1:]
self.assertEqual(extension, 'jpg')
def test_image_processors_save_to_both(self):
self.set_config_values(self.settings)
self._check_image_processors((1000, 1000), (500, 500), (750, 750))
self._check_image_processors((600, 600), (500, 500), (750, 750))
self._check_image_processors((400, 400), (500, 500), (750, 750))
def test_image_processors_save_to_tags(self):
settings = copy(self.settings)
settings['save_images_to_files'] = False
self.set_config_values(settings)
self._check_image_processors((1000, 1000), (500, 500))
self._check_image_processors((600, 600), (500, 500))
self._check_image_processors((400, 400), (500, 500))
self.set_config_values(self.settings)
def test_image_processors_save_to_file(self):
settings = copy(self.settings)
settings['save_images_to_tags'] = False
self.set_config_values(settings)
self._check_image_processors((1000, 1000), (1000, 1000), (750, 750))
self._check_image_processors((600, 600), (600, 600), (750, 750))
self._check_image_processors((400, 400), (400, 400), (750, 750))
self.set_config_values(self.settings)
def test_image_processors_save_to_none(self):
settings = copy(self.settings)
settings['save_images_to_tags'] = False
settings['save_images_to_files'] = False
self.set_config_values(settings)
self._check_image_processors((1000, 1000), (1000, 1000), (1000, 1000))
self.set_config_values(self.settings)
def _check_resize_image(self, size, expected_size):
image = ProcessingImage(*create_fake_image(size[0], size[1], 'jpg'))
processor = ResizeImage()
processor.run(image, ProcessingTarget.TAGS)
new_size = (image.get_qimage().width(), image.get_qimage().height())
new_info_size = (image.info.width, image.info.height)
self.assertEqual(new_size, expected_size)
self.assertEqual(new_info_size, expected_size)
def test_scale_down_both_dimensions(self):
self.set_config_values(self.settings)
self._check_resize_image((1000, 1000), (500, 500))
self._check_resize_image((1000, 500), (500, 250))
self._check_resize_image((600, 1200), (250, 500))
def test_scale_down_only_width(self):
settings = copy(self.settings)
settings['cover_tags_resize_mode'] = ResizeModes.SCALE_TO_WIDTH
self.set_config_values(settings)
self._check_resize_image((1000, 1000), (500, 500))
self._check_resize_image((1000, 500), (500, 250))
self._check_resize_image((600, 1200), (500, 1000))
self.set_config_values(self.settings)
def test_scale_down_only_height(self):
settings = copy(self.settings)
settings['cover_tags_resize_mode'] = ResizeModes.SCALE_TO_HEIGHT
self.set_config_values(settings)
self._check_resize_image((1000, 1000), (500, 500))
self._check_resize_image((1000, 500), (1000, 500))
self._check_resize_image((600, 1200), (250, 500))
self.set_config_values(self.settings)
def test_scale_up_both_dimensions(self):
self.set_config_values(self.settings)
self._check_resize_image((250, 250), (500, 500))
self._check_resize_image((400, 500), (400, 500))
self._check_resize_image((250, 150), (500, 300))
def test_scale_up_only_width(self):
settings = copy(self.settings)
settings['cover_tags_resize_mode'] = ResizeModes.SCALE_TO_WIDTH
self.set_config_values(settings)
self._check_resize_image((250, 250), (500, 500))
self._check_resize_image((400, 500), (500, 625))
self._check_resize_image((500, 250), (500, 250))
self.set_config_values(self.settings)
def test_scale_up_only_height(self):
settings = copy(self.settings)
settings['cover_tags_resize_mode'] = ResizeModes.SCALE_TO_HEIGHT
self.set_config_values(settings)
self._check_resize_image((250, 250), (500, 500))
self._check_resize_image((400, 500), (400, 500))
self._check_resize_image((500, 250), (1000, 500))
self.set_config_values(self.settings)
def test_scale_priority(self):
settings = copy(self.settings)
settings['cover_tags_resize_target_width'] = 500
settings['cover_tags_resize_target_height'] = 1000
self.set_config_values(settings)
self._check_resize_image((750, 750), (500, 500))
self.set_config_values(self.settings)
def test_stretch_both_dimensions(self):
settings = copy(self.settings)
settings['cover_tags_resize_mode'] = ResizeModes.STRETCH_TO_FIT
self.set_config_values(settings)
self._check_resize_image((1000, 100), (500, 500))
self._check_resize_image((200, 500), (500, 500))
self._check_resize_image((200, 2000), (500, 500))
self.set_config_values(self.settings)
def test_crop_both_dimensions(self):
settings = copy(self.settings)
settings['cover_tags_resize_mode'] = ResizeModes.CROP_TO_FIT
self.set_config_values(settings)
self._check_resize_image((1000, 100), (500, 500))
self._check_resize_image((750, 1000), (500, 500))
self._check_resize_image((250, 1000), (500, 500))
self.set_config_values(self.settings)
def _check_convert_image(self, format, expected_format):
image = ProcessingImage(*create_fake_image(100, 100, format))
processor = ConvertImage()
processor.run(image, ProcessingTarget.TAGS)
new_image = image.get_result()
new_info = imageinfo.identify(new_image)
self.assertIn(new_info.format, ConvertImage._format_aliases[expected_format])
def test_format_conversion(self):
settings = copy(self.settings)
settings['cover_tags_convert_images'] = True
formats = ['jpeg', 'png', 'webp', 'tiff']
for format in formats:
settings['cover_tags_convert_to_format'] = format
self.set_config_values(settings)
self._check_convert_image('jpeg', format)
self.set_config_values(self.settings)
def _check_processing_error(self, image, info):
self.set_config_values(self.settings)
coverartimage = CoverArtImage()
album = Album(None)
image_processing = CoverArtImageProcessing(album)
image_processing.run_image_processors(coverartimage, image, info)
image_processing.wait_for_processing()
self.assertNotEqual(album.errors, [])
for error in album.errors:
self.assertIsInstance(error, CoverArtProcessingError)
def test_identification_error(self):
image, info = create_fake_image(0, 0, "jpg")
self._check_processing_error(image, info)
def test_encoding_error(self):
image, info = create_fake_image(500, 500, "jpg")
info.extension = ".test"
self._check_processing_error(image, info)
| 14,234
|
Python
|
.py
| 289
| 41.33564
| 91
| 0.666858
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,861
|
test_util_mbserver.py
|
metabrainz_picard/test/test_util_mbserver.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021-2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.const import MUSICBRAINZ_SERVERS
from picard.util.mbserver import (
build_submission_url,
get_submission_server,
is_official_server,
)
class IsOfficialServerTest(PicardTestCase):
def test_official(self):
for host in MUSICBRAINZ_SERVERS:
self.assertTrue(is_official_server(host))
def test_not_official(self):
self.assertFalse(is_official_server('test.musicbrainz.org'))
self.assertFalse(is_official_server('example.com'))
self.assertFalse(is_official_server('127.0.0.1'))
self.assertFalse(is_official_server('localhost'))
class GetSubmissionServerTest(PicardTestCase):
def test_official(self):
for host in MUSICBRAINZ_SERVERS:
self.set_config_values(setting={
'server_host': host,
'server_port': 80,
'use_server_for_submission': False,
})
self.assertEqual((host, 443), get_submission_server())
def test_use_unofficial(self):
self.set_config_values(setting={
'server_host': 'example.com',
'server_port': 8042,
'use_server_for_submission': True,
})
self.assertEqual(('example.com', 8042), get_submission_server())
def test_unofficial_fallback(self):
self.set_config_values(setting={
'server_host': 'test.musicbrainz.org',
'server_port': 80,
'use_server_for_submission': False,
})
self.assertEqual((MUSICBRAINZ_SERVERS[0], 443), get_submission_server())
def test_named_tuple(self):
self.set_config_values(setting={
'server_host': 'example.com',
'server_port': 8042,
'use_server_for_submission': True,
})
server = get_submission_server()
self.assertEqual('example.com', server.host)
self.assertEqual(8042, server.port)
class BuildSubmissionUrlTest(PicardTestCase):
def test_official(self):
for host in MUSICBRAINZ_SERVERS:
self.set_config_values(setting={
'server_host': host,
'server_port': 80,
'use_server_for_submission': False,
})
self.assertEqual('https://%s' % host, build_submission_url())
self.assertEqual('https://%s/' % host, build_submission_url('/'))
self.assertEqual('https://%s/some/path?foo=1&bar=baz' % host,
build_submission_url('/some/path', {'foo': 1, 'bar': 'baz'}))
def test_use_unofficial(self):
self.set_config_values(setting={
'server_host': 'example.com',
'server_port': 8042,
'use_server_for_submission': True,
})
self.assertEqual('http://example.com:8042', build_submission_url())
self.assertEqual('http://example.com:8042/', build_submission_url('/'))
self.assertEqual('http://example.com:8042/some/path?foo=1&bar=baz',
build_submission_url('/some/path', {'foo': 1, 'bar': 'baz'}))
def test_unofficial_fallback(self):
self.set_config_values(setting={
'server_host': 'test.musicbrainz.org',
'server_port': 80,
'use_server_for_submission': False,
})
self.assertEqual('https://musicbrainz.org', build_submission_url())
self.assertEqual('https://musicbrainz.org/', build_submission_url('/'))
self.assertEqual('https://musicbrainz.org/some/path?foo=1&bar=baz',
build_submission_url('/some/path', {'foo': 1, 'bar': 'baz'}))
| 4,482
|
Python
|
.py
| 100
| 36.6
| 80
| 0.64253
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,862
|
test_scripttofilename.py
|
metabrainz_picard/test/test_scripttofilename.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018-2020 Philipp Wolfer
# Copyright (C) 2019-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
import unittest
from test.picardtestcase import PicardTestCase
from picard import config
from picard.const.sys import IS_WIN
from picard.extension_points.script_functions import register_script_function
from picard.file import File
from picard.metadata import Metadata
from picard.util.scripttofilename import (
script_to_filename,
script_to_filename_with_metadata,
)
settings = {
'ascii_filenames': False,
'enabled_plugins': [],
'windows_compatibility': False,
'win_compat_replacements': {},
'replace_spaces_with_underscores': False,
'replace_dir_separator': '_',
}
def func_has_file(parser):
return '1' if parser.file else ''
register_script_function(lambda p: '1' if p.file else '', 'has_file')
class ScriptToFilenameTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values(settings)
def test_plain_filename(self):
metadata = Metadata()
filename = script_to_filename('AlbumArt', metadata)
self.assertEqual('AlbumArt', filename)
def test_simple_script(self):
metadata = Metadata()
metadata['artist'] = 'AC/DC'
metadata['album'] = 'The Album'
filename = script_to_filename('%album%', metadata)
self.assertEqual('The Album', filename)
filename = script_to_filename('%artist%/%album%', metadata)
self.assertEqual('AC_DC/The Album', filename)
def test_preserve_backslash(self):
metadata = Metadata()
metadata['artist'] = 'AC\\/DC'
filename = script_to_filename('%artist%', metadata)
self.assertEqual('AC__DC' if IS_WIN else 'AC\\_DC', filename)
def test_file_metadata(self):
metadata = Metadata()
file = File('somepath/somefile.mp3')
self.assertEqual('', script_to_filename('$has_file()', metadata))
self.assertEqual('1', script_to_filename('$has_file()', metadata, file=file))
def test_script_to_filename_with_metadata(self):
metadata = Metadata()
metadata['artist'] = 'Foo'
metadata['~extension'] = 'foo'
(filename, new_metadata) = script_to_filename_with_metadata(
'$set(_extension,bar)\n%artist%', metadata)
self.assertEqual('Foo', filename)
self.assertEqual('foo', metadata['~extension'])
self.assertEqual('bar', new_metadata['~extension'])
def test_ascii_filenames(self):
metadata = Metadata()
metadata['artist'] = 'Die Ärzte'
settings = config.setting.copy()
settings['ascii_filenames'] = False
filename = script_to_filename('%artist% éöü½', metadata, settings=settings)
self.assertEqual('Die Ärzte éöü½', filename)
settings['ascii_filenames'] = True
filename = script_to_filename('%artist% éöü½', metadata, settings=settings)
self.assertEqual('Die Arzte eou 1_2', filename)
def test_windows_compatibility(self):
metadata = Metadata()
metadata['artist'] = '\\*:'
settings = config.setting.copy()
settings['windows_compatibility'] = False
expect_orig = '\\*:?'
expect_compat = '____'
filename = script_to_filename('%artist%?', metadata, settings=settings)
self.assertEqual(expect_compat if IS_WIN else expect_orig, filename)
settings['windows_compatibility'] = True
filename = script_to_filename('%artist%?', metadata, settings=settings)
self.assertEqual(expect_compat, filename)
def test_windows_compatibility_custom_replacements(self):
metadata = Metadata()
metadata['artist'] = '\\*:'
expect_compat = '_+_!'
settings = config.setting.copy()
settings['windows_compatibility'] = True
settings['win_compat_replacements'] = {
'*': '+',
'?': '!',
}
filename = script_to_filename('%artist%?', metadata, settings=settings)
self.assertEqual(expect_compat, filename)
def test_replace_spaces_with_underscores(self):
metadata = Metadata()
metadata['artist'] = ' The \t New* _ Artist '
settings = config.setting.copy()
settings['windows_compatibility'] = True
settings['replace_spaces_with_underscores'] = False
filename = script_to_filename('%artist%', metadata, settings=settings)
self.assertEqual(' The \t New_ _ Artist ', filename)
settings['replace_spaces_with_underscores'] = True
filename = script_to_filename('%artist%', metadata, settings=settings)
self.assertEqual('The_New_Artist', filename)
def test_replace_dir_separator(self):
metadata = Metadata()
metadata['artist'] = 'AC/DC'
settings = config.setting.copy()
settings['replace_dir_separator'] = '-'
filename = script_to_filename('/music/%artist%', metadata, settings=settings)
self.assertEqual('/music/AC-DC', filename)
@unittest.skipUnless(IS_WIN, "windows test")
def test_ascii_win_save(self):
self._test_ascii_windows_compatibility()
def test_ascii_win_compat(self):
config.setting['windows_compatibility'] = True
self._test_ascii_windows_compatibility()
def _test_ascii_windows_compatibility(self):
metadata = Metadata()
metadata['artist'] = '\u2216/\\\u2215'
settings = config.setting.copy()
settings['ascii_filenames'] = True
filename = script_to_filename('%artist%/\u2216\\\\\u2215', metadata, settings=settings)
self.assertEqual('____/_\\_', filename)
def test_remove_null_chars(self):
metadata = Metadata()
filename = script_to_filename('a\x00b\x00', metadata)
self.assertEqual('ab', filename)
def test_remove_tabs_and_linebreaks_chars(self):
metadata = Metadata()
filename = script_to_filename('a\tb\nc', metadata)
self.assertEqual('abc', filename)
def test_remove_leading_and_trailing_whitespace(self):
metadata = Metadata()
metadata['artist'] = 'The Artist'
filename = script_to_filename(' %artist% ', metadata)
self.assertEqual(' The Artist ', filename)
| 7,033
|
Python
|
.py
| 155
| 38.470968
| 95
| 0.66496
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,863
|
test_disc_dbpoweramplog.py
|
metabrainz_picard/test/test_disc_dbpoweramplog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 Laurent Monin
# Copyright (C) 2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from typing import Iterator
from test.picardtestcase import (
PicardTestCase,
get_test_data_path,
)
from picard.disc.dbpoweramplog import (
filter_toc_entries,
toc_from_file,
)
from picard.disc.utils import (
NotSupportedTOCError,
TocEntry,
)
test_log = (
'TEST LOG',
'Track 1: Ripped LBA 0 to 24914 (5:32) in 0:30. Filename: ',
'',
'Track 2: Ripped LBA 24914 to 43461 (4:07) in 0:20. Filename: ',
'Track 3: Ripped LBA 43461 to 60740 (3:50) in 0:17. Filename: ',
'',
'foo',
)
test_entries = [
TocEntry(1, 0, 24913),
TocEntry(2, 24914, 43460),
TocEntry(3, 43461, 60739),
]
class TestFilterTocEntries(PicardTestCase):
def test_filter_toc_entries(self):
result = filter_toc_entries(iter(test_log))
self.assertTrue(isinstance(result, Iterator))
entries = list(result)
self.assertEqual(test_entries, entries)
def test_no_gaps_in_track_numbers(self):
log = test_log[:2] + test_log[4:]
with self.assertRaisesRegex(NotSupportedTOCError, '^Non consecutive track numbers'):
list(filter_toc_entries(log))
class TestTocFromFile(PicardTestCase):
def _test_toc_from_file(self, logfile):
test_log = get_test_data_path(logfile)
toc = toc_from_file(test_log)
self.assertEqual((1, 8, 149323, 150, 25064, 43611, 60890, 83090, 100000, 115057, 135558), toc)
def test_toc_from_file_utf8(self):
self._test_toc_from_file('dbpoweramp-utf8.txt')
def test_toc_from_file_utf16le(self):
self._test_toc_from_file('dbpoweramp-utf16le.txt')
def test_toc_from_file_with_datatrack(self):
test_log = get_test_data_path('dbpoweramp-datatrack.txt')
toc = toc_from_file(test_log)
self.assertEqual((1, 13, 239218, 150, 16988, 32954, 48647, 67535, 87269, 104221, 121441, 138572, 152608, 170362, 187838, 215400), toc)
def test_toc_from_empty_file(self):
test_log = get_test_data_path('eac-empty.log')
with self.assertRaises(NotSupportedTOCError):
toc_from_file(test_log)
| 2,950
|
Python
|
.py
| 74
| 35.324324
| 142
| 0.70049
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,864
|
test_api_helpers.py
|
metabrainz_picard/test/test_api_helpers.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018, 2020-2021, 2023 Laurent Monin
# Copyright (C) 2019-2023 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from unittest.mock import MagicMock
from PyQt6.QtCore import QUrl
from test.picardtestcase import PicardTestCase
from picard.acoustid.manager import Submission
from picard.metadata import Metadata
from picard.webservice import WebService
from picard.webservice.api_helpers import (
AcoustIdAPIHelper,
APIHelper,
MBAPIHelper,
build_lucene_query,
escape_lucene_query,
)
class APITest(PicardTestCase):
def setUp(self):
super().setUp()
base_url = "http://abc.com/v1"
self.path = "/test/more/test"
self.complete_url = QUrl(base_url + self.path)
self.ws = MagicMock(auto_spec=WebService)
self.api = APIHelper(self.ws, base_url=base_url)
def _test_ws_function_args(self, ws_function):
self.assertGreater(ws_function.call_count, 0)
self.assertEqual(ws_function.call_args[1]['url'], self.complete_url)
def test_get(self):
self.api.get(self.path, None)
self._test_ws_function_args(self.ws.get_url)
def test_post(self):
self.api.post(self.path, None, None)
self._test_ws_function_args(self.ws.post_url)
def test_put(self):
self.api.put(self.path, None, None)
self._test_ws_function_args(self.ws.put_url)
def test_delete(self):
self.api.delete(self.path, None)
self._test_ws_function_args(self.ws.delete_url)
class MBAPITest(PicardTestCase):
def setUp(self):
super().setUp()
self.config = {'server_host': "mb.org", "server_port": 443}
self.set_config_values(self.config)
self.ws = MagicMock(auto_spec=WebService)
self.api = MBAPIHelper(self.ws)
def _test_ws_function_args(self, ws_function):
self.assertGreater(ws_function.call_count, 0)
url = ws_function.call_args[1]['url']
self.assertTrue(url.toString().startswith("https://mb.org/"))
self.assertTrue(url.path().startswith("/ws/2/"))
def assertInPath(self, ws_function, path):
self.assertIn(path, ws_function.call_args[1]['url'].path())
def assertNotInPath(self, ws_function, path):
self.assertNotIn(path, ws_function.call_args[1]['url'].path())
def assertInQuery(self, ws_function, argname, value=None):
unencoded_query_args = ws_function.call_args[1]['unencoded_queryargs']
self.assertIn(argname, unencoded_query_args)
self.assertEqual(value, unencoded_query_args[argname])
def _test_inc_args(self, ws_function, arg_list):
self.assertInQuery(self.ws.get_url, 'inc', self.api._make_inc_arg(arg_list))
def test_get_release(self):
inc_args_list = ['test']
self.api.get_release_by_id("1", None, inc=inc_args_list)
self._test_ws_function_args(self.ws.get_url)
self.assertInPath(self.ws.get_url, "/release/1")
self._test_inc_args(self.ws.get_url, inc_args_list)
def test_get_track(self):
inc_args_list = ['test']
self.api.get_track_by_id("1", None, inc=inc_args_list)
self._test_ws_function_args(self.ws.get_url)
self.assertInPath(self.ws.get_url, "/recording/1")
self._test_inc_args(self.ws.get_url, inc_args_list)
def test_get_collection(self):
inc_args_list = ["releases", "artist-credits", "media"]
self.api.get_collection("1", None)
self._test_ws_function_args(self.ws.get_url)
self.assertInPath(self.ws.get_url, "collection")
self.assertInPath(self.ws.get_url, "1/releases")
self._test_inc_args(self.ws.get_url, inc_args_list)
def test_get_collection_list(self):
self.api.get_collection_list(None)
self._test_ws_function_args(self.ws.get_url)
self.assertInPath(self.ws.get_url, "collection")
self.assertNotInPath(self.ws.get_url, "releases")
def test_put_collection(self):
self.api.put_to_collection("1", ["1", "2", "3"], None)
self._test_ws_function_args(self.ws.put_url)
self.assertInPath(self.ws.put_url, "collection/1/releases/1;2;3")
def test_delete_collection(self):
self.api.delete_from_collection("1", ["1", "2", "3", "4"] * 200, None)
collection_string = ";".join(["1", "2", "3", "4"] * 100)
self._test_ws_function_args(self.ws.delete_url)
self.assertInPath(self.ws.delete_url, "collection/1/releases/" + collection_string)
self.assertNotInPath(self.ws.delete_url, collection_string + ";" + collection_string)
self.assertEqual(self.ws.delete_url.call_count, 2)
def test_xml_ratings_empty(self):
ratings = dict()
xmldata = self.api._xml_ratings(ratings)
self.assertEqual(
xmldata,
'<?xml version="1.0" encoding="UTF-8"?>'
'<metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#">'
'<recording-list></recording-list>'
'</metadata>'
)
def test_xml_ratings_one(self):
ratings = {("recording", 'a'): 1}
xmldata = self.api._xml_ratings(ratings)
self.assertEqual(
xmldata,
'<?xml version="1.0" encoding="UTF-8"?>'
'<metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#">'
'<recording-list>'
'<recording id="a"><user-rating>20</user-rating></recording>'
'</recording-list>'
'</metadata>'
)
def test_xml_ratings_multiple(self):
ratings = {
("recording", 'a'): 1,
("recording", 'b'): 2,
("nonrecording", 'c'): 3,
}
xmldata = self.api._xml_ratings(ratings)
self.assertEqual(
xmldata,
'<?xml version="1.0" encoding="UTF-8"?>'
'<metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#">'
'<recording-list>'
'<recording id="a"><user-rating>20</user-rating></recording>'
'<recording id="b"><user-rating>40</user-rating></recording>'
'</recording-list>'
'</metadata>'
)
def test_xml_ratings_encode(self):
ratings = {("recording", '<a&"\'>'): 0}
xmldata = self.api._xml_ratings(ratings)
self.assertEqual(
xmldata,
'<?xml version="1.0" encoding="UTF-8"?>'
'<metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#">'
'<recording-list>'
'<recording id="<a&"\'>"><user-rating>0</user-rating></recording>'
'</recording-list>'
'</metadata>'
)
def test_xml_ratings_raises_value_error(self):
ratings = {("recording", 'a'): 'foo'}
self.assertRaises(ValueError, self.api._xml_ratings, ratings)
def test_collection_request(self):
releases = tuple("r"+str(i) for i in range(13))
generator = self.api._collection_request("test", releases, batchsize=5)
batch = next(generator)
self.assertEqual(batch, '/collection/test/releases/r0;r1;r2;r3;r4')
batch = next(generator)
self.assertEqual(batch, '/collection/test/releases/r5;r6;r7;r8;r9')
batch = next(generator)
self.assertEqual(batch, '/collection/test/releases/r10;r11;r12')
with self.assertRaises(StopIteration):
next(generator)
def test_make_inc_arg(self):
result = self.api._make_inc_arg(['b', 'a', '', 1, (), 0])
expected = '1+a+b'
self.assertEqual(result, expected)
class AcoustdIdAPITest(PicardTestCase):
def setUp(self):
super().setUp()
self.config = {'acoustid_apikey': "apikey"}
self.set_config_values(self.config)
self.ws = MagicMock(auto_spec=WebService)
self.api = AcoustIdAPIHelper(self.ws)
self.api.acoustid_host = 'acoustid_host'
self.api.acoustid_port = 443
self.api.client_key = "key"
self.api.client_version = "ver"
def test_encode_acoustid_args_static(self):
args = {'a': '1', 'b': 'v a l'}
result = self.api._encode_acoustid_args(args)
expected = 'a=1&b=v%20a%20l&client=key&clientversion=ver&format=json'
self.assertEqual(result, expected)
def test_encode_acoustid_args_static_empty(self):
args = dict()
result = self.api._encode_acoustid_args(args)
expected = 'client=key&clientversion=ver&format=json'
self.assertEqual(result, expected)
def test_submissions_to_args(self):
submissions = [
Submission('f1', 1, recordingid='or1', metadata=Metadata(musicip_puid='p1')),
Submission('f2', 2, recordingid='or2', metadata=Metadata(musicip_puid='p2')),
]
submissions[0].recordingid = 'r1'
submissions[1].recordingid = 'r2'
result = self.api._submissions_to_args(submissions)
expected = {
'user': 'apikey',
'fingerprint.0': 'f1', 'duration.0': '1', 'mbid.0': 'r1', 'puid.0': 'p1',
'fingerprint.1': 'f2', 'duration.1': '2', 'mbid.1': 'r2', 'puid.1': 'p2'
}
self.assertEqual(result, expected)
def test_submissions_to_args_invalid_duration(self):
metadata1 = Metadata({
'title': 'The Track',
'artist': 'The Artist',
'album': 'The Album',
'albumartist': 'The Album Artist',
'tracknumber': '4',
'discnumber': '2',
}, length=100000)
metadata2 = Metadata({
'year': '2022'
}, length=100000)
metadata3 = Metadata({
'date': '1980-08-30'
}, length=100000)
metadata4 = Metadata({
'date': '08-30'
}, length=100000)
submissions = [
Submission('f1', 500000, recordingid='or1', metadata=metadata1),
Submission('f2', 500000, recordingid='or2', metadata=metadata2),
Submission('f3', 500000, recordingid='or3', metadata=metadata3),
Submission('f4', 500000, recordingid='or4', metadata=metadata4),
]
submissions[0].recordingid = 'r1'
submissions[1].recordingid = 'r2'
submissions[1].recordingid = 'r3'
submissions[1].recordingid = 'r4'
result = self.api._submissions_to_args(submissions)
expected = {
'user': 'apikey',
'fingerprint.0': 'f1',
'duration.0': '500000',
'track.0': metadata1['title'],
'artist.0': metadata1['artist'],
'album.0': metadata1['album'],
'albumartist.0': metadata1['albumartist'],
'trackno.0': metadata1['tracknumber'],
'discno.0': metadata1['discnumber'],
'fingerprint.1': 'f2',
'duration.1': '500000',
'year.1': '2022',
'fingerprint.2': 'f3',
'duration.2': '500000',
'year.2': '1980',
'fingerprint.3': 'f4',
'duration.3': '500000',
}
self.assertEqual(result, expected)
class LuceneHelpersTest(PicardTestCase):
def test_escape_lucene_query(self):
self.assertEqual('', escape_lucene_query(''))
self.assertEqual(
'\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\"\\~\\*\\?\\:\\\\\\/',
escape_lucene_query('+-&|!(){}[]^"~*?:\\/'))
def test_build_lucene_query(self):
args = {
'title': 'test',
'artist': 'foo:bar',
'tnum': '3'
}
query = build_lucene_query(args)
self.assertEqual('title:(test) artist:(foo\\:bar) tnum:(3)', query)
| 12,423
|
Python
|
.py
| 282
| 35.375887
| 93
| 0.606399
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,865
|
test_script_serializer.py
|
metabrainz_picard/test/test_script_serializer.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021, 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import datetime
from unittest.mock import patch
import yaml
from test.picardtestcase import PicardTestCase
from picard.script.serializer import (
FileNamingScriptInfo,
ScriptSerializer,
ScriptSerializerFromFileError,
)
class MockDateTime(datetime.datetime):
@classmethod
def now(cls, tz=None):
if tz == datetime.timezone.utc:
return cls(year=2020, month=1, day=2, hour=12, minute=34, second=56, microsecond=789, tzinfo=None)
else:
raise Exception("Unexpected parameter tz=%r" % tz)
class ScriptSerializerTest(PicardTestCase):
def assertYamlEquals(self, yaml_str, obj, msg=None):
self.assertEqual(obj, yaml.safe_load(yaml_str), msg)
def test_script_object_1(self):
# Check initial loaded values.
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26', script_language_version='1.0')
self.assertEqual(test_script.id, '12345')
self.assertEqual(test_script['id'], '12345')
self.assertEqual(test_script.last_updated, '2021-04-26')
self.assertEqual(test_script['last_updated'], '2021-04-26')
self.assertYamlEquals(test_script.to_yaml(), {"id": "12345", "script": "Script text\n", "script_language_version": "1.0", "title": "Script 1"})
def test_script_object_2(self):
# Check updating values directly so as not to modify `last_updated`.
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26')
test_script.id = '54321'
self.assertEqual(test_script.id, '54321')
self.assertEqual(test_script['id'], '54321')
self.assertEqual(test_script.last_updated, '2021-04-26')
self.assertEqual(test_script['last_updated'], '2021-04-26')
test_script.title = 'Updated Script 1'
self.assertEqual(test_script.title, 'Updated Script 1')
self.assertEqual(test_script['title'], 'Updated Script 1')
self.assertEqual(test_script['last_updated'], '2021-04-26')
def test_script_object_3(self):
# Check updating values that are ignored from modifying `last_updated`.
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26')
test_script.update_script_setting(id='54321')
self.assertEqual(test_script.id, '54321')
self.assertEqual(test_script['id'], '54321')
self.assertEqual(test_script.last_updated, '2021-04-26')
self.assertEqual(test_script['last_updated'], '2021-04-26')
@patch('datetime.datetime', MockDateTime)
def test_script_object_4(self):
# Check updating values that modify `last_updated`.
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26')
test_script.update_script_setting(title='Updated Script 1')
self.assertEqual(test_script.title, 'Updated Script 1')
self.assertEqual(test_script['title'], 'Updated Script 1')
self.assertEqual(test_script.last_updated, '2020-01-02 12:34:56 UTC')
self.assertEqual(test_script['last_updated'], '2020-01-02 12:34:56 UTC')
@patch('datetime.datetime', MockDateTime)
def test_script_object_5(self):
# Check updating values from dict that modify `last_updated`.
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26')
test_script.update_from_dict({"script": "Updated script"})
self.assertEqual(test_script.script, 'Updated script')
self.assertEqual(test_script['script'], 'Updated script')
self.assertEqual(test_script.last_updated, '2020-01-02 12:34:56 UTC')
self.assertEqual(test_script['last_updated'], '2020-01-02 12:34:56 UTC')
def test_script_object_6(self):
# Test that extra (unknown) settings are ignored during updating
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26', script_language_version='1.0')
test_script.update_script_setting(description='Updated description')
self.assertEqual(test_script['last_updated'], '2021-04-26')
self.assertYamlEquals(test_script.to_yaml(), {"id": "12345", "script": "Script text\n", "script_language_version": "1.0", "title": "Script 1"})
with self.assertRaises(AttributeError):
print(test_script.description)
def test_script_object_7(self):
# Test that extra (unknown) settings are ignored during updating from dict
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26', script_language_version='1.0')
test_script.update_from_dict({"description": "Updated description"})
self.assertEqual(test_script['last_updated'], '2021-04-26')
self.assertYamlEquals(test_script.to_yaml(), {"id": "12345", "script": "Script text\n", "script_language_version": "1.0", "title": "Script 1"})
with self.assertRaises(AttributeError):
print(test_script.description)
def test_script_object_8(self):
# Test that requested unknown settings return None
test_script = ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26')
self.assertEqual(test_script['unknown_setting'], None)
def test_script_object_9(self):
# Test that an exception is raised when creating or updating using an invalid YAML string
with self.assertRaises(ScriptSerializerFromFileError):
ScriptSerializer().create_from_yaml('Not a YAML string')
ScriptSerializer(title='Script 1', script='Script text', id='12345', last_updated='2021-04-26', script_language_version='1.0')
def test_naming_script_object_1(self):
# Check initial loaded values.
test_script = FileNamingScriptInfo(
title='Script 1', script='Script text', id='12345', last_updated='2021-04-26',
description='Script description', author='Script author', script_language_version='1.0'
)
self.assertEqual(test_script.id, '12345')
self.assertEqual(test_script['id'], '12345')
self.assertEqual(test_script.last_updated, '2021-04-26')
self.assertEqual(test_script['last_updated'], '2021-04-26')
self.assertEqual(test_script.script, 'Script text')
self.assertEqual(test_script['script'], 'Script text')
self.assertEqual(test_script.author, 'Script author')
self.assertEqual(test_script['author'], 'Script author')
self.assertEqual(
test_script.to_yaml(),
"title: Script 1\n"
"description: |\n"
" Script description\n"
"author: Script author\n"
"license: ''\n"
"version: ''\n"
"last_updated: '2021-04-26'\n"
"script_language_version: '1.0'\n"
"script: |\n"
" Script text\n"
"id: '12345'\n"
)
| 7,938
|
Python
|
.py
| 138
| 49.963768
| 151
| 0.67875
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,866
|
test_acoustidmanager.py
|
metabrainz_picard/test/test_acoustidmanager.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2020 Laurent Monin
# Copyright (C) 2020, 2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from unittest.mock import (
MagicMock,
Mock,
)
from test.picardtestcase import PicardTestCase
from picard.acoustid.manager import (
FINGERPRINT_MAX_ALLOWED_LENGTH_DIFF_MS,
AcoustIDManager,
Submission,
)
from picard.file import File
from picard.metadata import Metadata
from picard.ui.enums import MainAction
def mock_succeed_submission(*args, **kwargs):
# Run the callback
args[1]({}, None, None)
def mock_fail_submission(*args, **kwargs):
# Run the callback with error arguments
args[1]({}, MagicMock(), True)
FINGERPRINT_SIZE = 4000
def dummy_file(i):
file = File('foo%d.flac' % i)
file.acoustid_fingerprint = 'Z' * FINGERPRINT_SIZE
file.acoustid_length = 120
file.metadata = Metadata(length=file.acoustid_length * 1000)
return file
class AcoustIDManagerTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({
"clear_existing_tags": False,
"compare_ignore_tags": []
})
self.mock_api_helper = MagicMock()
self.mock_api_helper.submit_acoustid_fingerprints = Mock(wraps=mock_succeed_submission)
self.acoustidmanager = AcoustIDManager(self.mock_api_helper)
self.tagger.window = MagicMock()
self.tagger.window.enable_action = MagicMock()
AcoustIDManager.MAX_PAYLOAD = FINGERPRINT_SIZE * 5
AcoustIDManager.MAX_ATTEMPTS = 3
def _add_unsubmitted_files(self, count):
files = []
for i in range(0, count):
file = dummy_file(i)
files.append(file)
self.acoustidmanager.add(file, None)
self.acoustidmanager.update(file, '00000000-0000-0000-0000-%012d' % i)
self.assertFalse(self.acoustidmanager.is_submitted(file))
return files
def test_add_invalid(self):
file = File('foo.flac')
self.acoustidmanager.add(file, '00000000-0000-0000-0000-000000000001')
self.tagger.window.enable_action.assert_not_called()
def test_add_and_update(self):
file = dummy_file(0)
self.acoustidmanager.add(file, '00000000-0000-0000-0000-000000000001')
self.tagger.window.enable_action.assert_called_with(MainAction.SUBMIT_ACOUSTID, False)
self.acoustidmanager.update(file, '00000000-0000-0000-0000-000000000002')
self.tagger.window.enable_action.assert_called_with(MainAction.SUBMIT_ACOUSTID, True)
self.acoustidmanager.update(file, '00000000-0000-0000-0000-000000000001')
self.tagger.window.enable_action.assert_called_with(MainAction.SUBMIT_ACOUSTID, False)
def test_add_and_remove(self):
file = dummy_file(0)
self.acoustidmanager.add(file, '00000000-0000-0000-0000-000000000001')
self.tagger.window.enable_action.assert_called_with(MainAction.SUBMIT_ACOUSTID, False)
self.acoustidmanager.update(file, '00000000-0000-0000-0000-000000000002')
self.tagger.window.enable_action.assert_called_with(MainAction.SUBMIT_ACOUSTID, True)
self.acoustidmanager.remove(file)
self.tagger.window.enable_action.assert_called_with(MainAction.SUBMIT_ACOUSTID, False)
def test_is_submitted(self):
file = dummy_file(0)
self.assertTrue(self.acoustidmanager.is_submitted(file))
self.acoustidmanager.add(file, '00000000-0000-0000-0000-000000000001')
self.assertTrue(self.acoustidmanager.is_submitted(file))
self.acoustidmanager.update(file, '00000000-0000-0000-0000-000000000002')
self.assertFalse(self.acoustidmanager.is_submitted(file))
self.acoustidmanager.update(file, '')
self.assertTrue(self.acoustidmanager.is_submitted(file))
def test_submit_single_batch(self):
f = self._add_unsubmitted_files(1)[0]
self.acoustidmanager.submit()
self.assertEqual(self.mock_api_helper.submit_acoustid_fingerprints.call_count, 1)
self.assertEqual(
f.acoustid_fingerprint,
self.mock_api_helper.submit_acoustid_fingerprints.call_args[0][0][0].fingerprint
)
def test_submit_multi_batch(self):
files = self._add_unsubmitted_files(int(AcoustIDManager.MAX_PAYLOAD / FINGERPRINT_SIZE) * 2)
self.acoustidmanager.submit()
self.assertEqual(self.mock_api_helper.submit_acoustid_fingerprints.call_count, 3)
for f in files:
self.assertTrue(self.acoustidmanager.is_submitted(f))
def test_submit_multi_batch_failure(self):
self.mock_api_helper.submit_acoustid_fingerprints = Mock(wraps=mock_fail_submission)
files = self._add_unsubmitted_files(int(AcoustIDManager.MAX_PAYLOAD / FINGERPRINT_SIZE) * 2)
self.acoustidmanager.submit()
self.assertEqual(self.mock_api_helper.submit_acoustid_fingerprints.call_count, 8)
for f in files:
self.assertFalse(self.acoustidmanager.is_submitted(f))
class SubmissionTest(PicardTestCase):
def test_init(self):
fingerprint = 'abc'
duration = 42
recordingid = 'rec1'
metadata = Metadata({
'musicip_puid': 'puid1'
})
submission = Submission(fingerprint, duration, recordingid, metadata)
self.assertEqual(fingerprint, submission.fingerprint)
self.assertEqual(duration, submission.duration)
self.assertEqual(recordingid, submission.recordingid)
self.assertEqual(recordingid, submission.orig_recordingid)
self.assertEqual(metadata, submission.metadata)
self.assertEqual(metadata['musicip_puid'], submission.puid)
self.assertEqual(0, submission.attempts)
def test_bool(self):
self.assertTrue(bool(Submission('foo', 1)))
self.assertTrue(bool(Submission('foo', 0)))
self.assertFalse(bool(Submission('foo', None)))
self.assertFalse(bool(Submission(None, 1)))
self.assertFalse(bool(Submission('', 1)))
def test_valid_duration(self):
duration_s = 342
duration_ms = duration_s * 1000
metadata = Metadata()
submission = Submission('abc', duration_s, metadata=metadata)
self.assertFalse(submission.valid_duration)
metadata.length = duration_ms
self.assertTrue(submission.valid_duration)
metadata.length = duration_ms + FINGERPRINT_MAX_ALLOWED_LENGTH_DIFF_MS
self.assertTrue(submission.valid_duration)
metadata.length = duration_ms - FINGERPRINT_MAX_ALLOWED_LENGTH_DIFF_MS
self.assertTrue(submission.valid_duration)
metadata.length = duration_ms + 1 + FINGERPRINT_MAX_ALLOWED_LENGTH_DIFF_MS
self.assertFalse(submission.valid_duration)
metadata.length = duration_ms - 1 - FINGERPRINT_MAX_ALLOWED_LENGTH_DIFF_MS
self.assertFalse(submission.valid_duration)
def test_valid_duration_no_metadata(self):
submission = Submission('abc', 342)
self.assertTrue(submission.valid_duration)
def test_init_no_metadata(self):
submission = Submission('abc', 42)
self.assertIsNone(submission.metadata)
self.assertEqual('', submission.puid)
def test_is_submitted_no_recording_id(self):
submission = Submission('abc', 42)
self.assertTrue(submission.is_submitted)
submission.recordingid = 'rec1'
self.assertFalse(submission.is_submitted)
def test_is_submitted_move_recording_id(self):
submission = Submission('abc', 42, recordingid='rec1')
self.assertTrue(submission.is_submitted)
submission.recordingid = 'rec2'
self.assertFalse(submission.is_submitted)
def test_args_with_mbid(self):
submission = Submission('abc', 42, recordingid='rec1')
expected = {
'fingerprint': 'abc',
'duration': '42',
'mbid': 'rec1',
}
self.assertEqual(expected, submission.args)
def test_args_with_mbid_with_puid(self):
metadata = Metadata(
musicip_puid='p1'
)
metadata.length = 42000
submission = Submission('abc', 42, recordingid='rec1', metadata=metadata)
expected = {
'fingerprint': 'abc',
'duration': '42',
'mbid': 'rec1',
'puid': 'p1'
}
self.assertEqual(expected, submission.args)
def test_args_with_invalid_duration(self):
metadata = Metadata({
'title': 'The Track',
'artist': 'The Artist',
'album': 'The Album',
'albumartist': 'The Album Artist',
'tracknumber': '4',
'discnumber': '2',
'date': '2022-01-22',
})
metadata.length = 500000
submission = Submission('abc', 42, recordingid='rec1', metadata=metadata)
expected = {
'fingerprint': 'abc',
'duration': '42',
'track': metadata['title'],
'artist': metadata['artist'],
'album': metadata['album'],
'albumartist': metadata['albumartist'],
'trackno': metadata['tracknumber'],
'discno': metadata['discnumber'],
'year': '2022',
}
self.assertEqual(expected, submission.args)
def test_args_without_mbid(self):
metadata = Metadata({
'title': 'The Track',
'artist': 'The Artist',
'album': 'The Album',
'albumartist': 'The Album Artist',
'tracknumber': '4',
'discnumber': '2',
'date': '2022-01-22',
})
metadata.length = 42000
submission = Submission('abc', 42, recordingid=None, metadata=metadata)
expected = {
'fingerprint': 'abc',
'duration': '42',
'track': metadata['title'],
'artist': metadata['artist'],
'album': metadata['album'],
'albumartist': metadata['albumartist'],
'trackno': metadata['tracknumber'],
'discno': metadata['discnumber'],
'year': '2022',
}
self.assertEqual(expected, submission.args)
def test_args_year(self):
metadata = Metadata({
'year': '2022',
})
metadata.length = 500000
submission = Submission('abc', 42, recordingid='rec1', metadata=metadata)
args = submission.args
self.assertEqual('2022', args['year'])
def test_args_invalid_year(self):
metadata = Metadata({
'year': 'NaN',
})
metadata.length = 500000
submission = Submission('abc', 42, recordingid='rec1', metadata=metadata)
self.assertNotIn('year', submission.args)
def test_len_mbid_puid(self):
fingerprint = 'abc' * 30
puid = 'p1'
recordingid = 'rec1'
duration = 42
metadata = Metadata(
musicip_puid=puid
)
metadata.length = 42000
submission = Submission(fingerprint, 42, recordingid=recordingid, metadata=metadata)
expected_min_length = len('&fingerprint=%s&duration=%s&mbid=%s&puid=%s' % (fingerprint, duration, recordingid, puid))
self.assertGreater(len(submission), expected_min_length)
def test_len_no_mbid(self):
metadata = Metadata({
'title': 'The Track',
'artist': 'The Artist',
'album': 'The Album',
'albumartist': 'The Album Artist',
'tracknumber': '4',
'discnumber': '2',
'date': '2022-01-22',
})
metadata.length = 500000
submission = Submission('abc', 42, recordingid='rec1', metadata=metadata)
expected_args = {
'fingerprint': 'abc',
'duration': '42',
'track': metadata['title'],
'artist': metadata['artist'],
'album': metadata['album'],
'albumartist': metadata['albumartist'],
'trackno': metadata['tracknumber'],
'discno': metadata['discnumber'],
'year': '2022',
}
expected_min_length = len('&'.join(('='.join([k, v]) for k, v in expected_args.items())))
self.assertGreater(len(submission), expected_min_length)
| 12,998
|
Python
|
.py
| 295
| 35.4
| 125
| 0.646292
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,867
|
test_disc_eaclog.py
|
metabrainz_picard/test/test_disc_eaclog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 Laurent Monin
# Copyright (C) 2022, 2024 Philipp Wolfer
# Copyright (C) 2022 Jeffrey Bosboom
#
# This program is free software; you can redistribute it and/or
# modify 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.
from typing import Iterator
import unittest
from test.picardtestcase import (
PicardTestCase,
get_test_data_path,
)
from picard.disc.eaclog import (
filter_toc_entries,
toc_from_file,
)
from picard.disc.utils import (
NotSupportedTOCError,
TocEntry,
)
from picard.util import detect as charset_detect
test_log = (
'TEST LOG',
' Track | Start | Length | Start sector | End sector',
'---------------------------------------------------------',
' 1 | 0:00.00 | 5:32.14 | 0 | 24913',
' 2 | 5:32.14 | 4:07.22 | 24914 | 43460',
' 3 | 9:39.36 | 3:50.29 | 43461 | 60739',
'',
'foo',
)
test_entries = [
TocEntry(1, 0, 24913),
TocEntry(2, 24914, 43460),
TocEntry(3, 43461, 60739),
]
class TestFilterTocEntries(PicardTestCase):
def test_filter_toc_entries(self):
result = filter_toc_entries(iter(test_log))
self.assertTrue(isinstance(result, Iterator))
entries = list(result)
self.assertEqual(test_entries, entries)
class TestTocFromFile(PicardTestCase):
def _test_toc_from_file(self, logfile):
test_log = get_test_data_path(logfile)
toc = toc_from_file(test_log)
self.assertEqual((1, 8, 149323, 150, 25064, 43611, 60890, 83090, 100000, 115057, 135558), toc)
@unittest.skipUnless(charset_detect, "test requires charset_normalizer or chardet package")
def test_toc_from_file_eac_windows1251(self):
self._test_toc_from_file('eac-windows1251.log')
def test_toc_from_file_eac_utf8(self):
self._test_toc_from_file('eac-utf8.log')
def test_toc_from_file_eac_utf16le(self):
self._test_toc_from_file('eac-utf16le.log')
def test_toc_from_file_xld(self):
self._test_toc_from_file('xld.log')
def test_toc_from_file_freac(self):
test_log = get_test_data_path('freac.log')
toc = toc_from_file(test_log)
self.assertEqual((1, 10, 280995, 150, 27732, 54992, 82825, 108837, 125742, 155160, 181292, 213715, 245750), toc)
def test_toc_from_file_with_datatrack(self):
test_log = get_test_data_path('eac-datatrack.log')
toc = toc_from_file(test_log)
self.assertEqual((1, 8, 178288, 150, 20575, 42320, 62106, 78432, 94973, 109750, 130111), toc)
def test_toc_from_file_with_datatrack_freac(self):
test_log = get_test_data_path('freac-datatrack.log')
toc = toc_from_file(test_log)
self.assertEqual((1, 13, 218150, 150, 15014, 33313, 49023, 65602, 81316, 102381, 116294, 133820, 151293, 168952, 190187, 203916), toc)
def test_toc_from_empty_file(self):
test_log = get_test_data_path('eac-empty.log')
with self.assertRaises(NotSupportedTOCError):
toc_from_file(test_log)
| 3,710
|
Python
|
.py
| 87
| 37.954023
| 142
| 0.670738
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,868
|
test_metadata.py
|
metabrainz_picard/test/test_metadata.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Sophist-UK
# Copyright (C) 2018, 2020 Wieland Hoffmann
# Copyright (C) 2018-2021 Laurent Monin
# Copyright (C) 2018-2021, 2023 Philipp Wolfer
# Copyright (C) 2020 dukeyin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import (
PicardTestCase,
create_fake_png,
load_test_json,
)
from test.test_coverart_image import create_image
from picard.acoustid.json_helpers import (
parse_recording as acoustid_parse_recording,
)
from picard.cluster import CLUSTER_COMPARISON_WEIGHTS
from picard.coverart.image import CoverArtImage
from picard.file import FILE_COMPARISON_WEIGHTS
from picard.mbjson import (
release_to_metadata,
track_to_metadata,
)
from picard.metadata import (
MULTI_VALUED_JOINER,
Metadata,
MultiMetadataProxy,
trackcount_score,
weights_from_preferred_countries,
weights_from_preferred_formats,
weights_from_release_type_scores,
)
from picard.track import Track
from picard.util.imagelist import ImageList
from picard.util.tags import PRESERVED_TAGS
settings = {
'write_id3v23': False,
'id3v23_join_with': '/',
'preferred_release_countries': [],
'preferred_release_formats': [],
'standardize_artists': False,
'standardize_instruments': False,
'translate_artist_names': False,
'release_ars': True,
'release_type_scores': [
('Album', 1.0),
('Other', 1.0),
],
}
class CommonTests:
class CommonMetadataTestCase(PicardTestCase):
original = None
tags = []
def setUp(self):
super().setUp()
self.set_config_values(settings)
self.metadata = self.get_metadata_object()
self.metadata.length = 242
self.metadata["single1"] = "single1-value"
self.metadata.add_unique("single2", "single2-value")
self.metadata.add_unique("single2", "single2-value")
self.multi1 = ["multi1-value1", "multi1-value1"]
self.metadata.add("multi1", self.multi1[0])
self.metadata.add("multi1", self.multi1[1])
self.multi2 = ["multi2-value1", "multi2-value2"]
self.metadata["multi2"] = self.multi2
self.multi3 = ["multi3-value1", "multi3-value2"]
self.metadata.set("multi3", self.multi3)
self.metadata["~hidden"] = "hidden-value"
self.metadata_d1 = Metadata({'a': 'b', 'c': 2, 'd': ['x', 'y'], 'x': ''})
self.metadata_d2 = Metadata({'a': 'b', 'c': 2, 'd': ['x', 'y'], 'x': 'z'})
self.metadata_d3 = Metadata({'c': 3, 'd': ['u', 'w'], 'x': 'p'})
@staticmethod
def get_metadata_object():
pass
def tearDown(self):
pass
def test_metadata_setitem(self):
self.assertEqual(["single1-value"], self.metadata.getraw("single1"))
self.assertEqual(["single2-value"], self.metadata.getraw("single2"))
self.assertEqual(self.multi1, self.metadata.getraw("multi1"))
self.assertEqual(self.multi2, self.metadata.getraw("multi2"))
self.assertEqual(self.multi3, self.metadata.getraw("multi3"))
self.assertEqual(["hidden-value"], self.metadata.getraw("~hidden"))
def test_metadata_set_all_values_as_string(self):
for val in (0, 2, True):
str_val = str(val)
self.metadata.set('val1', val)
self.assertEqual([str_val], self.metadata.getraw("val1"))
self.metadata['val2'] = val
self.assertEqual([str_val], self.metadata.getraw("val2"))
del self.metadata['val3']
self.metadata.add('val3', val)
self.assertEqual([str_val], self.metadata.getraw("val3"))
del self.metadata['val4']
self.metadata.add_unique('val4', val)
self.assertEqual([str_val], self.metadata.getraw("val4"))
def test_metadata_get(self):
self.assertEqual("single1-value", self.metadata["single1"])
self.assertEqual("single1-value", self.metadata.get("single1"))
self.assertEqual(["single1-value"], self.metadata.getall("single1"))
self.assertEqual(["single1-value"], self.metadata.getraw("single1"))
self.assertEqual(MULTI_VALUED_JOINER.join(self.multi1), self.metadata["multi1"])
self.assertEqual(MULTI_VALUED_JOINER.join(self.multi1), self.metadata.get("multi1"))
self.assertEqual(self.multi1, self.metadata.getall("multi1"))
self.assertEqual(self.multi1, self.metadata.getraw("multi1"))
self.assertEqual("", self.metadata["nonexistent"])
self.assertEqual(None, self.metadata.get("nonexistent"))
self.assertEqual([], self.metadata.getall("nonexistent"))
self.assertRaises(KeyError, self.metadata.getraw, "nonexistent")
self.assertEqual(self.metadata._store.items(), self.metadata.rawitems())
metadata_items = [(x, z) for (x, y) in self.metadata.rawitems() for z in y]
self.assertEqual(metadata_items, list(self.metadata.items()))
def test_metadata_unset(self):
self.metadata.unset("single1")
self.assertNotIn("single1", self.metadata)
self.assertNotIn("single1", self.metadata.deleted_tags)
self.metadata.unset('unknown_tag')
def test_metadata_pop(self):
self.metadata.pop("single1")
self.assertNotIn("single1", self.metadata)
self.assertIn("single1", self.metadata.deleted_tags)
self.metadata.pop('unknown_tag')
def test_metadata_delete(self):
del self.metadata["single1"]
self.assertNotIn("single1", self.metadata)
self.assertIn("single1", self.metadata.deleted_tags)
def test_metadata_legacy_delete(self):
self.metadata.delete("single1")
self.assertNotIn("single1", self.metadata)
self.assertIn("single1", self.metadata.deleted_tags)
def test_metadata_implicit_delete(self):
self.metadata["single2"] = ""
self.assertNotIn("single2", self.metadata)
self.assertIn("single2", self.metadata.deleted_tags)
self.metadata["unknown"] = ""
self.assertNotIn("unknown", self.metadata)
self.assertNotIn("unknown", self.metadata.deleted_tags)
def test_metadata_undelete(self):
self.metadata.delete("single1")
self.assertNotIn("single1", self.metadata)
self.assertIn("single1", self.metadata.deleted_tags)
self.metadata["single1"] = "value1"
self.assertIn("single1", self.metadata)
self.assertNotIn("single1", self.metadata.deleted_tags)
def test_normalize_tag(self):
self.assertEqual('sometag', Metadata.normalize_tag('sometag'))
self.assertEqual('sometag', Metadata.normalize_tag('sometag:'))
self.assertEqual('sometag', Metadata.normalize_tag('sometag::'))
self.assertEqual('sometag:desc', Metadata.normalize_tag('sometag:desc'))
def test_metadata_tag_trailing_colon(self):
self.metadata['tag:'] = 'Foo'
self.assertIn('tag', self.metadata)
self.assertIn('tag:', self.metadata)
self.assertEqual('Foo', self.metadata['tag'])
self.assertEqual('Foo', self.metadata['tag:'])
del self.metadata['tag']
self.assertNotIn('tag', self.metadata)
self.assertNotIn('tag:', self.metadata)
def test_metadata_copy(self):
m = Metadata()
m["old"] = "old-value"
self.metadata.delete("single1")
m.copy(self.metadata)
self.assertEqual(self.metadata._store, m._store)
self.assertEqual(self.metadata.deleted_tags, m.deleted_tags)
self.assertEqual(self.metadata.length, m.length)
self.assertEqual(self.metadata.images, m.images)
def test_metadata_copy_without_images(self):
m = Metadata()
m.copy(self.metadata, copy_images=False)
self.assertEqual(self.metadata._store, m._store)
self.assertEqual(self.metadata.deleted_tags, m.deleted_tags)
self.assertEqual(self.metadata.length, m.length)
self.assertEqual(ImageList(), m.images)
def test_metadata_init_with_existing_metadata(self):
self.metadata.delete("single1")
cover = CoverArtImage(url='file://file1', data=create_fake_png(b'a'))
self.metadata.images.append(cover)
m = Metadata(self.metadata)
self.assertEqual(self.metadata.length, m.length)
self.assertEqual(self.metadata.deleted_tags, m.deleted_tags)
self.assertEqual(self.metadata.images, m.images)
self.assertEqual(self.metadata._store, m._store)
def test_metadata_update(self):
m = Metadata()
m["old"] = "old-value"
self.metadata.delete("single1")
cover = CoverArtImage(url='file://file1', data=create_fake_png(b'a'))
self.metadata.images.append(cover)
m.update(self.metadata)
self.assertIn("old", m)
self.assertNotIn("single1", m)
self.assertIn("single1", m.deleted_tags)
self.assertEqual("single2-value", m["single2"])
self.assertEqual(self.metadata.length, m.length)
self.assertEqual(self.metadata.deleted_tags, m.deleted_tags)
self.assertEqual(self.metadata.images, m.images)
self.metadata["old"] = "old-value"
self.assertEqual(self.metadata._store, m._store)
def test_metadata_diff(self):
m1 = Metadata({
"foo1": "bar1",
"foo2": "bar2",
"foo3": "bar3",
})
m2 = Metadata(m1)
m1["foo1"] = "baz"
del m1["foo2"]
diff = m1.diff(m2)
self.assertEqual({"foo1": "baz"}, diff)
self.assertEqual(set(["foo2"]), diff.deleted_tags)
def test_metadata_clear(self):
self.metadata.clear()
self.assertEqual(0, len(self.metadata))
def test_metadata_clear_deleted(self):
self.metadata.delete("single1")
self.assertIn("single1", self.metadata.deleted_tags)
self.metadata.clear_deleted()
self.assertNotIn("single1", self.metadata.deleted_tags)
def test_metadata_applyfunc(self):
def func(x):
return x[1:]
self.metadata.apply_func(func)
self.assertEqual("ingle1-value", self.metadata["single1"])
self.assertEqual("ingle1-value", self.metadata.get("single1"))
self.assertEqual(["ingle1-value"], self.metadata.getall("single1"))
self.assertEqual(MULTI_VALUED_JOINER.join(map(func, self.multi1)), self.metadata["multi1"])
self.assertEqual(MULTI_VALUED_JOINER.join(map(func, self.multi1)), self.metadata.get("multi1"))
self.assertEqual(list(map(func, self.multi1)), self.metadata.getall("multi1"))
def test_metadata_applyfunc_preserve_tags(self):
self.assertTrue(len(PRESERVED_TAGS) > 0)
m = Metadata()
m[PRESERVED_TAGS[0]] = 'value1'
m['not_preserved'] = 'value2'
def func(x):
return x[1:]
m.apply_func(func)
self.assertEqual("value1", m[PRESERVED_TAGS[0]])
self.assertEqual("alue2", m['not_preserved'])
def test_metadata_applyfunc_delete_tags(self):
def func(x):
return None
metadata = Metadata(self.metadata)
metadata.apply_func(func)
self.assertEqual(0, len(metadata.rawitems()))
self.assertEqual(self.metadata.keys(), metadata.deleted_tags)
def test_length_score(self):
results = (
(20000, 0, 0.333333333333),
(20000, 10000, 0.666666666667),
(20000, 20000, 1.0),
(20000, 30000, 0.666666666667),
(20000, 40000, 0.333333333333),
(20000, 50000, 0.0),
(20000, None, 0.0),
(None, 2000, 0.0),
(None, None, 0.0),
)
for (a, b, expected) in results:
actual = Metadata.length_score(a, b)
self.assertAlmostEqual(expected, actual,
msg="a={a}, b={b}".format(a=a, b=b))
def test_compare_is_equal(self):
m1 = Metadata()
m1["title"] = "title1"
m1["tracknumber"] = "2"
m1.length = 360
m2 = Metadata()
m2["title"] = "title1"
m2["tracknumber"] = "2"
m2.length = 360
self.assertEqual(m1.compare(m2), m2.compare(m1))
self.assertEqual(m1.compare(m2), 1)
def test_compare_with_ignored(self):
m1 = Metadata()
m1["title"] = "title1"
m1["tracknumber"] = "2"
m1.length = 360
m2 = Metadata()
m2["title"] = "title1"
m2["tracknumber"] = "3"
m2.length = 300
self.assertNotEqual(m1.compare(m2), 1)
self.assertEqual(m1.compare(m2, ignored=['tracknumber', '~length']), 1)
def test_compare_lengths(self):
m1 = Metadata()
m1.length = 360
m2 = Metadata()
m2.length = 300
self.assertAlmostEqual(m1.compare(m2), 0.998)
def test_compare_tracknumber_difference(self):
m1 = Metadata()
m1["tracknumber"] = "1"
m2 = Metadata()
m2["tracknumber"] = "2"
m3 = Metadata()
m3["tracknumber"] = "2"
self.assertEqual(m1.compare(m2), 0)
self.assertEqual(m2.compare(m3), 1)
def test_compare_discnumber_difference(self):
m1 = Metadata()
m1["discnumber"] = "1"
m2 = Metadata()
m2["discnumber"] = "2"
m3 = Metadata()
m3["discnumber"] = "2"
self.assertEqual(m1.compare(m2), 0)
self.assertEqual(m2.compare(m3), 1)
def test_compare_deleted(self):
m1 = Metadata()
m1["artist"] = "TheArtist"
m1["title"] = "title1"
m2 = Metadata()
m2["artist"] = "TheArtist"
m2.delete("title")
self.assertTrue(m1.compare(m2) < 1)
def test_strip_whitespace(self):
m1 = Metadata()
m1["artist"] = " TheArtist "
m1["title"] = "\t\u00A0 tit le1 \r\n"
m1["genre"] = " \t"
m1.strip_whitespace()
self.assertEqual(m1["artist"], "TheArtist")
self.assertEqual(m1["title"], "tit le1")
def test_metadata_mapping_init(self):
d = {'a': 'b', 'c': 2, 'd': ['x', 'y'], 'x': '', 'z': {'u', 'w'}}
deleted_tags = set('c')
m = Metadata(d, deleted_tags=deleted_tags, length=1234)
self.assertIn('a', m)
self.assertEqual(m.getraw('a'), ['b'])
self.assertEqual(m['d'], MULTI_VALUED_JOINER.join(d['d']))
self.assertNotIn('c', m)
self.assertNotIn('length', m)
self.assertIn('c', m.deleted_tags)
self.assertEqual(m.length, 1234)
def test_metadata_mapping_init_zero(self):
m = Metadata(tag1='a', tag2=0, tag3='', tag4=None)
m['tag5'] = 0
m['tag1'] = ''
self.assertIn('tag1', m.deleted_tags)
self.assertEqual(m['tag2'], '0')
self.assertNotIn('tag3', m)
self.assertNotIn('tag4', m)
self.assertEqual(m['tag5'], '0')
def test_metadata_mapping_del(self):
m = self.metadata_d1
self.assertEqual(m.getraw('a'), ['b'])
self.assertNotIn('a', m.deleted_tags)
self.assertNotIn('x', m.deleted_tags)
self.assertRaises(KeyError, m.getraw, 'x')
del m['a']
self.assertRaises(KeyError, m.getraw, 'a')
self.assertIn('a', m.deleted_tags)
# NOTE: historic behavior of Metadata.delete()
# an attempt to delete an non-existing tag, will add it to the list
# of deleted tags
# so this will not raise a KeyError
# as is it differs from dict or even defaultdict behavior
del m['unknown']
self.assertIn('unknown', m.deleted_tags)
def test_metadata_mapping_iter(self):
self.assertEqual(set(self.metadata_d1), {'a', 'c', 'd'})
def test_metadata_mapping_keys(self):
self.assertEqual(set(self.metadata_d1.keys()), {'a', 'c', 'd'})
def test_metadata_mapping_values(self):
self.assertEqual(set(self.metadata_d1.values()), {'b', '2', 'x; y'})
def test_metadata_mapping_len(self):
m = self.metadata_d1
self.assertEqual(len(m), 3)
del m['x']
self.assertEqual(len(m), 3)
del m['c']
self.assertEqual(len(m), 2)
def _check_mapping_update(self, m):
self.assertEqual(m['a'], 'b')
self.assertEqual(m['c'], '3')
self.assertEqual(m.getraw('d'), ['u', 'w'])
self.assertEqual(m['x'], '')
self.assertIn('x', m.deleted_tags)
def test_metadata_mapping_update(self):
# update from Metadata
m = self.metadata_d2
m2 = self.metadata_d3
del m2['x']
m.update(m2)
self._check_mapping_update(m)
def test_metadata_mapping_update_dict(self):
# update from dict
m = self.metadata_d2
d2 = {'c': 3, 'd': ['u', 'w'], 'x': ''}
m.update(d2)
self._check_mapping_update(m)
def test_metadata_mapping_update_tuple(self):
# update from tuple
m = self.metadata_d2
d2 = (('c', 3), ('d', ['u', 'w']), ('x', ''))
m.update(d2)
self._check_mapping_update(m)
def test_metadata_mapping_update_dictlike(self):
# update from kwargs
m = self.metadata_d2
m.update(c=3, d=['u', 'w'], x='')
self._check_mapping_update(m)
def test_metadata_mapping_update_noparam(self):
# update without parameter
m = self.metadata_d2
self.assertRaises(TypeError, m.update)
self.assertEqual(m['a'], 'b')
def test_metadata_mapping_update_intparam(self):
# update without parameter
m = self.metadata_d2
self.assertRaises(TypeError, m.update, 123)
def test_metadata_mapping_update_strparam(self):
# update without parameter
m = self.metadata_d2
self.assertRaises(ValueError, m.update, 'abc')
def test_metadata_mapping_update_kw(self):
m = Metadata(tag1='a', tag2='b')
m.update(tag1='c')
self.assertEqual(m['tag1'], 'c')
self.assertEqual(m['tag2'], 'b')
m.update(tag2='')
self.assertIn('tag2', m.deleted_tags)
def test_metadata_mapping_update_kw_del(self):
m = Metadata(tag1='a', tag2='b')
del m['tag1']
m2 = Metadata(tag1='c', tag2='d')
del m2['tag2']
m.update(m2)
self.assertEqual(m['tag1'], 'c')
self.assertNotIn('tag2', m)
self.assertNotIn('tag1', m.deleted_tags)
self.assertIn('tag2', m.deleted_tags)
def test_metadata_mapping_images(self):
image1 = create_image(b'A', comment='A')
image2 = create_image(b'B', comment='B')
m1 = Metadata(a='b', length=1234, images=[image1])
self.assertEqual(m1.images[0], image1)
self.assertEqual(len(m1), 2) # one tag, one image
m1.images.append(image2)
self.assertEqual(m1.images[1], image2)
m1.images.pop(0)
self.assertEqual(m1.images[0], image2)
m2 = Metadata(a='c', length=4567, images=[image1])
m1.update(m2)
self.assertEqual(m1.images[0], image1)
m1.images.pop(0)
self.assertEqual(len(m1), 1) # one tag, zero image
self.assertFalse(m1.images)
def test_metadata_mapping_iterable(self):
m = Metadata(tag_tuple=('a', 0))
m['tag_set'] = {'c', 'd'}
m['tag_dict'] = {'e': 1, 'f': 2}
m['tag_str'] = 'gh'
self.assertIn('0', m.getraw('tag_tuple'))
self.assertIn('c', m.getraw('tag_set'))
self.assertIn('e', m.getraw('tag_dict'))
self.assertIn('gh', m.getraw('tag_str'))
def test_compare_to_release(self):
release = load_test_json('release.json')
metadata = Metadata()
release_to_metadata(release, metadata)
match_ = metadata.compare_to_release(release, CLUSTER_COMPARISON_WEIGHTS)
self.assertEqual(1.0, match_.similarity)
self.assertEqual(release, match_.release)
def test_compare_to_release_with_score(self):
release = load_test_json('release.json')
metadata = Metadata()
release_to_metadata(release, metadata)
for score, sim in ((42, 0.42), ('42', 0.42), ('foo', 1.0), (None, 1.0)):
release['score'] = score
match_ = metadata.compare_to_release(release, CLUSTER_COMPARISON_WEIGHTS)
self.assertEqual(sim, match_.similarity)
def test_compare_to_release_parts_totaltracks(self):
release = load_test_json('release_multidisc.json')
metadata = Metadata()
weights = {"totaltracks": 30}
release_to_metadata(release, metadata)
for totaltracks, sim in ((4, 1.0), (3, 1.0), (2, 0.3), (5, 0.0)):
metadata['totaltracks'] = totaltracks
parts = metadata.compare_to_release_parts(release, weights)
self.assertIn((sim, 30), parts)
def test_compare_to_release_parts_totalalbumtracks(self):
release = load_test_json('release_multidisc.json')
metadata = Metadata()
weights = {"totalalbumtracks": 30}
release_to_metadata(release, metadata)
for totaltracks, sim in ((7, 1.0), (6, 0.3), (8, 0.0)):
metadata['~totalalbumtracks'] = totaltracks
parts = metadata.compare_to_release_parts(release, weights)
self.assertIn((sim, 30), parts)
def test_compare_to_release_parts_totalalbumtracks_totaltracks_fallback(self):
release = load_test_json('release_multidisc.json')
metadata = Metadata()
weights = {"totalalbumtracks": 30}
release_to_metadata(release, metadata)
for totaltracks, sim in ((7, 1.0), (6, 0.3), (8, 0.0)):
metadata['totaltracks'] = totaltracks
parts = metadata.compare_to_release_parts(release, weights)
self.assertIn((sim, 30), parts)
def test_trackcount_score(self):
self.assertEqual(1.0, trackcount_score(5, 5))
self.assertEqual(0.0, trackcount_score(6, 5))
self.assertEqual(0.3, trackcount_score(4, 5))
def test_weights_from_release_type_scores(self):
release = load_test_json('release.json')
parts = []
weights_from_release_type_scores(parts, release, {'Album': 0.75}, 666)
self.assertEqual(
parts[0],
(0.75, 666)
)
weights_from_release_type_scores(parts, release, {}, 666)
self.assertEqual(
parts[1],
(0.5, 666)
)
def test_weights_from_release_type_scores_no_type(self):
release = load_test_json('release_no_type.json')
parts = []
weights_from_release_type_scores(parts, release, {'Other': 0.75}, 123)
self.assertEqual(
parts[0],
(0.75, 123)
)
weights_from_release_type_scores(parts, release, {}, 123)
self.assertEqual(
parts[1],
(0.5, 123)
)
def test_preferred_countries(self):
release = load_test_json('release.json')
parts = []
weights_from_preferred_countries(parts, release, [], 666)
self.assertFalse(parts)
weights_from_preferred_countries(parts, release, ['FR'], 666)
self.assertEqual(parts[0], (0.0, 666))
weights_from_preferred_countries(parts, release, ['GB'], 666)
self.assertEqual(parts[1], (1.0, 666))
def test_preferred_formats(self):
release = load_test_json('release.json')
parts = []
weights_from_preferred_formats(parts, release, [], 777)
self.assertFalse(parts)
weights_from_preferred_formats(parts, release, ['Digital Media'], 777)
self.assertEqual(parts[0], (0.0, 777))
weights_from_preferred_formats(parts, release, ['12" Vinyl'], 777)
self.assertEqual(parts[1], (1.0, 777))
def test_compare_to_track(self):
track_json = load_test_json('track.json')
track = Track(track_json['id'])
track_to_metadata(track_json, track)
match_ = track.metadata.compare_to_track(track_json, FILE_COMPARISON_WEIGHTS)
self.assertEqual(1.0, match_.similarity)
self.assertEqual(track_json, match_.track)
def test_compare_to_track_with_score(self):
track_json = load_test_json('track.json')
track = Track(track_json['id'])
track_to_metadata(track_json, track)
for score, sim in ((42, 0.42), ('42', 0.42), ('foo', 1.0), (None, 1.0)):
track_json['score'] = score
match_ = track.metadata.compare_to_track(track_json, FILE_COMPARISON_WEIGHTS)
self.assertEqual(sim, match_.similarity)
def test_compare_to_track_is_video(self):
recording = load_test_json('recording_video_null.json')
m = Metadata()
match_ = m.compare_to_track(recording, {'isvideo': 1})
self.assertEqual(1.0, match_.similarity)
m['~video'] = '1'
match_ = m.compare_to_track(recording, {'isvideo': 1})
self.assertEqual(0.0, match_.similarity)
recording['video'] = True
match_ = m.compare_to_track(recording, {'isvideo': 1})
self.assertEqual(1.0, match_.similarity)
def test_compare_to_track_full(self):
recording = load_test_json('recording_video_null.json')
m = Metadata({
'artist': 'Tim Green',
'release': 'Eastbound Silhouette',
'date': '2022',
'title': 'Lune',
'totaltracks': '6',
'albumartist': 'Tim Green',
'tracknumber': '4',
})
match_ = m.compare_to_track(recording, FILE_COMPARISON_WEIGHTS)
self.assertGreaterEqual(match_.similarity, 0.8)
self.assertEqual(recording, match_.track)
self.assertEqual(recording['releases'][0], match_.release)
def test_compare_to_track_without_releases(self):
self.set_config_values({
'release_type_scores': [('Compilation', 0.6), ('Other', 0.6)]
})
track_json = acoustid_parse_recording(load_test_json('acoustid.json'))
track = Track(track_json['id'])
track.metadata.update({
'album': 'x',
'artist': 'Ed Sheeran',
'title': 'Nina',
})
track.metadata.length = 225000
m1 = track.metadata.compare_to_track(track_json, FILE_COMPARISON_WEIGHTS)
del track_json['releases']
m2 = track.metadata.compare_to_track(track_json, FILE_COMPARISON_WEIGHTS)
self.assertGreater(m1.similarity, m2.similarity,
'Matching score for release with recordings must be higher then for release without')
class MetadataTest(CommonTests.CommonMetadataTestCase):
@staticmethod
def get_metadata_object():
return Metadata()
class MultiMetadataProxyAsMetadataTest(CommonTests.CommonMetadataTestCase):
@staticmethod
def get_metadata_object():
return MultiMetadataProxy(Metadata())
class MultiMetadataProxyTest(PicardTestCase):
def setUp(self):
super().setUp()
self.m1 = Metadata({
"key1": "m1.val1",
"key2": "m1.val2",
})
self.m2 = Metadata({
"key2": "m2.val2",
"key3": "m2.val3",
})
self.m3 = Metadata({
"key2": "m3.val2",
"key4": "m3.val4",
})
def test_get_attribute(self):
mp = MultiMetadataProxy(self.m1, self.m2, self.m3)
self.assertEqual(mp.deleted_tags, self.m1.deleted_tags)
def test_gettitem(self):
mp = MultiMetadataProxy(self.m1, self.m2, self.m3)
self.assertEqual("m1.val1", mp["key1"])
self.assertEqual("m1.val2", mp["key2"])
self.assertEqual("m2.val3", mp["key3"])
self.assertEqual("m3.val4", mp["key4"])
def test_settitem(self):
orig_m2 = Metadata(self.m2)
mp = MultiMetadataProxy(self.m1, self.m2, self.m3)
mp["key1"] = "foo1"
mp["key2"] = "foo2"
mp["key3"] = "foo3"
mp["key4"] = "foo4"
mp["key5"] = "foo5"
self.assertEqual("foo1", self.m1["key1"])
self.assertEqual("foo2", self.m1["key2"])
self.assertEqual("foo3", self.m1["key3"])
self.assertEqual("foo4", self.m1["key4"])
self.assertEqual("foo5", self.m1["key5"])
self.assertEqual(orig_m2, self.m2)
def test_delitem(self):
orig_m2 = Metadata(self.m2)
mp = MultiMetadataProxy(self.m1, self.m2, self.m3)
del mp["key2"]
del mp["key3"]
self.assertIn("key2", self.m1.deleted_tags)
self.assertIn("key3", self.m1.deleted_tags)
self.assertEqual(orig_m2, self.m2)
| 31,468
|
Python
|
.py
| 677
| 34.679468
| 116
| 0.571196
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,869
|
test_acoustid.py
|
metabrainz_picard/test/test_acoustid.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2019-2020, 2023 Philipp Wolfer
# Copyright (C) 2020 Ray Bouchard
# Copyright (C) 2020-2021 Laurent Monin
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Vladislav Karbovskii
#
# This program is free software; you can redistribute it and/or
# modify 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.
import json
import os
from test.picardtestcase import PicardTestCase
from picard.acoustid.json_helpers import (
parse_recording,
recording_has_metadata,
)
from picard.acoustid.recordings import (
Recording,
max_source_count,
parse_recording_map,
)
from picard.mbjson import recording_to_metadata
from picard.metadata import Metadata
from picard.track import Track
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"artist_locales": ['en'],
"translate_artist_names_script_exception": False,
}
class AcoustIDTest(PicardTestCase):
def setUp(self):
super().setUp()
self.init_test(self.filename)
def init_test(self, filename):
self.set_config_values(settings)
self.json_doc = None
with open(os.path.join('test', 'data', 'ws_data', filename), encoding='utf-8') as f:
self.json_doc = json.load(f)
class RecordingTest(AcoustIDTest):
filename = 'acoustid.json'
def test_recording(self):
parsed_recording = parse_recording(self.json_doc)
release = parsed_recording['releases'][0]
artist_credit = parsed_recording['artist-credit'][0]
self.assertEqual(parsed_recording['id'], '017830c1-d1cf-46f3-8801-aaaa0a930223')
self.assertEqual(parsed_recording['length'], 225000)
self.assertEqual(parsed_recording['title'], 'Nina')
self.assertEqual(release['media'], [{'format': 'CD', 'track-count': 12, 'position': 1, 'track': [{'position': 5, 'id': '16affcc3-9f34-48e5-88dc-68378c4cc208', 'number': 5}]}])
self.assertEqual(release['title'], 'x')
self.assertEqual(release['id'], 'a2b25883-306f-4a53-809a-a234737c209d')
self.assertEqual(release['release-group'], {
'id': 'c24e5416-cd2e-4cff-851b-5faa78db98a2',
'primary-type': 'Album',
'secondary-types': ['Compilation']
})
self.assertEqual(release['country'], 'XE')
self.assertEqual(release['date'], {'month': 6, 'day': 23, 'year': 2014})
self.assertEqual(release['medium-count'], 1)
self.assertEqual(release['track-count'], 12)
self.assertEqual(artist_credit['artist'], {'sort-name': 'Ed Sheeran',
'name': 'Ed Sheeran',
'id': 'b8a7c51f-362c-4dcb-a259-bc6e0095f0a6'})
self.assertEqual(artist_credit['name'], 'Ed Sheeran')
class NullRecordingTest(AcoustIDTest):
filename = 'acoustid_null.json'
def test_recording(self):
m = Metadata()
t = Track("1")
parsed_recording = parse_recording(self.json_doc)
recording_to_metadata(parsed_recording, m, t)
self.assertEqual(m, {})
class MaxSourceCountTest(PicardTestCase):
def test_max_source_count(self):
recordings = (
Recording({}, sources=5),
Recording({}, sources=13),
Recording({}, sources=12),
)
self.assertEqual(13, max_source_count(recordings))
def test_max_source_count_no_recordings(self):
self.assertEqual(1, max_source_count([]))
def test_max_source_count_smaller_1(self):
recordings = (
Recording({}, sources=0),
)
self.assertEqual(1, max_source_count(recordings))
class ParseRecordingMapTest(PicardTestCase):
def test_parse_recording_map(self):
recordings = {
"cb127606-8e3d-4dcf-9902-69c7a9b59bc9": {
"d12e0535-3b2f-4987-8b03-63d85ef57fdd": Recording({
"id": "d12e0535-3b2f-4987-8b03-63d85ef57fdd",
}),
"e8a313ee-b723-4b48-9395-6c8e026fc9e0": Recording(
{"id": "e8a313ee-b723-4b48-9395-6c8e026fc9e0"},
sources=4,
result_score=0.5,
),
}
}
expected = [
{
"id": "d12e0535-3b2f-4987-8b03-63d85ef57fdd",
"acoustid": "cb127606-8e3d-4dcf-9902-69c7a9b59bc9",
"score": 25,
"sources": 1,
},
{
"id": "e8a313ee-b723-4b48-9395-6c8e026fc9e0",
"acoustid": "cb127606-8e3d-4dcf-9902-69c7a9b59bc9",
"score": 50,
"sources": 4,
}
]
self.assertEqual(expected, list(parse_recording_map(recordings)))
class RecordingHasMetadataTest(PicardTestCase):
filename = 'acoustid_no_metadata.json'
def test_recording_has_metadata(self):
recording = {
'id': '8855169b-b148-4896-9ed3-a1065dc60cf4',
'sources': 94,
}
self.assertFalse(recording_has_metadata(recording))
recording['title'] = 'Foo'
self.assertTrue(recording_has_metadata(recording))
del recording['id']
self.assertFalse(recording_has_metadata(recording))
| 6,053
|
Python
|
.py
| 146
| 33.267123
| 183
| 0.63556
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,870
|
test_tagger_message_parsing.py
|
metabrainz_picard/test/test_tagger_message_parsing.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 skelly37
# Copyright (C) 2022 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.const.sys import IS_WIN
from picard.tagger import ParseItemsToLoad
class TestMessageParsing(PicardTestCase):
def test(self):
test_cases = {
"test_case.mp3",
"file:///home/picard/music/test.flac",
"mbid://recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94",
"https://musicbrainz.org/recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94",
"http://musicbrainz.org/recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94",
}
result = ParseItemsToLoad(test_cases)
self.assertSetEqual(result.files, {"test_case.mp3", "/home/picard/music/test.flac"}, "Files test")
self.assertSetEqual(result.mbids, {"recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94"}, "MBIDs test")
self.assertSetEqual(result.urls, {"recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94",
"recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94"}, "URLs test")
def test_bool_files_true(self):
test_cases = {
"test_case.mp3",
}
self.assertTrue(ParseItemsToLoad(test_cases))
def test_bool_mbids_true(self):
test_cases = {
"mbid://recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94",
}
self.assertTrue(ParseItemsToLoad(test_cases))
def test_bool_urls_true(self):
test_cases = {
"https://musicbrainz.org/recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94",
}
self.assertTrue(ParseItemsToLoad(test_cases))
def test_bool_invalid_false(self):
test_cases = {
"mbd://recording/7cd3782d-86dc-4dd1-8d9b-e37f9cbe6b94",
}
self.assertFalse(ParseItemsToLoad(test_cases))
def test_bool_empty_false(self):
test_cases = {}
self.assertFalse(ParseItemsToLoad(test_cases))
def test_windows_file_with_drive(self):
test_cases = {
"C:\\test_case.mp3",
}
if IS_WIN:
self.assertTrue(ParseItemsToLoad(test_cases))
else:
self.assertFalse(ParseItemsToLoad(test_cases))
| 2,949
|
Python
|
.py
| 68
| 36.676471
| 107
| 0.687108
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,871
|
test_coverart_utils.py
|
metabrainz_picard/test/test_coverart_utils.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2019, 2021 Philipp Wolfer
# Copyright (C) 2020 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.coverart.utils import (
image_type_as_id3_num,
image_type_from_id3_num,
translate_caa_type,
types_from_id3,
)
class CaaTypeTranslationTest(PicardTestCase):
def test_translating_unknown_types_returns_input(self):
testtype = "ThisIsAMadeUpCoverArtTypeName"
self.assertEqual(translate_caa_type(testtype), testtype)
class Id3TypeTranslationTest(PicardTestCase):
def test_image_type_from_id3_num(self):
self.assertEqual(image_type_from_id3_num(0), 'other')
self.assertEqual(image_type_from_id3_num(3), 'front')
self.assertEqual(image_type_from_id3_num(6), 'medium')
self.assertEqual(image_type_from_id3_num(9999), 'other')
def test_image_type_as_id3_num(self):
self.assertEqual(image_type_as_id3_num('other'), 0)
self.assertEqual(image_type_as_id3_num('front'), 3)
self.assertEqual(image_type_as_id3_num('medium'), 6)
self.assertEqual(image_type_as_id3_num('track'), 6)
self.assertEqual(image_type_as_id3_num('unknowntype'), 0)
def test_types_from_id3(self):
self.assertEqual(types_from_id3(0), ['other'])
self.assertEqual(types_from_id3(3), ['front'])
self.assertEqual(types_from_id3(6), ['medium'])
self.assertEqual(types_from_id3(9999), ['other'])
| 2,265
|
Python
|
.py
| 49
| 41.938776
| 80
| 0.726778
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,872
|
test_file.py
|
metabrainz_picard/test/test_file.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018-2022 Philipp Wolfer
# Copyright (C) 2019-2022 Laurent Monin
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Sophist-UK
#
# This program is free software; you can redistribute it and/or
# modify 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.
import os
import re
from types import GeneratorType
import unittest
from unittest.mock import MagicMock
from test.picardtestcase import PicardTestCase
from test.test_coverart_image import create_image
from picard import config
from picard.const.sys import (
IS_MACOS,
IS_WIN,
)
from picard.file import File
from picard.metadata import Metadata
from picard.util.tags import (
CALCULATED_TAGS,
FILE_INFO_TAGS,
)
class FileTest(PicardTestCase):
def setUp(self):
super().setUp()
self.tagger.acoustidmanager = MagicMock()
self.file = File('somepath/somefile.mp3')
self.set_config_values({
'save_acoustid_fingerprints': True,
})
def test_filename(self):
self.assertEqual('somepath/somefile.mp3', self.file.filename)
self.assertEqual('somefile.mp3', self.file.base_filename)
def test_tracknumber(self):
self.assertEqual(0, self.file.tracknumber)
self.file.metadata['tracknumber'] = '42'
self.assertEqual(42, self.file.tracknumber)
self.file.metadata['tracknumber'] = 'FOURTYTWO'
self.assertEqual(0, self.file.tracknumber)
def test_discnumber(self):
self.assertEqual(0, self.file.discnumber)
self.file.metadata['discnumber'] = '42'
self.assertEqual(42, self.file.discnumber)
self.file.metadata['discnumber'] = 'FOURTYTWO'
self.assertEqual(0, self.file.discnumber)
def test_set_acoustid_fingerprint(self):
fingerprint = 'foo'
length = 36
self.file.set_acoustid_fingerprint(fingerprint, length)
self.assertEqual(fingerprint, self.file.acoustid_fingerprint)
self.assertEqual(length, self.file.acoustid_length)
self.tagger.acoustidmanager.add.assert_called_with(self.file, None)
self.tagger.acoustidmanager.add.reset_mock()
self.file.set_acoustid_fingerprint(fingerprint, length)
self.tagger.acoustidmanager.add.assert_not_called()
self.tagger.acoustidmanager.remove.assert_not_called()
self.assertEqual(fingerprint, self.file.metadata['acoustid_fingerprint'])
def test_set_acoustid_fingerprint_no_length(self):
self.file.metadata.length = 42000
fingerprint = 'foo'
self.file.set_acoustid_fingerprint(fingerprint)
self.assertEqual(fingerprint, self.file.acoustid_fingerprint)
self.assertEqual(42, self.file.acoustid_length)
self.assertEqual(fingerprint, self.file.metadata['acoustid_fingerprint'])
def test_set_acoustid_fingerprint_unset(self):
self.file.acoustid_fingerprint = 'foo'
self.file.set_acoustid_fingerprint(None, 42)
self.tagger.acoustidmanager.add.assert_not_called()
self.tagger.acoustidmanager.remove.assert_called_with(self.file)
self.assertEqual(None, self.file.acoustid_fingerprint)
self.assertEqual(0, self.file.acoustid_length)
self.assertEqual('', self.file.metadata['acoustid_fingerprint'])
def format_specific_metadata(self):
values = ['foo', 'bar']
self.file.metadata['test'] = values
self.assertEqual(values, self.file.format_specific_metadata(self.file.metadata, 'test'))
def test_set_acoustid_fingerprint_no_save(self):
self.set_config_values({
'save_acoustid_fingerprints': False,
})
fingerprint = 'foo'
length = 36
self.file.set_acoustid_fingerprint(fingerprint, length)
self.assertEqual(fingerprint, self.file.acoustid_fingerprint)
self.assertEqual(length, self.file.acoustid_length)
self.assertEqual('', self.file.metadata['acoustid_fingerprint'])
class TestPreserveTimes(PicardTestCase):
def setUp(self):
super().setUp()
self.tmp_directory = self.mktmpdir()
filepath = os.path.join(self.tmp_directory, 'a.mp3')
self.file = File(filepath)
def _create_testfile(self):
# create a dummy file
with open(self.file.filename, 'w') as f:
f.write('xxx')
f.flush()
os.fsync(f.fileno())
def _modify_testfile(self):
# dummy file modification, append data to it
with open(self.file.filename, 'a') as f:
f.write('yyy')
f.flush()
os.fsync(f.fileno())
def _read_testfile(self):
with open(self.file.filename, 'r') as f:
return f.read()
def test_preserve_times(self):
self._create_testfile()
# test if times are preserved
(before_atime_ns, before_mtime_ns) = self.file._preserve_times(self.file.filename, self._modify_testfile)
# HERE an external access to the file is possible, modifying its access time
# read times again and compare with original
st = os.stat(self.file.filename)
(after_atime_ns, after_mtime_ns) = (st.st_atime_ns, st.st_mtime_ns)
# on macOS 10.14 and later os.utime only sets the times with second
# precision see https://tickets.metabrainz.org/browse/PICARD-1516.
# This also seems to depend on the Python build being used.
if IS_MACOS:
before_atime_ns //= 1000
before_mtime_ns //= 1000
after_atime_ns //= 1000
after_mtime_ns //= 1000
# modification times should be equal
self.assertEqual(before_mtime_ns, after_mtime_ns)
# access times may not be equal
# time difference should be positive and reasonably low (if no access in between, it should be 0)
delta = after_atime_ns - before_atime_ns
tolerance = 10**7 # 0.01 seconds
self.assertTrue(0 <= delta < tolerance, "0 <= %s < %s" % (delta, tolerance))
# ensure written data can be read back
# keep it at the end, we don't want to access file before time checks
self.assertEqual(self._read_testfile(), 'xxxyyy')
def test_preserve_times_nofile(self):
with self.assertRaises(self.file.PreserveTimesStatError):
self.file._preserve_times(self.file.filename,
self._modify_testfile)
with self.assertRaises(FileNotFoundError):
self._read_testfile()
def test_preserve_times_nofile_utime(self):
self._create_testfile()
def save():
os.remove(self.file.filename)
with self.assertRaises(self.file.PreserveTimesUtimeError):
self.file._preserve_times(self.file.filename, save)
class FakeMp3File(File):
EXTENSIONS = ['.mp3']
class FileNamingTest(PicardTestCase):
def setUp(self):
super().setUp()
self.file = File('/somepath/somefile.mp3')
self.set_config_values({
'ascii_filenames': False,
'clear_existing_tags': False,
'enabled_plugins': [],
'move_files_to': '/media/music',
'move_files': False,
'rename_files': False,
'windows_compatibility': True,
'win_compat_replacements': {},
'windows_long_paths': False,
'replace_spaces_with_underscores': False,
'replace_dir_separator': '_',
'file_renaming_scripts': {'test_id': {'script': '%album%/%title%'}},
'selected_file_naming_script_id': 'test_id',
})
self.metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
def test_make_filename_no_move_and_rename(self):
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(os.path.realpath(self.file.filename), filename)
def test_make_filename_rename_only(self):
config.setting['rename_files'] = True
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(os.path.realpath('/somepath/sometitle.mp3'), filename)
def test_make_filename_move_only(self):
config.setting['move_files'] = True
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(
os.path.realpath('/media/music/somealbum/somefile.mp3'),
filename)
def test_make_filename_move_and_rename(self):
config.setting['rename_files'] = True
config.setting['move_files'] = True
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(
os.path.realpath('/media/music/somealbum/sometitle.mp3'),
filename)
def test_make_filename_move_relative_path(self):
config.setting['move_files'] = True
config.setting['move_files_to'] = 'subdir'
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(
os.path.realpath('/somepath/subdir/somealbum/somefile.mp3'),
filename)
def test_make_filename_empty_script(self):
config.setting['rename_files'] = True
config.setting['file_renaming_scripts'] = {'test_id': {'script': '$noop()'}}
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(os.path.realpath('/somepath/somefile.mp3'), filename)
def test_make_filename_empty_basename(self):
config.setting['move_files'] = True
config.setting['rename_files'] = True
config.setting['file_renaming_scripts'] = {'test_id': {'script': '/somedir/$noop()'}}
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(os.path.realpath('/media/music/somedir/somefile.mp3'), filename)
def test_make_filename_no_extension(self):
config.setting['rename_files'] = True
file_ = FakeMp3File('/somepath/_')
filename = file_.make_filename(file_.filename, self.metadata)
self.assertEqual(os.path.realpath('/somepath/sometitle.mp3'), filename)
def test_make_filename_lowercase_extension(self):
config.setting['rename_files'] = True
file_ = FakeMp3File('/somepath/somefile.MP3')
filename = file_.make_filename(file_.filename, self.metadata)
self.assertEqual(os.path.realpath('/somepath/sometitle.mp3'), filename)
def test_make_filename_scripted_extension(self):
config.setting['rename_files'] = True
config.setting['file_renaming_scripts'] = {'test_id': {'script': '$set(_extension,.foo)%title%'}}
filename = self.file.make_filename(self.file.filename, self.metadata)
self.assertEqual(os.path.realpath('/somepath/sometitle.foo'), filename)
def test_make_filename_replace_trailing_dots(self):
config.setting['rename_files'] = True
config.setting['move_files'] = True
config.setting['windows_compatibility'] = True
metadata = Metadata({
'album': 'somealbum.',
'title': 'sometitle',
})
filename = self.file.make_filename(self.file.filename, metadata)
self.assertEqual(
os.path.realpath('/media/music/somealbum_/sometitle.mp3'),
filename)
@unittest.skipUnless(not IS_WIN, "non-windows test")
def test_make_filename_keep_trailing_dots(self):
config.setting['rename_files'] = True
config.setting['move_files'] = True
config.setting['windows_compatibility'] = False
metadata = Metadata({
'album': 'somealbum.',
'title': 'sometitle',
})
filename = self.file.make_filename(self.file.filename, metadata)
self.assertEqual(
os.path.realpath('/media/music/somealbum./sometitle.mp3'),
filename)
def test_make_filename_replace_leading_dots(self):
config.setting['rename_files'] = True
config.setting['move_files'] = True
config.setting['windows_compatibility'] = True
metadata = Metadata({
'album': '.somealbum',
'title': '.sometitle',
})
filename = self.file.make_filename(self.file.filename, metadata)
self.assertEqual(
os.path.realpath('/media/music/_somealbum/_sometitle.mp3'),
filename)
class FileGuessTracknumberAndTitleTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({
'guess_tracknumber_and_title': True,
})
def test_no_guess(self):
f = File('/somepath/01 somefile.mp3')
metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
'tracknumber': '2',
})
f._guess_tracknumber_and_title(metadata)
self.assertEqual(metadata['tracknumber'], '2')
self.assertEqual(metadata['title'], 'sometitle')
def test_guess_title(self):
f = File('/somepath/01 somefile.mp3')
metadata = Metadata({
'album': 'somealbum',
'tracknumber': '2',
})
f._guess_tracknumber_and_title(metadata)
self.assertEqual(metadata['tracknumber'], '2')
self.assertEqual(metadata['title'], 'somefile')
def test_guess_tracknumber(self):
f = File('/somepath/01 somefile.mp3')
metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
f._guess_tracknumber_and_title(metadata)
self.assertEqual(metadata['tracknumber'], '1')
def test_guess_title_tracknumber(self):
f = File('/somepath/01 somefile.mp3')
metadata = Metadata({
'album': 'somealbum',
})
f._guess_tracknumber_and_title(metadata)
self.assertEqual(metadata['tracknumber'], '1')
self.assertEqual(metadata['title'], 'somefile')
class FileAdditionalFilesPatternsTest(PicardTestCase):
def test_empty_patterns(self):
self.assertEqual(File._compile_move_additional_files_pattern(' '), set())
def test_simple_patterns(self):
pattern = 'cover.jpg'
expected = {
(re.compile('(?s:cover\\.jpg)\\Z', re.IGNORECASE), False)
}
self.assertEqual(File._compile_move_additional_files_pattern(pattern), expected)
def test_whitespaces_patterns(self):
pattern = " a \n b "
expected = {
(re.compile('(?s:a)\\Z', re.IGNORECASE), False),
(re.compile('(?s:b)\\Z', re.IGNORECASE), False),
}
self.assertEqual(File._compile_move_additional_files_pattern(pattern), expected)
def test_duplicated_patterns(self):
pattern = 'cover.jpg cover.jpg COVER.JPG'
expected = {
(re.compile('(?s:cover\\.jpg)\\Z', re.IGNORECASE), False)
}
self.assertEqual(File._compile_move_additional_files_pattern(pattern), expected)
def test_simple_hidden_patterns(self):
pattern = 'cover.jpg .hidden'
expected = {
(re.compile('(?s:cover\\.jpg)\\Z', re.IGNORECASE), False),
(re.compile('(?s:\\.hidden)\\Z', re.IGNORECASE), True)
}
self.assertEqual(File._compile_move_additional_files_pattern(pattern), expected)
def test_wildcard_patterns(self):
pattern = 'c?ver.jpg .h?dden* *.jpg *.JPG'
expected = {
(re.compile('(?s:c.ver\\.jpg)\\Z', re.IGNORECASE), False),
(re.compile('(?s:\\.h.dden.*)\\Z', re.IGNORECASE), True),
(re.compile('(?s:.*\\.jpg)\\Z', re.IGNORECASE), False),
}
self.assertEqual(File._compile_move_additional_files_pattern(pattern), expected)
class FileUpdateTest(PicardTestCase):
def setUp(self):
super().setUp()
self.file = File('/somepath/somefile.mp3')
self.INVALIDSIMVAL = 666
self.file.similarity = self.INVALIDSIMVAL # to check if changed or not
self.file.supports_tag = lambda x: False if x.startswith('unsupported') else True
self.set_config_values({
'clear_existing_tags': False,
'compare_ignore_tags': [],
'enabled_plugins': [],
})
def test_same_image(self):
image = create_image(b'a')
self.file.metadata.images = [image]
self.file.orig_metadata.images = [image]
self.file.state = File.NORMAL
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0) # it should be modified
self.assertEqual(self.file.state, File.NORMAL)
def test_same_image_pending(self):
image = create_image(b'a')
self.file.metadata.images = [image]
self.file.orig_metadata.images = [image]
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.PENDING)
def test_same_image_changed_state(self):
image = create_image(b'a')
self.file.metadata.images = [image]
self.file.orig_metadata.images = [image]
self.file.state = File.CHANGED
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.NORMAL)
def test_changed_image(self):
old_image = create_image(b'a')
new_image = create_image(b'b')
self.file.metadata.images = [new_image]
self.file.orig_metadata.images = [old_image]
self.file.state = File.NORMAL
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.CHANGED)
def test_signal(self):
# just for coverage
self.file.update(signal=True)
self.assertEqual(self.file.metadata, Metadata())
self.assertEqual(self.file.orig_metadata, Metadata())
def test_tags_to_update(self):
self.file.orig_metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
'ignoreme_old': 'a',
'~ignoreme_old': 'b',
'unsupported_old': 'c',
})
self.file.metadata = Metadata({
'artist': 'someartist',
'ignoreme_new': 'd',
'~ignoreme_new': 'e',
'unsupported_new': 'f',
})
ignore_tags = {'ignoreme_old', 'ignoreme_new'}
expected = {'album', 'title', 'artist'}
result = self.file._tags_to_update(ignore_tags)
self.assertIsInstance(result, GeneratorType)
self.assertEqual(set(result), expected)
def test_unchanged_metadata(self):
self.file.orig_metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
self.file.metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
self.file.state = File.NORMAL
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.NORMAL)
def test_changed_metadata(self):
self.file.orig_metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
self.file.metadata = Metadata({
'album': 'somealbum2',
'title': 'sometitle2',
})
self.file.state = File.NORMAL
self.file.update(signal=False)
self.assertLess(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.CHANGED)
def test_changed_metadata_pending(self):
self.file.orig_metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
self.file.metadata = Metadata({
'album': 'somealbum2',
'title': 'sometitle2',
})
self.file.update(signal=False)
self.assertLess(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.PENDING) # it shouldn't be modified
def test_clear_existing(self):
self.file.orig_metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
self.file.metadata = Metadata()
self.file.state = File.NORMAL
config.setting["clear_existing_tags"] = True
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 0.0)
self.assertEqual(self.file.state, File.CHANGED)
def test_no_new_metadata(self):
self.file.orig_metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
})
self.file.metadata = Metadata()
self.file.state = File.NORMAL
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.NORMAL)
def test_tilde_tag(self):
self.file.orig_metadata = Metadata()
self.file.metadata = Metadata({
'~tag': 'value'
})
self.file.state = File.NORMAL
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.NORMAL)
def test_ignored_tag(self):
self.file.orig_metadata = Metadata()
self.file.metadata = Metadata({
'tag': 'value'
})
self.file.state = File.NORMAL
config.setting["compare_ignore_tags"] = ['tag']
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.NORMAL)
def test_unsupported_tag(self):
self.file.orig_metadata = Metadata()
self.file.metadata = Metadata({
'unsupported': 'value'
})
self.file.state = File.NORMAL
self.file.update(signal=False)
self.assertEqual(self.file.similarity, 1.0)
self.assertEqual(self.file.state, File.NORMAL)
def test_copy_file_info_tags(self):
info_tags = {}
for info in FILE_INFO_TAGS:
info_tags[info] = 'val' + info
orig_metadata = Metadata(info_tags)
orig_metadata['a'] = 'vala'
metadata = Metadata({
'~bitrate': 'xxx',
'b': 'valb',
})
self.file._copy_file_info_tags(metadata, orig_metadata)
for info in FILE_INFO_TAGS:
self.assertEqual('val' + info, metadata[info])
self.assertEqual('valb', metadata['b'])
self.assertNotIn('a', metadata)
class FileCopyMetadataTest(PicardTestCase):
def setUp(self):
super().setUp()
metadata = Metadata({
'album': 'somealbum',
'artist': 'someartist',
'title': 'sometitle',
})
del metadata['deletedtag']
metadata.images.append(create_image(b'a'))
self.file = File('/somepath/somefile.mp3')
self.file.metadata = metadata
self.file.orig_metadata = Metadata({
'album': 'origalbum',
'artist': 'origartist',
'title': 'origtitle',
})
self.INVALIDSIMVAL = 666
self.set_config_values({
'preserved_tags': [],
})
def test_copy_metadata_full(self):
new_metadata = Metadata({
'title': 'othertitle',
'~foo': 'bar',
})
del new_metadata['foo']
new_metadata.images.append(create_image(b'b'))
self.file.copy_metadata(new_metadata, preserve_deleted=False)
self.assertEqual(self.file.metadata, new_metadata)
self.assertEqual(self.file.metadata.images, new_metadata.images)
self.assertEqual(self.file.metadata.deleted_tags, new_metadata.deleted_tags)
def test_copy_metadata_must_preserve_deleted_tags_by_default(self):
new_metadata = Metadata({
'title': 'othertitle',
'~foo': 'bar',
})
del new_metadata['foo']
self.file.copy_metadata(new_metadata)
self.assertEqual(self.file.metadata, new_metadata)
self.assertEqual(self.file.metadata.deleted_tags, {'deletedtag', 'foo'})
def test_copy_metadata_do_not_preserve_deleted_tags(self):
new_metadata = Metadata({
'title': 'othertitle',
'~foo': 'bar',
})
del new_metadata['foo']
self.file.copy_metadata(new_metadata, preserve_deleted=False)
self.assertEqual(self.file.metadata, new_metadata)
self.assertEqual(self.file.metadata.deleted_tags, {'foo'})
def test_copy_metadata_must_keep_file_content_specific_tags(self):
for tag in CALCULATED_TAGS:
self.file.metadata[tag] = 'foo'
new_metadata = Metadata()
self.file.copy_metadata(new_metadata)
for tag in CALCULATED_TAGS:
self.assertEqual(
self.file.metadata[tag], 'foo',
f'Tag {tag}: {self.file.metadata[tag]!r} != "foo"')
def test_copy_metadata_must_remove_deleted_acoustid_id(self):
self.file.metadata['acoustid_id'] = 'foo'
new_metadata = Metadata()
new_metadata.delete('acoustid_id')
self.file.copy_metadata(new_metadata)
self.assertEqual(self.file.metadata['acoustid_id'], '')
self.assertIn('acoustid_id', self.file.metadata.deleted_tags)
def test_copy_metadata_with_preserved_tags(self):
self.set_config_values({
'preserved_tags': ['artist', 'title'],
})
new_metadata = Metadata({
'album': 'otheralbum',
'artist': 'otherartist',
'title': 'othertitle',
})
self.file.copy_metadata(new_metadata)
self.assertEqual(self.file.metadata['album'], 'otheralbum')
self.assertEqual(self.file.metadata['artist'], 'origartist')
self.assertEqual(self.file.metadata['title'], 'origtitle')
def test_copy_metadata_must_always_preserve_technical_variables(self):
self.file.orig_metadata['~filename'] = 'orig.flac'
new_metadata = Metadata({
'~filename': 'new.flac',
})
self.file.copy_metadata(new_metadata)
self.assertEqual(self.file.metadata['~filename'], 'orig.flac')
| 26,814
|
Python
|
.py
| 612
| 34.792484
| 113
| 0.629681
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,873
|
__init__.py
|
metabrainz_picard/test/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006 Lukáš Lalinský
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2019 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
import glob
import os.path
for filename in glob.glob(os.path.join(os.path.dirname(__file__), "test_*.py")):
__import__("test." + os.path.basename(filename)[:-3])
| 1,111
|
Python
|
.py
| 26
| 41.307692
| 80
| 0.758813
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,874
|
test_disc_utils.py
|
metabrainz_picard/test/test_disc_utils.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.disc.utils import (
NotSupportedTOCError,
TocEntry,
calculate_mb_toc_numbers,
)
test_entries = [
TocEntry(1, 0, 24913),
TocEntry(2, 24914, 43460),
TocEntry(3, 43461, 60739),
]
class TestCalculateMbTocNumbers(PicardTestCase):
def test_calculate_mb_toc_numbers(self):
self.assertEqual((1, 3, 60890, 150, 25064, 43611), calculate_mb_toc_numbers(test_entries))
def test_calculate_mb_toc_numbers_invalid_track_numbers(self):
entries = [TocEntry(1, 0, 100), TocEntry(3, 101, 200), TocEntry(4, 201, 300)]
with self.assertRaisesRegex(NotSupportedTOCError, r"^Non-standard track number sequence: \(1, 3, 4\)$"):
calculate_mb_toc_numbers(entries)
def test_calculate_mb_toc_numbers_empty_entries(self):
with self.assertRaisesRegex(NotSupportedTOCError, r"^Empty track list$"):
calculate_mb_toc_numbers([])
def test_calculate_mb_toc_numbers_ignore_datatrack(self):
entries = [*test_entries, TocEntry(4, 72140, 80000)]
self.assertEqual((1, 3, 60890, 150, 25064, 43611), calculate_mb_toc_numbers(entries))
| 1,993
|
Python
|
.py
| 43
| 42.511628
| 112
| 0.733505
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,875
|
test_plugins.py
|
metabrainz_picard/test/test_plugins.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
# Copyright (C) 2019-2021, 2023 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import logging
import os
import sys
import unittest
from unittest.mock import Mock
from test.picardtestcase import PicardTestCase
import picard
from picard.const import USER_PLUGIN_DIR
from picard.plugin import (
PluginFunctions,
PluginWrapper,
_unregister_module_extensions,
)
from picard.pluginmanager import (
PluginManager,
_compatible_api_versions,
_plugin_dirs,
_plugin_name_from_path,
register_plugin_dir,
)
from picard.version import (
Version,
VersionError,
)
# testplugins structure along plugins (zipped or not) structures
#
# ├── module/
# │ └── dummyplugin/
# │ └── __init__.py
# ├── packaged_module/
# │ └── dummyplugin.picard.zip
# │ └── dummyplugin/ # FIXME: correct structure??
# │ └── __init__.py
# │ └── MANIFEST.json # FIXME: format??
# ├── singlefile/
# │ └── dummyplugin.py
# ├── zipped_module/
# │ └── dummyplugin.zip
# │ └── dummyplugin/
# │ └── __init__.py
# └── zipped_singlefile/
# └── dummyplugin.zip
# └── dummyplugin.py
# module
# packaged_module
# singlefile
# zipped_module
# zipped_singlefile
def _get_test_plugins():
testplugins = {}
testplugins_path = os.path.join('test', 'data', 'testplugins')
for f in os.listdir(testplugins_path):
testplugin = os.path.join(testplugins_path, f)
for e in os.listdir(testplugin):
if e == '__pycache__':
continue
testplugins[f] = os.path.join(testplugin, e)
return testplugins
_testplugins = _get_test_plugins()
def unload_plugin(plugin_name):
"""for testing purposes"""
_unregister_module_extensions(plugin_name)
if hasattr(picard.plugins, plugin_name):
delattr(picard.plugins, plugin_name)
if plugin_name in sys.modules:
del sys.modules[plugin_name]
class TestPicardPluginsCommon(PicardTestCase):
def setUp(self):
super().setUp()
logging.disable(logging.ERROR)
def tearDown(self):
pass
class TestPicardPluginsCommonTmpDir(TestPicardPluginsCommon):
def setUp(self):
super().setUp()
self.tmp_directory = self.mktmpdir()
register_plugin_dir(self.tmp_directory)
class TestPicardPluginManager(TestPicardPluginsCommon):
def test_compatible_api_version(self):
# use first element from picard.api_versions, it should be compatible
api_versions = picard.api_versions[:1]
expected = {Version.from_string(v) for v in api_versions}
result = _compatible_api_versions(api_versions)
self.assertEqual(result, expected)
# pretty sure 0.0 isn't compatible
api_versions = ["0.0"]
expected = set()
result = _compatible_api_versions(api_versions)
self.assertEqual(result, expected)
# buggy version
api_versions = ["0.a"]
with self.assertRaises(VersionError):
result = _compatible_api_versions(api_versions)
def test_plugin_name_from_path(self):
for name, path in _testplugins.items():
self.assertEqual(
_plugin_name_from_path(path), 'dummyplugin',
"failed to get plugin name from %s: %r" % (name, path)
)
class TestPicardPluginsInstall(TestPicardPluginsCommonTmpDir):
def _test_plugin_install(self, name):
plugin_path = _testplugins[name]
pm = PluginManager(plugins_directory=self.tmp_directory)
msg = "install_plugin: %s %r" % (name, plugin_path)
pm.install_plugin(plugin_path)
self.assertEqual(len(pm.plugins), 1, msg)
self.assertEqual(pm.plugins[0].name, 'Dummy plugin', msg)
# if module is properly loaded, this should work
from picard.plugins.dummyplugin import DummyPlugin
DummyPlugin()
# Remove plugin again
pm.remove_plugin('dummyplugin')
unload_plugin('picard.plugins.dummyplugin')
with self.assertRaises(ImportError):
from picard.plugins.dummyplugin import ( # noqa: F811 # pylint: disable=reimported
DummyPlugin,
)
def _test_plugin_install_data(self, name):
# simulate installation from UI using data from picard plugins api web service
with open(_testplugins[name], 'rb') as f:
data = f.read()
pm = PluginManager(plugins_directory=self.tmp_directory)
msg = "install_plugin_data: %s data: %d bytes" % (name, len(data))
pm.install_plugin(None, plugin_name='dummyplugin', plugin_data=data)
self.assertEqual(len(pm.plugins), 1, msg)
self.assertEqual(pm.plugins[0].name, 'Dummy plugin', msg)
# if module is properly loaded, this should work
from picard.plugins.dummyplugin import DummyPlugin
DummyPlugin()
# Remove plugin again
pm.remove_plugin('dummyplugin')
unload_plugin('picard.plugins.dummyplugin')
with self.assertRaises(ImportError):
from picard.plugins.dummyplugin import ( # noqa: F811 # pylint: disable=reimported
DummyPlugin,
)
# module
def test_plugin_install_module(self):
self._test_plugin_install('module')
# packaged_module
# FIXME : not really implemented
@unittest.skipIf(True, "FIXME")
def test_plugin_install_packaged_module(self):
self._test_plugin_install('packaged_module')
# singlefile
def test_plugin_install_packaged_singlefile(self):
self._test_plugin_install('singlefile')
# zipped_module
def test_plugin_install_packaged_zipped_module(self):
self._test_plugin_install('zipped_module')
# zipped_singlefile
def test_plugin_install_packaged_zipped_singlefile(self):
self._test_plugin_install('zipped_singlefile')
# zipped_module from picard plugins ws
def test_plugin_install_zipped_module_data(self):
self._test_plugin_install_data('zipped_module')
# zipped_singlefile from picard plugins ws
def test_plugin_install_zipped_singlefile_data(self):
self._test_plugin_install_data('zipped_singlefile')
def test_plugin_install_no_path_no_plugin_name(self):
pm = PluginManager(plugins_directory=self.tmp_directory)
with self.assertRaises(AssertionError):
pm.install_plugin(None)
class TestPicardPluginsLoad(TestPicardPluginsCommonTmpDir):
def setUp(self):
super().setUp()
self.pm = PluginManager(plugins_directory=self.tmp_directory)
self.src_dir = None
def tearDown(self):
super().tearDown()
unload_plugin('picard.plugins.dummyplugin')
if self.src_dir:
_plugin_dirs.remove(self.src_dir)
def _register_plugin_dir(self, name):
self.src_dir = os.path.dirname(_testplugins[name])
register_plugin_dir(self.src_dir)
def _test_plugin_load_from_directory(self, name):
self._register_plugin_dir(name)
msg = "plugins_load_from_directory: %s %r" % (name, self.src_dir)
self.pm.load_plugins_from_directory(self.src_dir)
self.assertEqual(len(self.pm.plugins), 1, msg)
self.assertEqual(self.pm.plugins[0].name, 'Dummy plugin', msg)
# if module is properly loaded, this should work
from picard.plugins.dummyplugin import DummyPlugin
DummyPlugin()
# singlefile
def test_plugin_load_from_directory_singlefile(self):
self._test_plugin_load_from_directory('singlefile')
# zipped_module
def test_plugin_load_from_directory_zipped_module(self):
self._test_plugin_load_from_directory('zipped_module')
# zipped_singlefile
def test_plugin_load_from_directory_zipped_singlefile(self):
self._test_plugin_load_from_directory('zipped_singlefile')
# module
def test_plugin_load_from_directory_module(self):
self._test_plugin_load_from_directory('module')
def test_plugin_import_error(self):
module_name = 'picard.plugins.dummyplugin'
self.assertIsNone(sys.modules.get(module_name))
self._register_plugin_dir('importerror')
self.pm.load_plugins_from_directory(self.src_dir)
self.assertIsNone(sys.modules.get(module_name))
class TestPluginWrapper(PicardTestCase):
def test_is_user_installed(self):
manifest = {
'PLUGIN_NAME': 'foo'
}
user_plugin = PluginWrapper({}, USER_PLUGIN_DIR, manifest_data=manifest)
self.assertTrue(user_plugin.is_user_installed)
system_plugin = PluginWrapper({}, '/other/path/plugins', manifest_data=manifest)
self.assertFalse(system_plugin.is_user_installed)
class TestPluginFunctions(PicardTestCase):
def setUp(self):
self.set_config_values({
'enabled_plugins': [],
})
def test_register_order(self):
pfs = PluginFunctions(label="test")
self.assertEqual(pfs.functions, {})
pfs.register('m', 'f1', priority=0)
pfs.register('m', 'f2', priority=0)
self.assertEqual(list(pfs._get_functions()), ['f1', 'f2'])
pfs.register('m', 'f3', priority=1)
pfs.register('m', 'f4', priority=-1)
self.assertEqual(list(pfs._get_functions()), ['f3', 'f1', 'f2', 'f4'])
def test_run_args(self):
testfunc1 = Mock()
testfunc2 = Mock()
pfs = PluginFunctions(label="test")
pfs.register('m', testfunc1)
pfs.register('m', testfunc2)
pfs.run(1, k=2)
testfunc1.assert_called_with(1, k=2)
testfunc2.assert_called_with(1, k=2)
| 10,587
|
Python
|
.py
| 255
| 34.376471
| 95
| 0.671508
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,876
|
test_coverartprovider_caa.py
|
metabrainz_picard/test/test_coverartprovider_caa.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2020-2021 Laurent Monin
# Copyright (C) 2020-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.coverart.providers.caa import caa_url_fallback_list
class CoverArtImageProviderCaaTest(PicardTestCase):
def test_caa_url_fallback_list(self):
def do_tests(sizes, expectations):
# we create a dummy url named after matching size
thumbnails = {size: "url %s" % size for size in sizes}
msgfmt = "for size %s, with sizes %r, got %r, expected %r"
for size, expect in expectations.items():
result = [thumbnail.url for thumbnail in caa_url_fallback_list(size, thumbnails)]
self.assertEqual(result, expect, msg=msgfmt % (size, sizes, result, expect))
# For historical reasons, caa web service returns 2 identical urls,
# for 2 different keys (250/small, 500/large)
# Here is an example of the json relevant part:
# "thumbnails": {
# "250": "http://coverartarchive.org/release/d20247ad-940e-486d-948f-be4c17024ab9/24885128253-250.jpg",
# "500": "http://coverartarchive.org/release/d20247ad-940e-486d-948f-be4c17024ab9/24885128253-500.jpg",
# "1200": "http://coverartarchive.org/release/d20247ad-940e-486d-948f-be4c17024ab9/24885128253-1200.jpg",
# "large": "http://coverartarchive.org/release/d20247ad-940e-486d-948f-be4c17024ab9/24885128253-500.jpg",
# "small": "http://coverartarchive.org/release/d20247ad-940e-486d-948f-be4c17024ab9/24885128253-250.jpg"
# },
sizes = ("250", "500", "1200", "large", "small")
expectations = {
50: [],
250: ['url 250'],
400: ['url 250'],
500: ['url 500', 'url 250'],
600: ['url 500', 'url 250'],
1200: ['url 1200', 'url 500', 'url 250'],
1500: ['url 1200', 'url 500', 'url 250'],
}
do_tests(sizes, expectations)
# Some older releases have no 1200px thumbnail
sizes = ("250", "500", "large", "small")
expectations = {
50: [],
250: ['url 250'],
400: ['url 250'],
500: ['url 500', 'url 250'],
600: ['url 500', 'url 250'],
1200: ['url 500', 'url 250'],
1500: ['url 500', 'url 250'],
}
do_tests(sizes, expectations)
# In the future, large and small might be removed or new size added
# test if we can handle that (through size aliases)
sizes = ("small", "large", "1200", "2000", "unknownsize")
expectations = {
50: [],
250: ['url small'],
400: ['url small'],
500: ['url large', 'url small'],
600: ['url large', 'url small'],
1200: ['url 1200', 'url large', 'url small'],
1500: ['url 1200', 'url large', 'url small'],
}
do_tests(sizes, expectations)
with self.assertRaises(TypeError):
caa_url_fallback_list("not_an_integer", {"250": "url 250"})
with self.assertRaises(AttributeError):
caa_url_fallback_list(250, 666)
| 3,966
|
Python
|
.py
| 81
| 40.62963
| 115
| 0.619097
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,877
|
test_compatid3.py
|
metabrainz_picard/test/test_compatid3.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007 Lukáš Lalinský
# Copyright (C) 2013, 2018, 2020-2021 Laurent Monin
# Copyright (C) 2016 Christoph Reiter
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2019, 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from mutagen import id3
from test.picardtestcase import PicardTestCase
from picard.formats.id3 import Id3Encoding
from picard.formats.mutagenext import compatid3
class UpdateToV23Test(PicardTestCase):
def test_keep_some_v24_tag(self):
tags = compatid3.CompatID3()
tags.add(id3.TSOP(encoding=Id3Encoding.LATIN1, text=["foo"]))
tags.add(id3.TSOA(encoding=Id3Encoding.LATIN1, text=["foo"]))
tags.add(id3.TSOT(encoding=Id3Encoding.LATIN1, text=["foo"]))
tags.update_to_v23()
self.assertEqual(tags["TSOP"].text, ["foo"])
self.assertEqual(tags["TSOA"].text, ["foo"])
self.assertEqual(tags["TSOT"].text, ["foo"])
def test_tdrc(self):
tags = compatid3.CompatID3()
tags.add(id3.TDRC(encoding=Id3Encoding.UTF16, text="2003-04-05 12:03"))
tags.update_to_v23()
self.assertEqual(tags["TYER"].text, ["2003"])
self.assertEqual(tags["TDAT"].text, ["0504"])
self.assertEqual(tags["TIME"].text, ["1203"])
def test_tdor(self):
tags = compatid3.CompatID3()
tags.add(id3.TDOR(encoding=Id3Encoding.UTF16, text="2003-04-05 12:03"))
tags.update_to_v23()
self.assertEqual(tags["TORY"].text, ["2003"])
def test_genre_from_v24_1(self):
tags = compatid3.CompatID3()
tags.add(id3.TCON(encoding=Id3Encoding.UTF16, text=["4", "Rock"]))
tags.update_to_v23()
self.assertEqual(tags["TCON"].text, ["Disco", "Rock"])
def test_genre_from_v24_2(self):
tags = compatid3.CompatID3()
tags.add(id3.TCON(encoding=Id3Encoding.UTF16, text=["RX", "3", "CR"]))
tags.update_to_v23()
self.assertEqual(tags["TCON"].text, ["Remix", "Dance", "Cover"])
def test_genre_from_v23_1(self):
tags = compatid3.CompatID3()
tags.add(id3.TCON(encoding=Id3Encoding.UTF16, text=["(4)Rock"]))
tags.update_to_v23()
self.assertEqual(tags["TCON"].text, ["Disco", "Rock"])
def test_genre_from_v23_2(self):
tags = compatid3.CompatID3()
tags.add(id3.TCON(encoding=Id3Encoding.UTF16, text=["(RX)(3)(CR)"]))
tags.update_to_v23()
self.assertEqual(tags["TCON"].text, ["Remix", "Dance", "Cover"])
| 3,231
|
Python
|
.py
| 69
| 41.246377
| 80
| 0.680229
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,878
|
test_interface_colors.py
|
metabrainz_picard/test/test_interface_colors.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2020 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from PyQt6.QtGui import QColor
from test.picardtestcase import PicardTestCase
from picard import config
from picard.ui.colors import (
InterfaceColors,
UnknownColorException,
interface_colors,
)
settings = {
'interface_colors': {
'unknowncolor': '#deadbe',
'entity_error': '#abcdef',
},
'interface_colors_dark': {
'unknowncolor': '#deadbe',
'entity_error': '#abcdef',
}
}
class InterfaceColorsTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values(settings)
def test_interface_colors(self):
for key in ('interface_colors', 'interface_colors_dark'):
interface_colors = InterfaceColors(dark_theme=key == 'interface_colors_dark')
with self.assertRaises(UnknownColorException):
interface_colors.get_color('testcolor')
default_colors = interface_colors.default_colors
self.assertEqual(interface_colors.get_color('entity_error'), default_colors['entity_error'].value)
interface_colors.load_from_config()
self.assertEqual(interface_colors.get_color('entity_error'), '#abcdef')
self.assertEqual(interface_colors.get_colors()['entity_error'], '#abcdef')
interface_colors.set_color('entity_error', '#000000')
self.assertTrue(interface_colors.save_to_config())
self.assertEqual(config.setting[key]['entity_error'], '#000000')
self.assertNotIn('unknowncolor', config.setting[key])
self.assertEqual(interface_colors.get_color_description('entity_error'), default_colors['entity_error'].description)
self.assertEqual(interface_colors.get_qcolor('entity_error'), QColor('#000000'))
def test_interface_colors_default(self):
self.assertIsInstance(interface_colors, InterfaceColors)
| 2,735
|
Python
|
.py
| 60
| 39.8
| 128
| 0.708333
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,879
|
test_profiles.py
|
metabrainz_picard/test/test_profiles.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import logging
import os
import shutil
from test.picardtestcase import PicardTestCase
from picard.config import (
BoolOption,
Config,
IntOption,
ListOption,
Option,
SettingConfigSection,
TextOption,
)
from picard.profile import (
profile_groups_add_setting,
profile_groups_all_settings,
profile_groups_keys,
profile_groups_order,
profile_groups_reset,
profile_groups_settings,
profile_groups_values,
)
class TestPicardProfilesCommon(PicardTestCase):
PROFILES_KEY = SettingConfigSection.PROFILES_KEY
SETTINGS_KEY = SettingConfigSection.SETTINGS_KEY
def setUp(self):
super().setUp()
self.tmp_directory = self.mktmpdir()
self.configpath = os.path.join(self.tmp_directory, 'test.ini')
shutil.copy(os.path.join('test', 'data', 'test.ini'), self.configpath)
self.addCleanup(os.remove, self.configpath)
self.config = Config.from_file(None, self.configpath)
self.addCleanup(self.cleanup_config_obj)
self.config.application["version"] = "testing"
logging.disable(logging.ERROR)
Option.registry = {}
ListOption('profiles', self.PROFILES_KEY, [])
Option('profiles', self.SETTINGS_KEY, {})
# Get valid profile option settings for testing
profile_groups_reset()
for n in range(0, 4):
group = 'group%d' % (n % 2)
title = 'title_' + group
name = 'opt%d' % n
highlights = ('obj%d' % i for i in range(0, n))
profile_groups_add_setting(group, name, highlights, title=title)
option_settings = list(profile_groups_all_settings())
self.test_setting_0 = option_settings[0]
self.test_setting_1 = option_settings[1]
self.test_setting_2 = option_settings[2]
self.test_setting_3 = option_settings[3]
TextOption("setting", self.test_setting_0, "abc")
BoolOption("setting", self.test_setting_1, True)
IntOption("setting", self.test_setting_2, 42)
TextOption("setting", self.test_setting_3, "xyz")
def cleanup_config_obj(self):
# Ensure QSettings do not recreate the file on exit
self.config.sync()
del self.config
self.config = None
def get_profiles(self, enabled=True):
profiles = []
for i in range(3):
profiles.append(
{
"position": i,
"title": "Test Profile {0}".format(i),
"enabled": enabled,
"id": "test_key_{0}".format(i),
}
)
return profiles
class TestUserProfileGroups(TestPicardProfilesCommon):
def test_has_groups(self):
groups = list(profile_groups_keys())
self.assertEqual(groups, ['group0', 'group1'])
def test_groups_have_items(self):
for group in profile_groups_keys():
settings = profile_groups_settings(group)
self.assertNotEqual(settings, {})
def test_no_duplicate_settings(self):
count1 = 0
for group in profile_groups_keys():
settings = profile_groups_settings(group)
count1 += len(list(settings))
count2 = len(list(profile_groups_all_settings()))
self.assertEqual(count1, count2)
def test_settings_have_no_blank_keys(self):
for group in profile_groups_keys():
settings = profile_groups_settings(group)
for name, highlights in settings:
self.assertNotEqual(name.strip(), "")
def test_groups_have_title(self):
for value in profile_groups_values():
self.assertTrue(value['title'].startswith('title_'))
def test_groups_have_highlights(self):
for group in profile_groups_keys():
for setting in profile_groups_settings(group):
self.assertIsNotNone(setting.highlights)
def test_order(self):
result_before = [value['title'] for value in profile_groups_values()]
self.assertEqual(
result_before,
['title_group0', 'title_group1']
)
profile_groups_order('group1')
profile_groups_order('group0')
result_after = [value['title'] for value in profile_groups_values()]
self.assertEqual(
result_after,
['title_group1', 'title_group0']
)
class TestUserProfiles(TestPicardProfilesCommon):
def test_settings(self):
self.config.setting[self.test_setting_0] = "abc"
self.config.setting[self.test_setting_1] = True
self.config.setting[self.test_setting_2] = 42
settings = {
"test_key_0": {self.test_setting_0: None},
"test_key_1": {self.test_setting_1: None},
"test_key_2": {self.test_setting_2: None},
}
self.config.profiles[self.SETTINGS_KEY] = settings
self.config.profiles[self.PROFILES_KEY] = self.get_profiles(enabled=True)
# Stack:
# setting_0 setting_1 setting_2
# --------- --------- ---------
# test_key_0: None n/a n/a
# test_key_1: n/a None n/a
# test_key_2: n/a n/a None
# user_settings: abc True 42
# Test retrieval with overrides at None
self.assertEqual(self.config.setting[self.test_setting_0], "abc")
self.assertEqual(self.config.setting[self.test_setting_1], True)
self.assertEqual(self.config.setting[self.test_setting_2], 42)
# Test setting new values
self.config.setting[self.test_setting_0] = "def"
self.config.setting[self.test_setting_1] = False
self.config.setting[self.test_setting_2] = 99
# Stack:
# setting_0 setting_1 setting_2
# --------- --------- ---------
# test_key_0: def n/a n/a
# test_key_1: n/a False n/a
# test_key_2: n/a n/a 99
# user_settings: abc True 42
self.assertEqual(self.config.setting[self.test_setting_0], "def")
self.assertEqual(self.config.setting[self.test_setting_1], False)
self.assertEqual(self.config.setting[self.test_setting_2], 99)
# Test retrieval with profiles disabled
self.config.profiles[self.PROFILES_KEY] = self.get_profiles(enabled=False)
self.assertEqual(self.config.setting[self.test_setting_0], "abc")
self.assertEqual(self.config.setting[self.test_setting_1], True)
self.assertEqual(self.config.setting[self.test_setting_2], 42)
# Test setting new values with profiles disabled
self.config.setting[self.test_setting_0] = "ghi"
self.config.setting[self.test_setting_1] = True
self.config.setting[self.test_setting_2] = 86
# Stack:
# setting_0 setting_1 setting_2
# --------- --------- ---------
# test_key_0: def n/a n/a
# test_key_1: n/a False n/a
# test_key_2: n/a n/a 99
# user_settings: ghi True 86
self.assertEqual(self.config.setting[self.test_setting_0], "ghi")
self.assertEqual(self.config.setting[self.test_setting_1], True)
self.assertEqual(self.config.setting[self.test_setting_2], 86)
# Re-enable profiles and check that the saved settings still exist
self.config.profiles[self.PROFILES_KEY] = self.get_profiles(enabled=True)
self.assertEqual(self.config.setting[self.test_setting_0], "def")
self.assertEqual(self.config.setting[self.test_setting_1], False)
self.assertEqual(self.config.setting[self.test_setting_2], 99)
def test_settings_with_overrides(self):
self.config.setting[self.test_setting_0] = "abc"
self.config.setting[self.test_setting_1] = True
self.config.setting[self.test_setting_2] = 42
settings = {
"test_key_0": {self.test_setting_0: None},
"test_key_1": {self.test_setting_1: None},
"test_key_2": {self.test_setting_2: None},
}
self.config.profiles[self.SETTINGS_KEY] = settings
self.config.profiles[self.PROFILES_KEY] = self.get_profiles(enabled=False)
self.config.setting.set_profiles_override(self.get_profiles(enabled=True))
# Stack:
# setting_0 setting_1 setting_2
# --------- --------- ---------
# test_key_0: None n/a n/a
# test_key_1: n/a None n/a
# test_key_2: n/a n/a None
# user_settings: abc True 42
# Test retrieval with overrides at None
self.assertEqual(self.config.setting[self.test_setting_0], "abc")
self.assertEqual(self.config.setting[self.test_setting_1], True)
self.assertEqual(self.config.setting[self.test_setting_2], 42)
# Test setting new values
self.config.setting[self.test_setting_0] = "def"
self.config.setting[self.test_setting_1] = False
self.config.setting[self.test_setting_2] = 99
# Stack:
# setting_0 setting_1 setting_2
# --------- --------- ---------
# test_key_0: def n/a n/a
# test_key_1: n/a False n/a
# test_key_2: n/a n/a 99
# user_settings: abc True 42
self.assertEqual(self.config.setting[self.test_setting_0], "def")
self.assertEqual(self.config.setting[self.test_setting_1], False)
self.assertEqual(self.config.setting[self.test_setting_2], 99)
# Test retrieval with profile overrides disabled
self.config.setting.set_profiles_override()
self.assertEqual(self.config.setting[self.test_setting_0], "abc")
self.assertEqual(self.config.setting[self.test_setting_1], True)
self.assertEqual(self.config.setting[self.test_setting_2], 42)
# Test retrieval with empty settings overrides
self.config.setting.set_profiles_override(self.get_profiles(enabled=True))
empty_settings = {
"test_key_0": {},
"test_key_1": {},
"test_key_2": {},
}
self.config.setting.set_settings_override(empty_settings)
self.assertEqual(self.config.setting[self.test_setting_0], "abc")
self.assertEqual(self.config.setting[self.test_setting_1], True)
self.assertEqual(self.config.setting[self.test_setting_2], 42)
# Test retrieval with settings overrides disabled
self.config.setting.set_settings_override()
self.assertEqual(self.config.setting[self.test_setting_0], "def")
self.assertEqual(self.config.setting[self.test_setting_1], False)
self.assertEqual(self.config.setting[self.test_setting_2], 99)
# Test setting new values with profiles override disabled
self.config.setting.set_profiles_override()
self.config.setting[self.test_setting_0] = "ghi"
self.config.setting[self.test_setting_1] = True
self.config.setting[self.test_setting_2] = 86
# Stack:
# setting_0 setting_1 setting_2
# --------- --------- ---------
# test_key_0: def n/a n/a
# test_key_1: n/a False n/a
# test_key_2: n/a n/a 99
# user_settings: ghi True 86
self.assertEqual(self.config.setting[self.test_setting_0], "ghi")
self.assertEqual(self.config.setting[self.test_setting_1], True)
self.assertEqual(self.config.setting[self.test_setting_2], 86)
# Re-enable profile overrides and check that the saved settings still exist
self.config.setting.set_profiles_override(self.get_profiles(enabled=True))
self.assertEqual(self.config.setting[self.test_setting_0], "def")
self.assertEqual(self.config.setting[self.test_setting_1], False)
self.assertEqual(self.config.setting[self.test_setting_2], 99)
# Re-enable profile overrides and check that the saved settings still exist
# with invalid profile id in profile list
profiles = [
{
"position": 4,
"title": "Test Profile 4",
"enabled": True,
"id": "test_key_4",
}
]
profiles.extend(self.get_profiles(enabled=True))
self.config.setting.set_profiles_override(profiles)
self.assertEqual(self.config.setting[self.test_setting_0], "def")
self.assertEqual(self.config.setting[self.test_setting_1], False)
self.assertEqual(self.config.setting[self.test_setting_2], 99)
def test_config_option_rename(self):
from picard.config_upgrade import rename_option
self.config.setting[self.test_setting_0] = "abc"
self.config.setting[self.test_setting_1] = True
self.config.setting[self.test_setting_2] = 42
settings = {
"test_key_0": {self.test_setting_0: None},
"test_key_1": {self.test_setting_1: None},
"test_key_2": {self.test_setting_2: None},
}
self.config.profiles[self.SETTINGS_KEY] = settings
self.config.profiles[self.PROFILES_KEY] = self.get_profiles(enabled=True)
self.config.setting[self.test_setting_0] = "def"
rename_option(self.config, self.test_setting_0, self.test_setting_3, TextOption, "")
self.assertEqual(self.config.setting[self.test_setting_3], "def")
self.config.profiles[self.PROFILES_KEY] = self.get_profiles(enabled=False)
self.assertEqual(self.config.setting[self.test_setting_3], "abc")
| 14,974
|
Python
|
.py
| 303
| 40.630363
| 92
| 0.604447
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,880
|
test_metadatabox.py
|
metabrainz_picard/test/test_metadatabox.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.browser.filelookup import FileLookup
from picard.ui.metadatabox import MetadataBox
class MetadataBoxFileLookupTest(PicardTestCase):
def test_filelook_methods(self):
"""Test if methods listed in MetadataBox.LOOKUP_TAGS are valid FileLookup methods"""
for method_as_string in MetadataBox.LOOKUP_TAGS.values():
method = getattr(FileLookup, method_as_string, None)
self.assertIsNotNone(method, f"No such FileLookup.{method_as_string}")
self.assertTrue(callable(method), f"FileLookup.{method_as_string} is not callable")
| 1,456
|
Python
|
.py
| 29
| 47.068966
| 95
| 0.767065
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,881
|
test_util_preservedtags.py
|
metabrainz_picard/test/test_util_preservedtags.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2020 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard import config
from picard.util.preservedtags import PreservedTags
class PreservedTagsTest(PicardTestCase):
def setUp(self):
super().setUp()
config.setting[PreservedTags.opt_name] = ["tag1", "tag2"]
def test_load_and_contains(self):
preserved = PreservedTags()
self.assertIn("tag1", preserved)
self.assertIn("tag2", preserved)
self.assertIn("TAG1", preserved)
self.assertIn(" tag1", preserved)
def test_add(self):
preserved = PreservedTags()
self.assertNotIn("tag3", preserved)
preserved.add("tag3")
self.assertIn("tag3", preserved)
# Add must persists the change
self.assertIn("tag3", PreservedTags())
def test_add_case_insensitive(self):
preserved = PreservedTags()
self.assertNotIn("tag3", preserved)
preserved.add("TAG3")
self.assertIn("tag3", preserved)
def test_discard(self):
preserved = PreservedTags()
self.assertIn("tag1", preserved)
preserved.discard("tag1")
self.assertNotIn("tag1", preserved)
# Discard must persists the change
self.assertNotIn("tag1", PreservedTags())
def test_discard_case_insensitive(self):
preserved = PreservedTags()
self.assertIn("tag1", preserved)
preserved.discard("TAG1")
self.assertNotIn("tag1", preserved)
def test_order(self):
preserved = PreservedTags()
preserved.add('tag3')
preserved.add('tag2')
preserved.add('tag1')
preserved.discard('tag2')
self.assertEqual(config.setting[PreservedTags.opt_name], ['tag1', 'tag3'])
| 2,585
|
Python
|
.py
| 64
| 34.65625
| 82
| 0.696414
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,882
|
test_mbjson.py
|
metabrainz_picard/test/test_mbjson.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2017, 2019-2022 Laurent Monin
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2023 Philipp Wolfer
# Copyright (C) 2020 dukeyin
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Vladislav Karbovskii
# Copyright (C) 2023 David Kellner
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import (
PicardTestCase,
load_test_json,
)
from picard import config
from picard.album import Album
from picard.const import (
ALIAS_TYPE_ARTIST_NAME_ID,
ALIAS_TYPE_LEGAL_NAME_ID,
ALIAS_TYPE_SEARCH_HINT_ID,
)
from picard.mbjson import (
_locales_from_aliases,
_node_skip_empty_iter,
_parse_attributes,
_relations_to_metadata_target_type_url,
_translate_artist_node,
artist_to_metadata,
countries_from_node,
get_score,
label_info_from_node,
media_formats_from_node,
medium_to_metadata,
recording_to_metadata,
release_dates_and_countries_from_node,
release_group_to_metadata,
release_to_metadata,
track_to_metadata,
)
from picard.metadata import Metadata
from picard.releasegroup import ReleaseGroup
from picard.track import Track
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": False,
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['en'],
}
class MBJSONItersTest(PicardTestCase):
def test_node_skip_empty_iter(self):
d = {
'bool_false': False,
'bool_true': True,
'int_0': 0,
'int_1': 1,
'float_0': 0.0,
'float_1': 1.1,
'list_empty': [],
'list_non_empty': ['a'],
'dict_empty': {},
'dict_non_empty': {'a': 'b'},
}
expected = set(d) - {'list_empty', 'dict_empty'}
result = set({k: v for k, v in _node_skip_empty_iter(d)})
self.assertSetEqual(expected, result)
class MBJSONTest(PicardTestCase):
def setUp(self):
super().setUp()
self.init_test(self.filename)
def init_test(self, filename):
self.set_config_values(settings)
self.json_doc = load_test_json(filename)
class ReleaseTest(MBJSONTest):
filename = 'release.json'
def test_release(self):
m = Metadata()
a = Album("1")
release_to_metadata(self.json_doc, m, a)
self.assertEqual(m['album'], 'The Dark Side of the Moon')
self.assertEqual(m['albumartist'], 'Pink Floyd')
self.assertEqual(m['albumartistsort'], 'Pink Floyd')
self.assertEqual(m['asin'], 'b123')
self.assertEqual(m['barcode'], '123')
self.assertEqual(m['catalognumber'], 'SHVL 804')
self.assertEqual(m['date'], '1973-03-24')
self.assertEqual(m['label'], 'Harvest')
self.assertEqual(m['musicbrainz_albumartistid'], '83d91898-7763-47d7-b03b-b92132375c47')
self.assertEqual(m['musicbrainz_albumid'], 'b84ee12a-09ef-421b-82de-0441a926375b')
self.assertEqual(m['producer'], 'Hipgnosis')
self.assertEqual(m['releasecountry'], 'GB')
self.assertEqual(m['releasestatus'], 'official')
self.assertEqual(m['script'], 'Latn')
self.assertEqual(m['~albumartists'], 'Pink Floyd')
self.assertEqual(m['~albumartists_sort'], 'Pink Floyd')
self.assertEqual(m['~releasecomment'], 'stereo')
self.assertEqual(m['~releaseannotation'], 'Original Vinyl release')
self.assertEqual(m['~releaselanguage'], 'eng')
self.assertEqual(m.getall('~releasecountries'), ['GB', 'NZ'])
self.assertEqual(m['~release_series'], 'Why Pink Floyd?')
self.assertEqual(m['~release_seriesid'], '7421b602-a413-4151-bcf4-d831debc3f27')
self.assertEqual(m['~release_seriescomment'], 'Pink Floyed special editions')
self.assertEqual(m['~release_seriesnumber'], '')
self.assertEqual(a.genres, {
'genre1': 6, 'genre2': 3,
'tag1': 6, 'tag2': 3})
for artist in a._album_artists:
self.assertEqual(artist.genres, {
'british': 2,
'progressive rock': 10})
def test_release_without_release_relationships(self):
config.setting['release_ars'] = False
m = Metadata()
a = Album("1")
release_to_metadata(self.json_doc, m, a)
self.assertEqual(m['album'], 'The Dark Side of the Moon')
self.assertEqual(m['albumartist'], 'Pink Floyd')
self.assertEqual(m['albumartistsort'], 'Pink Floyd')
self.assertEqual(m['asin'], 'b123')
self.assertEqual(m['barcode'], '123')
self.assertEqual(m['catalognumber'], 'SHVL 804')
self.assertEqual(m['date'], '1973-03-24')
self.assertEqual(m['label'], 'Harvest')
self.assertEqual(m['musicbrainz_albumartistid'], '83d91898-7763-47d7-b03b-b92132375c47')
self.assertEqual(m['musicbrainz_albumid'], 'b84ee12a-09ef-421b-82de-0441a926375b')
self.assertEqual(m['producer'], '')
self.assertEqual(m['releasecountry'], 'GB')
self.assertEqual(m['releasestatus'], 'official')
self.assertEqual(m['script'], 'Latn')
self.assertEqual(m['~albumartists'], 'Pink Floyd')
self.assertEqual(m['~albumartists_sort'], 'Pink Floyd')
self.assertEqual(m['~releaselanguage'], 'eng')
self.assertEqual(m.getall('~releasecountries'), ['GB', 'NZ'])
self.assertEqual(a.genres, {
'genre1': 6, 'genre2': 3,
'tag1': 6, 'tag2': 3})
for artist in a._album_artists:
self.assertEqual(artist.genres, {
'british': 2,
'progressive rock': 10})
def test_preferred_release_country(self):
m = Metadata()
a = Album("1")
release_to_metadata(self.json_doc, m, a)
self.assertEqual(m['releasecountry'], 'GB')
config.setting['preferred_release_countries'] = ['NZ', 'GB']
release_to_metadata(self.json_doc, m, a)
self.assertEqual(m['releasecountry'], 'NZ')
config.setting['preferred_release_countries'] = ['GB', 'NZ']
release_to_metadata(self.json_doc, m, a)
self.assertEqual(m['releasecountry'], 'GB')
def test_media_formats_from_node(self):
formats = media_formats_from_node(self.json_doc['media'])
self.assertEqual(formats, '12" Vinyl')
def test_release_group_rels(self):
m = Metadata()
release_group_to_metadata(self.json_doc['release-group'], m)
self.assertEqual(m.getall('~releasegroup_series'), [
"Absolute Radio's The 100 Collection",
'1001 Albums You Must Hear Before You Die'
])
self.assertEqual(m.getall('~releasegroup_seriesid'), [
'4bf41050-6fa9-41a6-8398-15bdab4b0352',
'4bc2a338-e1d8-4546-8a61-640da8aaf888'
])
self.assertEqual(m.getall('~releasegroup_seriescomment'), [
'2005 edition'
])
self.assertEqual(m.getall('~releasegroup_seriesnumber'), ['15', '291'])
def test_release_group_rels_double(self):
m = Metadata()
release_group_to_metadata(self.json_doc['release-group'], m)
# load it twice and check for duplicates
release_group_to_metadata(self.json_doc['release-group'], m)
self.assertEqual(m.getall('~releasegroup_series'), [
"Absolute Radio's The 100 Collection",
'1001 Albums You Must Hear Before You Die'
])
self.assertEqual(m.getall('~releasegroup_seriesid'), [
'4bf41050-6fa9-41a6-8398-15bdab4b0352',
'4bc2a338-e1d8-4546-8a61-640da8aaf888'
])
self.assertEqual(m.getall('~releasegroup_seriescomment'), [
'2005 edition'
])
self.assertEqual(m.getall('~releasegroup_seriesnumber'), ['15', '291'])
def test_release_group_rels_removed(self):
m = Metadata()
release_group_to_metadata(self.json_doc['release-group'], m)
# remove one of the series from original metadata
for i, rel in enumerate(self.json_doc['release-group']['relations']):
if not rel['type'] == 'part of':
continue
if rel['series']['name'] == '1001 Albums You Must Hear Before You Die':
del self.json_doc['release-group']['relations'][i]
break
release_group_to_metadata(self.json_doc['release-group'], m)
self.assertEqual(m.getall('~releasegroup_series'), [
"Absolute Radio's The 100 Collection",
])
self.assertEqual(m.getall('~releasegroup_seriesid'), [
'4bf41050-6fa9-41a6-8398-15bdab4b0352',
])
self.assertEqual(m.getall('~releasegroup_seriescomment'), [])
self.assertEqual(m.getall('~releasegroup_seriesnumber'), ['15'])
class NullReleaseTest(MBJSONTest):
filename = 'release_null.json'
def test_release(self):
m = Metadata()
a = Album("1")
release_to_metadata(self.json_doc, m, a)
self.assertEqual(m, {})
def test_media_formats_from_node(self):
formats = media_formats_from_node(self.json_doc['media'])
self.assertEqual(formats, '(unknown)')
class RecordingTest(MBJSONTest):
filename = 'recording.json'
def test_recording(self):
m = Metadata()
t = Track('1')
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m['artist'], 'Ed Sheeran')
self.assertEqual(m['artists'], 'Ed Sheeran')
self.assertEqual(m['artistsort'], 'Sheeran, Ed')
self.assertEqual(m['isrc'], 'GBAHS1400099')
self.assertEqual(m['language'], 'eng')
self.assertEqual(m['musicbrainz_artistid'], 'b8a7c51f-362c-4dcb-a259-bc6e0095f0a6')
self.assertEqual(m['musicbrainz_recordingid'], 'cb2cc207-8125-445c-9ef9-6ea44eee959a')
self.assertEqual(m['musicbrainz_workid'], 'dc469dc8-198e-42e5-b5a7-6be2f0a95ac0')
self.assertEqual(m['performer:'], 'Ed Sheeran')
self.assertEqual(m['performer:lead vocals'], 'Ed Sheeran')
self.assertEqual(m['performer:guitar family'], 'Ed Sheeran')
self.assertEqual(m['title'], 'Thinking Out Loud')
self.assertEqual(m['work'], 'Thinking Out Loud')
self.assertEqual(m['~workcomment'], 'Ed Sheeran song')
self.assertEqual(m['writer'], 'Ed Sheeran; Amy Wadge')
self.assertEqual(m['~writersort'], 'Sheeran, Ed; Wadge, Amy')
self.assertEqual(m['~artists_sort'], 'Sheeran, Ed')
self.assertEqual(m['~length'], '4:41')
self.assertEqual(m['~recordingtitle'], 'Thinking Out Loud')
self.assertEqual(m['~recording_firstreleasedate'], '2014-06-20')
self.assertEqual(m['~video'], '')
self.assertNotIn('originaldate', m)
self.assertNotIn('originalyear', m)
self.assertEqual(t.genres, {
'blue-eyed soul': 1,
'pop': 3})
for artist in t._track_artists:
self.assertEqual(artist.genres, {
'dance-pop': 1,
'guitarist': 0})
def test_recording_instrument_credits(self):
m = Metadata()
t = Track('1')
config.setting['standardize_instruments'] = False
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m['performer:vocals'], 'Ed Sheeran')
self.assertEqual(m['performer:acoustic guitar'], 'Ed Sheeran')
class RecordingComposerCreditsTest(MBJSONTest):
filename = 'recording_composer.json'
def test_standardize_artists(self):
m = Metadata()
t = Track('1')
config.setting['translate_artist_names'] = False
config.setting['standardize_artists'] = True
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m['composer'], 'Пётр Ильич Чайковский')
self.assertEqual(m['composersort'], 'Tchaikovsky, Pyotr Ilyich')
def test_use_credited_as(self):
m = Metadata()
t = Track('1')
config.setting['translate_artist_names'] = False
config.setting['standardize_artists'] = False
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m['composer'], 'Tchaikovsky')
self.assertEqual(m['composersort'], 'Tchaikovsky, Pyotr Ilyich')
def test_translate(self):
m = Metadata()
t = Track('1')
config.setting['translate_artist_names'] = True
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m['composer'], 'Pyotr Ilyich Tchaikovsky')
self.assertEqual(m['composersort'], 'Tchaikovsky, Pyotr Ilyich')
class RecordingInstrumentalTest(MBJSONTest):
filename = 'recording_instrumental.json'
def test_recording(self):
m = Metadata()
t = Track('1')
recording_to_metadata(self.json_doc, m, t)
self.assertIn('instrumental', m.getall('~performance_attributes'))
self.assertEqual(m['language'], 'zxx')
self.assertNotIn('lyricist', m)
class MultiWorkRecordingTest(MBJSONTest):
filename = 'recording_multiple_works.json'
def test_recording(self):
m = Metadata()
t = Track('1')
recording_to_metadata(self.json_doc, m, t)
self.assertIn('instrumental', m.getall('~performance_attributes'))
self.assertEqual(m['language'], 'jpn; eng; zxx')
self.assertEqual(m['lyricist'], 'Satoru Kōsaki; Aki Hata; Minoru Shiraishi')
self.assertEqual(m['~lyricistsort'], 'Kōsaki, Satoru; Hata, Aki; Shiraishi, Minoru')
class RecordingVideoTest(MBJSONTest):
filename = 'recording_video.json'
def test_recording(self):
m = Metadata()
t = Track('1')
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m['director'], 'Edward 209')
self.assertEqual(m['producer'], 'Edward 209')
self.assertEqual(m['~video'], '1')
class NullRecordingTest(MBJSONTest):
filename = 'recording_null.json'
def test_recording(self):
m = Metadata()
t = Track("1")
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m, {})
class RecordingCreditsTest(MBJSONTest):
filename = 'recording_credits.json'
def test_recording_solo_vocals(self):
m = Metadata()
t = Track("1")
recording_to_metadata(self.json_doc, m, t)
config.setting["standardize_artists"] = False
self.assertNotIn('performer:solo', m)
self.assertEqual(m['performer:solo vocals'], 'Frida')
def test_recording_standardize_artist_credits(self):
m = Metadata()
t = Track("1")
config.setting["standardize_artists"] = True
recording_to_metadata(self.json_doc, m, t)
self.assertNotIn('performer:solo', m)
self.assertEqual(m['performer:solo vocals'], 'Anni-Frid Lyngstad')
def test_recording_instrument_keep_case(self):
m = Metadata()
t = Track("1")
recording_to_metadata(self.json_doc, m, t)
self.assertEqual(m['performer:EWI'], 'Michael Brecker')
class TrackTest(MBJSONTest):
filename = 'track.json'
def test_track(self):
t = Track("1")
m = t.metadata
track_to_metadata(self.json_doc, t)
self.assertEqual(m['title'], 'Speak to Me')
self.assertEqual(m['musicbrainz_recordingid'], 'bef3fddb-5aca-49f5-b2fd-d56a23268d63')
self.assertEqual(m['musicbrainz_trackid'], 'd4156411-b884-368f-a4cb-7c0101a557a2')
self.assertEqual(m['~length'], '1:08')
self.assertEqual(m['tracknumber'], '1')
self.assertEqual(m['~musicbrainz_tracknumber'], 'A1')
self.assertEqual(m['~recordingcomment'], 'original stereo mix')
self.assertEqual(m['~recordingtitle'], 'Speak to Me')
class PregapTrackTest(MBJSONTest):
filename = 'track_pregap.json'
def test_track(self):
t = Track("1")
m = t.metadata
track_to_metadata(self.json_doc, t)
self.assertEqual(m['title'], 'Lady')
self.assertEqual(m['tracknumber'], '0')
self.assertEqual(m['~musicbrainz_tracknumber'], '0')
class NullTrackTest(MBJSONTest):
filename = 'track_null.json'
def test_track(self):
t = Track("1")
m = t.metadata
track_to_metadata(self.json_doc, t)
self.assertEqual(m, {})
class MediaTest(MBJSONTest):
filename = 'release_5medias.json'
def test_media_formats_from_node_multi(self):
formats = media_formats_from_node(self.json_doc['media'])
self.assertEqual('2×CD + 2×DVD-Video + Blu-ray', formats)
def test_medium_to_metadata_0(self):
m = Metadata()
medium_to_metadata(self.json_doc['media'][0], m)
self.assertEqual(m['discnumber'], '1')
self.assertEqual(m['media'], 'CD')
self.assertEqual(m['totaltracks'], '5')
self.assertEqual(m['discsubtitle'], 'The Original Album')
def test_medium_to_metadata_4(self):
m = Metadata()
medium_to_metadata(self.json_doc['media'][4], m)
self.assertEqual(m['discnumber'], '5')
self.assertEqual(m['media'], 'Blu-ray')
self.assertEqual(m['totaltracks'], '19')
self.assertEqual(m['discsubtitle'], 'High Resolution Audio and Audio‐Visual Material')
class MediaPregapTest(MBJSONTest):
filename = 'media_pregap.json'
def test_track(self):
m = Metadata()
medium_to_metadata(self.json_doc, m)
self.assertEqual(m['discnumber'], '1')
self.assertEqual(m['media'], 'Enhanced CD')
self.assertEqual(m['totaltracks'], '9')
class NullMediaTest(MBJSONTest):
filename = 'media_null.json'
def test_track(self):
m = Metadata()
medium_to_metadata(self.json_doc, m)
self.assertEqual(m, {})
class NullArtistTest(MBJSONTest):
filename = 'artist_null.json'
def test_artist(self):
m = Metadata()
artist_to_metadata(self.json_doc, m)
self.assertEqual(m, {})
class ArtistEndedTest(MBJSONTest):
filename = 'artist_ended.json'
def test_artist_ended(self):
m = Metadata()
artist_to_metadata(self.json_doc, m)
self.assertEqual(m['area'], 'France')
self.assertEqual(m['beginarea'], 'Paris')
self.assertEqual(m['begindate'], '1928-04-02')
self.assertEqual(m['endarea'], 'Paris')
self.assertEqual(m['enddate'], '1991-03-02')
self.assertEqual(m['gender'], 'Male')
self.assertEqual(m['musicbrainz_artistid'], 'b21ef19b-c6aa-4775-90d3-3cc3e067ce6d')
self.assertEqual(m['name'], 'Serge Gainsbourg')
self.assertEqual(m['type'], 'Person')
class ArtistTranslationTest(MBJSONTest):
filename = 'artist.json'
def test_locale_specific_match_first(self):
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": False,
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['en_CA', 'en'],
}
self.set_config_values(settings)
(artist_name, artist_sort_name) = _translate_artist_node(self.json_doc)
self.assertEqual(artist_name, 'Ed Sheeran (en_CA)')
def test_locale_specific_match_first_exc(self):
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": True,
"script_exceptions": [("LATIN", 0)],
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['en_CA', 'en'],
}
self.set_config_values(settings)
(artist_name, artist_sort_name) = _translate_artist_node(self.json_doc)
self.assertEqual(artist_name, 'Ed Sheeran')
def test_locale_specific_match_second(self):
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": False,
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['en_UK', 'en'],
}
self.set_config_values(settings)
(artist_name, artist_sort_name) = _translate_artist_node(self.json_doc)
self.assertEqual(artist_name, 'Ed Sheeran (en)')
def test_artist_match_root_locale_fallback(self):
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": False,
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['en_UK'],
}
self.set_config_values(settings)
(artist_name, artist_sort_name) = _translate_artist_node(self.json_doc)
self.assertEqual(artist_name, 'Ed Sheeran (en)')
def test_artist_no_match(self):
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": False,
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['de'],
}
self.set_config_values(settings)
(artist_name, artist_sort_name) = _translate_artist_node(self.json_doc)
self.assertEqual(artist_name, 'Ed Sheeran')
class ArtistTranslationArabicExceptionsTest(MBJSONTest):
filename = 'artist_arabic.json'
def test_locale_specific_match_first_exc1(self):
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": True,
"script_exceptions": [("LATIN", 0)],
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['en_CA', 'en'],
}
self.set_config_values(settings)
(artist_name, artist_sort_name) = _translate_artist_node(self.json_doc)
self.assertEqual(artist_name, 'Mohamed Mounir')
def test_locale_specific_match_first_exc2(self):
settings = {
"standardize_tracks": False,
"standardize_artists": False,
"standardize_releases": False,
"translate_artist_names": True,
"translate_artist_names_script_exception": True,
"script_exceptions": [("ARABIC", 0)],
"standardize_instruments": True,
"release_ars": True,
"preferred_release_countries": [],
"artist_locales": ['en_CA', 'en'],
}
self.set_config_values(settings)
(artist_name, artist_sort_name) = _translate_artist_node(self.json_doc)
self.assertEqual(artist_name, 'محمد منير')
class TestAliasesLocales(PicardTestCase):
def setUp(self):
self.maxDiff = None
self.aliases = [
{
"name": "Shearan",
"sort-name": "Shearan",
"primary": None,
"locale": None,
"type-id": ALIAS_TYPE_SEARCH_HINT_ID,
},
{
"primary": True,
"name": "Ed Sheeran (en)",
"sort-name": "Sheeran, Ed",
"type-id": ALIAS_TYPE_ARTIST_NAME_ID,
"locale": "en",
},
{
"primary": True,
"name": "Ed Sheeran (en_CA)",
"sort-name": "Sheeran, Ed",
"type-id": ALIAS_TYPE_ARTIST_NAME_ID,
"locale": "en_CA",
},
]
def test_1(self):
expect_full = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed')), 'en_CA': (0.8, ('Ed Sheeran (en_CA)', 'Sheeran, Ed'))}
expect_root = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed'))}
full_locales, root_locales = _locales_from_aliases(self.aliases)
self.assertDictEqual(expect_full, full_locales)
self.assertDictEqual(expect_root, root_locales)
def test_2(self):
self.aliases[2]['type-id'] = ALIAS_TYPE_LEGAL_NAME_ID
expect_full = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed')), 'en_CA': (0.65, ('Ed Sheeran (en_CA)', 'Sheeran, Ed'))}
expect_root = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed'))}
full_locales, root_locales = _locales_from_aliases(self.aliases)
self.assertDictEqual(expect_full, full_locales)
self.assertDictEqual(expect_root, root_locales)
def test_3(self):
self.aliases[0]['primary'] = True
del self.aliases[0]['locale']
expect_full = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed')), 'en_CA': (0.8, ('Ed Sheeran (en_CA)', 'Sheeran, Ed'))}
expect_root = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed'))}
full_locales, root_locales = _locales_from_aliases(self.aliases)
self.assertDictEqual(expect_full, full_locales)
self.assertDictEqual(expect_root, root_locales)
def test_4(self):
self.aliases[2]['type-id'] = ALIAS_TYPE_SEARCH_HINT_ID
expect_full = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed')), 'en_CA': (0.4, ('Ed Sheeran (en_CA)', 'Sheeran, Ed'))}
expect_root = {'en': (0.8, ('Ed Sheeran (en)', 'Sheeran, Ed'))}
full_locales, root_locales = _locales_from_aliases(self.aliases)
self.assertDictEqual(expect_full, full_locales)
self.assertDictEqual(expect_root, root_locales)
def test_5(self):
self.aliases[1]['locale'] = 'en_US'
self.aliases[1]['name'] = 'Ed Sheeran (en_US)'
expect_full = {'en_US': (0.8, ('Ed Sheeran (en_US)', 'Sheeran, Ed')), 'en_CA': (0.8, ('Ed Sheeran (en_CA)', 'Sheeran, Ed'))}
expect_root = {'en': (0.6, ('Ed Sheeran (en_US)', 'Sheeran, Ed'))}
full_locales, root_locales = _locales_from_aliases(self.aliases)
self.assertDictEqual(expect_full, full_locales)
self.assertDictEqual(expect_root, root_locales)
def test_6(self):
self.aliases[2]['locale'] = 'en'
self.aliases[2]['name'] = 'Ed Sheeran (en2)'
self.aliases[2]['type-id'] = ALIAS_TYPE_ARTIST_NAME_ID
self.aliases[1]['type-id'] = ALIAS_TYPE_LEGAL_NAME_ID
self.aliases[1]['name'] = 'Ed Sheeran (en1)'
expect_full = {'en': (0.8, ('Ed Sheeran (en2)', 'Sheeran, Ed'))}
expect_root = {'en': (0.8, ('Ed Sheeran (en2)', 'Sheeran, Ed'))}
full_locales, root_locales = _locales_from_aliases(self.aliases)
self.assertDictEqual(expect_full, full_locales)
self.assertDictEqual(expect_root, root_locales)
class ReleaseGroupTest(MBJSONTest):
filename = 'release_group.json'
def test_release_group(self):
m = Metadata()
r = ReleaseGroup("1")
release_group_to_metadata(self.json_doc, m, r)
self.assertEqual(m['musicbrainz_releasegroupid'], 'f5093c06-23e3-404f-aeaa-40f72885ee3a')
self.assertEqual(m['~releasegroup_firstreleasedate'], '1973-03-24')
self.assertEqual(m['originaldate'], '1973-03-24')
self.assertEqual(m['originalyear'], '1973')
self.assertEqual(m['releasetype'], 'album')
self.assertEqual(m['~primaryreleasetype'], 'album')
self.assertEqual(m['~releasegroup'], 'The Dark Side of the Moon')
self.assertEqual(r.genres, {'test2': 3, 'test': 6})
class NullReleaseGroupTest(MBJSONTest):
filename = 'release_group_null.json'
def test_release_group(self):
m = Metadata()
r = ReleaseGroup("1")
release_group_to_metadata(self.json_doc, m, r)
self.assertEqual(m, {})
class CountriesFromNodeTest(MBJSONTest):
filename = 'country.json'
def test_countries_from_node(self):
countries = countries_from_node(self.json_doc)
self.assertEqual(['GB'], countries)
def test_countries_from_node_no_event(self):
del self.json_doc["release-events"]
countries = countries_from_node(self.json_doc)
self.assertEqual([], countries)
def test_countries_from_node_no_area(self):
del self.json_doc["release-events"][0]["area"]
countries = countries_from_node(self.json_doc)
self.assertEqual([], countries)
class CountriesFromNodeNullTest(MBJSONTest):
filename = 'country_null.json'
def test_countries_from_node(self):
countries = countries_from_node(self.json_doc)
self.assertEqual(countries, [])
class DatesCountriesFromNodeTest(MBJSONTest):
filename = 'country.json'
def test_dates_countries_from_node(self):
dates, countries = release_dates_and_countries_from_node(self.json_doc)
self.assertEqual(['GB'], countries)
self.assertEqual(['1986-03'], dates)
def test_dates_countries_from_node_no_event(self):
del self.json_doc["release-events"]
dates, countries = release_dates_and_countries_from_node(self.json_doc)
self.assertEqual([], countries)
self.assertEqual([], dates)
class DatesCountriesFromNodeNullTest(MBJSONTest):
filename = 'country_null.json'
def test_dates_countries_from_node(self):
dates, countries = release_dates_and_countries_from_node(self.json_doc)
self.assertEqual(countries, [])
self.assertEqual([''], dates)
class LabelInfoTest(MBJSONTest):
filename = 'label_info.json'
def _label_info(self, n):
return label_info_from_node(self.json_doc['releases'][n]['label-info'])
def test_label_info_from_node_0(self):
self.assertEqual((['naïve'], ['NJ628311']), self._label_info(0))
def test_label_info_from_node_1(self):
self.assertEqual((['naïve'], []), self._label_info(1))
def test_label_info_from_node_2(self):
self.assertEqual((['naïve'], []), self._label_info(2))
def test_label_info_from_node_3(self):
self.assertEqual(([], ["[None]"]), self._label_info(3))
class NullLabelInfoTest(MBJSONTest):
filename = 'label_info_null.json'
def test_label_info_from_node_0(self):
label_info = label_info_from_node(self.json_doc['releases'][0]['label-info'])
self.assertEqual(label_info, ([], []))
class GetScoreTest(PicardTestCase):
def test_get_score(self):
for score, expected in ((42, 0.42), ('100', 1.0), (0, 0.0), (None, 1.0), ('', 1.0)):
self.assertEqual(expected, get_score({'score': score}))
def test_get_score_no_score(self):
self.assertEqual(1.0, get_score({}))
class ParseAttributeTest(PicardTestCase):
def test_1(self):
attrs, reltype, attr_credits = ('guest', 'keyboard'), 'instrument', {'keyboard': 'keyboards'}
result = _parse_attributes(attrs, reltype, attr_credits)
expected = 'guest keyboards'
self.assertEqual(expected, result)
def test_2(self):
attrs, reltype, attr_credits = (), 'vocal', {}
result = _parse_attributes(attrs, reltype, attr_credits)
expected = 'vocals'
self.assertEqual(expected, result)
def test_3(self):
attrs, reltype, attr_credits = ('guitar', 'keyboard'), 'instrument', {'keyboard': 'keyboards', 'guitar': 'weird guitar'}
result = _parse_attributes(attrs, reltype, attr_credits)
expected = 'weird guitar and keyboards'
self.assertEqual(expected, result)
class RelationsToMetadataTargetTypeUrlTest(PicardTestCase):
def test_invalid_asin_url(self):
m = Metadata()
relation = {
'type': 'amazon asin',
'url': {
'resource': 'http://www.amazon.com/dp/020530902x',
}
}
_relations_to_metadata_target_type_url(relation, m, None)
self.assertEqual('', m['asin'])
def test_has_asin_already(self):
m = Metadata({'asin': 'ASIN'})
relation = {
'type': 'amazon asin',
'url': {
'resource': 'http://www.amazon.com/dp/020530902X',
}
}
_relations_to_metadata_target_type_url(relation, m, None)
self.assertEqual('ASIN', m['asin'])
def test_valid_asin_url(self):
m = Metadata()
relation = {
'type': 'amazon asin',
'url': {
'resource': 'http://www.amazon.com/dp/020530902X',
}
}
_relations_to_metadata_target_type_url(relation, m, None)
self.assertEqual('020530902X', m['asin'])
def test_license_url(self):
m = Metadata()
relation = {
'type': 'license',
'url': {
'resource': 'https://URL.LICENSE',
}
}
_relations_to_metadata_target_type_url(relation, m, None)
self.assertEqual('https://URL.LICENSE', m['license'])
| 34,407
|
Python
|
.py
| 763
| 36.330275
| 132
| 0.619929
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,883
|
test_util_script_detector_weighted.py
|
metabrainz_picard/test/test_util_script_detector_weighted.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util.script_detector_weighted import (
detect_script_weighted,
list_script_weighted,
)
class WeightedScriptDetectionTest(PicardTestCase):
def test_detect_script_weighted(self):
scripts = detect_script_weighted("Latin, кириллический, Ελληνική")
self.assertAlmostEqual(scripts['LATIN'], 0.195, 3)
self.assertAlmostEqual(scripts['CYRILLIC'], 0.518, 3)
self.assertAlmostEqual(scripts['GREEK'], 0.287, 3)
scripts = detect_script_weighted("Latin, кириллический, Ελληνική", threshold=0.5)
script_keys = list(scripts.keys())
self.assertEqual(script_keys, ["CYRILLIC"])
scripts = detect_script_weighted("Latin")
self.assertEqual(scripts["LATIN"], 1)
scripts = detect_script_weighted("привет")
self.assertEqual(scripts["CYRILLIC"], 1)
scripts = detect_script_weighted("ελληνικά?")
self.assertEqual(scripts["GREEK"], 1)
scripts = detect_script_weighted("سماوي يدور")
self.assertEqual(scripts["ARABIC"], 1)
scripts = detect_script_weighted("שלום")
self.assertEqual(scripts["HEBREW"], 1)
scripts = detect_script_weighted("汉字")
self.assertEqual(scripts["CJK"], 1)
scripts = detect_script_weighted("한글")
self.assertEqual(scripts["HANGUL"], 1)
scripts = detect_script_weighted("ひらがな")
self.assertEqual(scripts["HIRAGANA"], 1)
scripts = detect_script_weighted("カタカナ")
self.assertEqual(scripts["KATAKANA"], 1)
scripts = detect_script_weighted("พยัญชนะ")
self.assertEqual(scripts["THAI"], 1)
scripts = detect_script_weighted("1234567890+-/*=,./!?")
self.assertEqual(scripts, {})
scripts = detect_script_weighted("")
self.assertEqual(scripts, {})
class ListScriptWeightedTest(PicardTestCase):
def test_list_script_weighted(self):
scripts = list_script_weighted("Cyrillic, кириллический, 汉字")
self.assertEqual(scripts, ['CYRILLIC', 'LATIN', 'CJK'])
scripts = list_script_weighted("Cyrillic, кириллический, 汉字", threshold=0.3)
self.assertEqual(scripts, ['CYRILLIC', 'LATIN'])
| 3,259
|
Python
|
.py
| 65
| 42.061538
| 89
| 0.70165
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,884
|
test_emptydir.py
|
metabrainz_picard/test/test_emptydir.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Philipp Wolfer
# Copyright (C) 2020 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
import os.path
from tempfile import NamedTemporaryFile
from test.picardtestcase import PicardTestCase
from picard.util import emptydir
class EmptyDirTestCommon(PicardTestCase):
def create_temp_dir(self, extra_files=(), extra_dirs=(), ignore_errors=False):
tempdir = self.mktmpdir(ignore_errors=ignore_errors)
for f in extra_files:
open(os.path.join(tempdir, f), 'a').close()
for f in extra_dirs:
os.mkdir(os.path.join(tempdir, f))
return tempdir
class EmptyDirTest(EmptyDirTestCommon):
def test_is_empty_dir_really_empty(self):
tempdir = self.create_temp_dir()
self.assertTrue(emptydir.is_empty_dir(tempdir))
def test_is_empty_dir_only_junk_files(self):
tempdir = self.create_temp_dir(extra_files=emptydir.JUNK_FILES)
self.assertTrue(len(os.listdir(tempdir)) > 0)
self.assertTrue(emptydir.is_empty_dir(tempdir))
def test_is_empty_dir_not_empty(self):
tempdir = self.create_temp_dir(extra_files=['.notempty'])
self.assertEqual(1, len(os.listdir(tempdir)))
self.assertFalse(emptydir.is_empty_dir(tempdir))
def test_is_empty_dir_custom_ignore_files(self):
ignored_files = ['.empty']
tempdir = self.create_temp_dir(extra_files=ignored_files)
self.assertEqual(1, len(os.listdir(tempdir)))
self.assertTrue(emptydir.is_empty_dir(tempdir, ignored_files=ignored_files))
def test_is_empty_dir_not_empty_child_dir(self):
tempdir = self.create_temp_dir(extra_dirs=['childdir'])
self.assertEqual(1, len(os.listdir(tempdir)))
self.assertFalse(emptydir.is_empty_dir(tempdir))
def test_is_empty_dir_on_file(self):
with NamedTemporaryFile() as f:
self.assertRaises(NotADirectoryError, emptydir.is_empty_dir, f.name)
class RmEmptyDirTest(EmptyDirTestCommon):
def test_rm_empty_dir_really_empty(self):
tempdir = self.create_temp_dir(ignore_errors=True)
self.assertTrue(os.path.isdir(tempdir))
emptydir.rm_empty_dir(tempdir)
self.assertFalse(os.path.exists(tempdir))
def test_rm_empty_dir_only_junk_files(self):
tempdir = self.create_temp_dir(extra_files=emptydir.JUNK_FILES, ignore_errors=True)
self.assertTrue(os.path.isdir(tempdir))
emptydir.rm_empty_dir(tempdir)
self.assertFalse(os.path.exists(tempdir))
def test_rm_empty_dir_not_empty(self):
tempdir = self.create_temp_dir(['.notempty'])
self.assertEqual(1, len(os.listdir(tempdir)))
self.assertRaises(emptydir.SkipRemoveDir, emptydir.rm_empty_dir, tempdir)
def test_rm_empty_dir_is_special(self):
tempdir = self.create_temp_dir()
orig_portected_dirs = emptydir.PROTECTED_DIRECTORIES
emptydir.PROTECTED_DIRECTORIES.add(os.path.realpath(tempdir))
self.assertRaises(emptydir.SkipRemoveDir, emptydir.rm_empty_dir, tempdir)
emptydir.PROTECTED_DIRECTORIES = orig_portected_dirs
def test_is_empty_dir_on_file(self):
with NamedTemporaryFile() as f:
self.assertRaises(NotADirectoryError, emptydir.rm_empty_dir, f.name)
| 4,016
|
Python
|
.py
| 80
| 44.025
| 91
| 0.71768
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,885
|
test_union_sorted_lists.py
|
metabrainz_picard/test/test_union_sorted_lists.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018, 2020 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util import union_sorted_lists
class UnionSortedListsTest(PicardTestCase):
def test_1(self):
list1 = [1, 2, 3]
list2 = [3, 4, 5, 6]
expected = [1, 2, 3, 4, 5, 6]
r = union_sorted_lists(list1, list2)
self.assertEqual(r, expected)
r = union_sorted_lists(list2, list1)
self.assertEqual(r, expected)
def test_2(self):
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
expected = [1, 2, 3, 4, 5, 6, 7, 8]
r = union_sorted_lists(list1, list2)
self.assertEqual(r, expected)
def test_3(self):
list1 = ['Back', 'Back', 'Front', 'Front, Side']
list2 = ['Front', 'Front', 'Front, Side']
expected = ['Back', 'Back', 'Front', 'Front', 'Front, Side']
r = union_sorted_lists(list1, list2)
self.assertEqual(r, expected)
def test_4(self):
list1 = ['Back', 'Back, Spine', 'Front', 'Front, Side']
list2 = ['Back', 'Back, Spine', 'Front', 'Front, Side']
expected = ['Back', 'Back, Spine', 'Front', 'Front, Side']
r = union_sorted_lists(list1, list2)
self.assertEqual(r, expected)
| 2,109
|
Python
|
.py
| 50
| 37.16
| 80
| 0.657073
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,886
|
test_clustering.py
|
metabrainz_picard/test/test_clustering.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.cluster import (
Cluster,
FileCluster,
tokenize,
)
from picard.file import File
class TokenizeTest(PicardTestCase):
def test_tokenize(self):
token = tokenize("")
self.assertEqual(token, "")
token = tokenize(" \t ")
self.assertEqual(token, "")
token = tokenize(" A\tWord-test ")
self.assertEqual(token, "awordtest")
class ClusterTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({
'windows_compatibility': False,
'va_name': 'Diverse Interpreten',
})
def _create_file(self, album, artist, filename="foo.mp3"):
file = File(filename)
file.metadata['album'] = album
file.metadata['artist'] = artist
return file
def assertClusterEqual(self, album, artist, files, cluster):
self.assertEqual(album, cluster.title)
self.assertEqual(artist, cluster.artist)
self.assertEqual(set(files), set(cluster.files))
def test_cluster_none(self):
clusters = list(Cluster.cluster([]))
# No cluster is being created
self.assertEqual(0, len(clusters))
def test_cluster_single_file(self):
files = [
self._create_file('album foo', 'artist foo'),
]
clusters = list(Cluster.cluster(files))
self.assertEqual(1, len(clusters))
def test_cluster_single_cluster(self):
files = [
self._create_file('album foo', 'artist bar'),
self._create_file('album foo', 'artist foo'),
self._create_file('album foo', 'artist foo'),
]
clusters = list(Cluster.cluster(files))
self.assertEqual(1, len(clusters))
self.assertClusterEqual('album foo', 'artist foo', files, clusters[0])
def test_cluster_multi(self):
files = [
self._create_file('album cluster1', 'artist bar'),
self._create_file('album cluster2', 'artist foo'),
self._create_file('album cluster1', 'artist foo'),
self._create_file('albumcluster2', 'artist bar'),
self._create_file('album single', 'artist bar'),
]
clusters = list(Cluster.cluster(files))
self.assertEqual(3, len(clusters))
self.assertClusterEqual('album cluster1', 'artist bar', {files[0], files[2]}, clusters[0])
self.assertClusterEqual('album cluster2', 'artist foo', {files[1], files[3]}, clusters[1])
self.assertClusterEqual('album single', 'artist bar', {files[4]}, clusters[2])
def test_cluster_by_path(self):
files = [
self._create_file(None, None, 'artist1/album1/foo1.ogg'),
self._create_file(None, None, 'album2/foo1.ogg'),
self._create_file(None, None, 'artist1/album1/foo2.ogg'),
self._create_file(None, None, 'album2/foo2.ogg'),
self._create_file(None, None, 'single/foo.ogg'),
self._create_file(None, None, 'album1/foo3.ogg'),
]
clusters = list(Cluster.cluster(files))
self.assertEqual(3, len(clusters))
self.assertClusterEqual('album1', 'artist1', {files[0], files[2], files[5]}, clusters[0])
self.assertClusterEqual('album2', 'Diverse Interpreten', {files[1], files[3]}, clusters[1])
self.assertClusterEqual('single', 'Diverse Interpreten', {files[4]}, clusters[2])
def test_cluster_no_metadata(self):
files = [
self._create_file(None, None, 'foo1.ogg'),
self._create_file(None, None, 'foo2.ogg'),
self._create_file(None, None, 'foo3.ogg'),
]
clusters = list(Cluster.cluster(files))
self.assertEqual(0, len(clusters))
def test_common_artist_name(self):
files = [
self._create_file('cluster 1', 'artist 1'),
self._create_file('cluster 1', 'artist 2'),
self._create_file('cluster 1', 'artist2'),
self._create_file('cluster 1', 'artist 1'),
self._create_file('cluster 1', 'artist 2'),
]
clusters = list(Cluster.cluster(files))
self.assertEqual(1, len(clusters))
self.assertClusterEqual('cluster 1', 'artist 2', files, clusters[0])
class FileClusterTest(PicardTestCase):
def test_single(self):
file = File('foo')
fc = FileCluster()
fc.add('album 1', 'artist 1', file)
self.assertEqual('album 1', fc.title)
self.assertEqual('artist 1', fc.artist)
self.assertEqual([file], list(fc.files))
def test_multi(self):
files = [
File('foo1'),
File('foo2'),
File('foo3'),
File('foo4'),
File('foo5'),
]
fc = FileCluster()
fc.add('album 1', 'artist1', files[0])
fc.add('Album 1', 'artist 2', files[1])
fc.add('album\t1', 'Artist 1', files[2])
fc.add('Album 1', 'Artist 2', files[3])
fc.add('album 2', 'Artist 1', files[4])
self.assertEqual('Album 1', fc.title)
self.assertEqual('Artist 1', fc.artist)
self.assertEqual(files, list(fc.files))
| 6,051
|
Python
|
.py
| 141
| 34.879433
| 99
| 0.621814
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,887
|
test_webservice.py
|
metabrainz_picard/test/test_webservice.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2017-2018 Wieland Hoffmann
# Copyright (C) 2018, 2020-2021 Laurent Monin
# Copyright (C) 2019-2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import sys
from unittest.mock import (
MagicMock,
patch,
)
from PyQt6.QtCore import QUrl
from PyQt6.QtNetwork import (
QNetworkProxy,
QNetworkRequest,
)
from test.picardtestcase import PicardTestCase
from picard import config
from picard.webservice import (
TEMP_ERRORS_RETRIES,
RequestPriorityQueue,
RequestTask,
UnknownResponseParserError,
WebService,
WSRequest,
ratecontrol,
)
from picard.webservice.utils import (
host_port_to_url,
hostkey_from_url,
port_from_qurl,
)
PROXY_SETTINGS = {
"use_proxy": True,
"proxy_type": 'http',
"proxy_server_host": '127.0.0.1',
"proxy_server_port": 3128,
"proxy_username": 'user',
"proxy_password": 'password',
"network_transfer_timeout_seconds": 30,
"network_cache_size_bytes": 100*1000*1000,
}
def dummy_handler(*args, **kwargs):
"""Dummy handler method for tests"""
class WebServiceTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({
'use_proxy': False,
'server_host': '',
'network_transfer_timeout_seconds': 30,
'network_cache_size_bytes': 100*1000*1000,
})
self.ws = WebService()
@patch.object(WebService, 'add_task')
def test_webservice_url_method_calls(self, mock_add_task):
url = "http://abc.xyz"
handler = dummy_handler
data = None
def get_wsreq(mock_add_task):
return mock_add_task.call_args[0][1]
self.ws.get_url(url=url, handler=handler)
self.assertEqual(1, mock_add_task.call_count)
self.assertEqual('abc.xyz', get_wsreq(mock_add_task).host)
self.assertEqual(80, get_wsreq(mock_add_task).port)
self.assertIn("GET", get_wsreq(mock_add_task).method)
self.ws.post_url(url=url, data=data, handler=handler)
self.assertIn("POST", get_wsreq(mock_add_task).method)
self.ws.put_url(url=url, data=data, handler=handler)
self.assertIn("PUT", get_wsreq(mock_add_task).method)
self.ws.delete_url(url=url, handler=handler)
self.assertIn("DELETE", get_wsreq(mock_add_task).method)
self.ws.download_url(url=url, handler=handler)
self.assertIn("GET", get_wsreq(mock_add_task).method)
self.assertEqual(5, mock_add_task.call_count)
class WebServiceTaskTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({
'use_proxy': False,
'network_transfer_timeout_seconds': 30,
'network_cache_size_bytes': 100*1000*1000,
})
self.ws = WebService()
self.queue = self.ws._queue = MagicMock()
# Patching the QTimers since they can only be started in a QThread
self.ws._timer_run_next_task = MagicMock()
self.ws._timer_count_pending_requests = MagicMock()
def test_add_task(self):
request = WSRequest(
method='GET',
url='http://abc.xyz',
handler=dummy_handler,
)
func = 1
task = self.ws.add_task(func, request)
self.assertEqual((request.get_host_key(), func, 0), task)
self.ws._queue.add_task.assert_called_with(task, False)
request.important = True
task = self.ws.add_task(func, request)
self.ws._queue.add_task.assert_called_with(task, True)
def test_add_task_calls_timers(self):
mock_timer1 = self.ws._timer_run_next_task
mock_timer2 = self.ws._timer_count_pending_requests
request = WSRequest(
method='GET',
url='http://abc.xyz',
handler=dummy_handler,
)
self.ws.add_task(0, request)
mock_timer1.start.assert_not_called()
mock_timer2.start.assert_not_called()
# Test if timer start was called in case it was inactive
mock_timer1.isActive.return_value = False
mock_timer2.isActive.return_value = False
self.ws.add_task(0, request)
mock_timer1.start.assert_called_with(0)
mock_timer2.start.assert_called_with(0)
def test_remove_task(self):
task = RequestTask(('example.com', 80), dummy_handler, priority=0)
self.ws.remove_task(task)
self.ws._queue.remove_task.assert_called_with(task)
def test_remove_task_calls_timers(self):
mock_timer = self.ws._timer_count_pending_requests
task = RequestTask(('example.com', 80), dummy_handler, priority=0)
self.ws.remove_task(task)
mock_timer.start.assert_not_called()
mock_timer.isActive.return_value = False
self.ws.remove_task(task)
mock_timer.start.assert_called_with(0)
def test_run_next_task(self):
mock_timer = self.ws._timer_run_next_task
self.ws._queue.run_ready_tasks.return_value = sys.maxsize
self.ws._run_next_task()
self.ws._queue.run_ready_tasks.assert_called()
mock_timer.start.assert_not_called()
def test_run_next_task_starts_next(self):
mock_timer = self.ws._timer_run_next_task
delay = 42
self.ws._queue.run_ready_tasks.return_value = delay
self.ws._run_next_task()
self.ws._queue.run_ready_tasks.assert_called()
mock_timer.start.assert_called_with(42)
class RequestTaskTest(PicardTestCase):
def test_from_request(self):
request = WSRequest(
method='GET',
url='https://example.com',
handler=dummy_handler,
priority=True,
)
func = 1
task = RequestTask.from_request(request, func)
self.assertEqual(request.get_host_key(), task.hostkey)
self.assertEqual(func, task.func)
self.assertEqual(1, task.priority)
self.assertEqual((request.get_host_key(), func, 1), task)
class RequestPriorityQueueTest(PicardTestCase):
def test_add_task(self):
queue = RequestPriorityQueue(ratecontrol)
key = ("abc.xyz", 80)
task1 = RequestTask(key, dummy_handler, priority=0)
queue.add_task(task1)
task2 = RequestTask(key, dummy_handler, priority=1)
queue.add_task(task2)
task3 = RequestTask(key, dummy_handler, priority=0)
queue.add_task(task3, important=True)
task4 = RequestTask(key, dummy_handler, priority=1)
queue.add_task(task4, important=True)
# Test if 2 requests were added in each queue
self.assertEqual(len(queue._queues[0][key]), 2)
self.assertEqual(len(queue._queues[1][key]), 2)
# Test if important request was added ahead in the queue
self.assertEqual(queue._queues[0][key][0], task3.func)
self.assertEqual(queue._queues[0][key][1], task1.func)
self.assertEqual(queue._queues[1][key][0], task4.func)
self.assertEqual(queue._queues[1][key][1], task2.func)
def test_remove_task(self):
queue = RequestPriorityQueue(ratecontrol)
key = ("abc.xyz", 80)
# Add a task and check for its existence
task = RequestTask(key, dummy_handler, priority=0)
task = queue.add_task(task)
self.assertIn(key, queue._queues[0])
self.assertEqual(len(queue._queues[0][key]), 1)
# Remove the task and check
queue.remove_task(task)
self.assertIn(key, queue._queues[0])
self.assertEqual(len(queue._queues[0][key]), 0)
# Try to remove a non existing task and check for errors
non_existing_task = (1, "a", "b")
queue.remove_task(non_existing_task)
def test_run_task(self):
mock_ratecontrol = MagicMock()
delay_func = mock_ratecontrol.get_delay_to_next_request = MagicMock()
queue = RequestPriorityQueue(mock_ratecontrol)
key = ("abc.xyz", 80)
# Patching the get delay function to delay the 2nd task on queue to the next call
delay_func.side_effect = [(False, 0), (True, 0), (False, 0), (False, 0), (False, 0), (False, 0)]
func1 = MagicMock()
task1 = RequestTask(key, func1, priority=0)
queue.add_task(task1)
func2 = MagicMock()
task2 = RequestTask(key, func2, priority=1)
queue.add_task(task2)
task3 = RequestTask(key, func1, priority=0)
queue.add_task(task3)
task4 = RequestTask(key, func1, priority=0)
queue.add_task(task4)
# Ensure no tasks are run before run_next_task is called
self.assertEqual(func1.call_count, 0)
queue.run_ready_tasks()
# Ensure priority task is run first
self.assertEqual(func2.call_count, 1)
self.assertEqual(func1.call_count, 0)
self.assertIn(key, queue._queues[1])
# Ensure that the calls are run as expected
queue.run_ready_tasks()
self.assertEqual(func1.call_count, 1)
# Checking if the cleanup occurred on the prio queue
self.assertNotIn(key, queue._queues[1])
# Check the call counts on proper execution of tasks
queue.run_ready_tasks()
self.assertEqual(func1.call_count, 2)
queue.run_ready_tasks()
self.assertEqual(func1.call_count, 3)
# Ensure that the clean up happened on the normal queue
queue.run_ready_tasks()
self.assertEqual(func1.call_count, 3)
self.assertNotIn(key, queue._queues[0])
def test_count(self):
queue = RequestPriorityQueue(ratecontrol)
key = ("abc.xyz", 80)
self.assertEqual(0, queue.count())
task1 = RequestTask(key, dummy_handler, priority=0)
queue.add_task(task1)
self.assertEqual(1, queue.count())
task2 = RequestTask(key, dummy_handler, priority=1)
queue.add_task(task2)
self.assertEqual(2, queue.count())
task3 = RequestTask(key, dummy_handler, priority=0)
queue.add_task(task3, important=True)
self.assertEqual(3, queue.count())
task4 = RequestTask(key, dummy_handler, priority=1)
queue.add_task(task4, important=True)
self.assertEqual(4, queue.count())
queue.remove_task(task1)
self.assertEqual(3, queue.count())
queue.remove_task(task2)
self.assertEqual(2, queue.count())
queue.remove_task(task3)
self.assertEqual(1, queue.count())
queue.remove_task(task4)
self.assertEqual(0, queue.count())
class WebServiceProxyTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values(PROXY_SETTINGS)
def test_proxy_setup(self):
proxy_types = [
('http', QNetworkProxy.ProxyType.HttpProxy),
('socks', QNetworkProxy.ProxyType.Socks5Proxy),
]
for proxy_type, expected_qt_type in proxy_types:
config.setting['proxy_type'] = proxy_type
ws = WebService()
proxy = ws.manager.proxy()
self.assertEqual(proxy.type(), expected_qt_type)
self.assertEqual(proxy.user(), PROXY_SETTINGS['proxy_username'])
self.assertEqual(proxy.password(), PROXY_SETTINGS['proxy_password'])
self.assertEqual(proxy.hostName(), PROXY_SETTINGS['proxy_server_host'])
self.assertEqual(proxy.port(), PROXY_SETTINGS['proxy_server_port'])
class ParserHookTest(PicardTestCase):
def test_parser_hook(self):
WebService.add_parser('A', 'mime', 'parser')
self.assertIn('A', WebService.PARSERS)
self.assertEqual(WebService.PARSERS['A'].mimetype, 'mime')
self.assertEqual(WebService.PARSERS['A'].mimetype, WebService.get_response_mimetype('A'))
self.assertEqual(WebService.PARSERS['A'].parser, 'parser')
self.assertEqual(WebService.PARSERS['A'].parser, WebService.get_response_parser('A'))
with self.assertRaises(UnknownResponseParserError):
WebService.get_response_parser('B')
with self.assertRaises(UnknownResponseParserError):
WebService.get_response_mimetype('B')
class WSRequestTest(PicardTestCase):
def test_init_minimal(self):
request = WSRequest(url='https://example.org/path', method='GET', handler=dummy_handler)
self.assertEqual(request.host, 'example.org')
self.assertEqual(request.port, 443)
self.assertEqual(request.path, '/path')
self.assertEqual(request.handler, dummy_handler)
self.assertEqual(request.method, 'GET')
self.assertEqual(request.get_host_key(), ('example.org', 443))
self.assertIsNone(request.parse_response_type)
self.assertIsNone(request.data)
self.assertIsNone(request.cacheloadcontrol)
self.assertIsNone(request.request_mimetype)
self.assertFalse(request.mblogin)
self.assertFalse(request.refresh)
self.assertFalse(request.priority)
self.assertFalse(request.important)
self.assertFalse(request.has_auth)
def test_init_minimal_extra(self):
request = WSRequest(
url='https://example.org/path',
method='GET',
handler=dummy_handler,
priority=True,
important=True,
refresh=True,
)
self.assertTrue(request.priority)
self.assertTrue(request.important)
self.assertTrue(request.refresh)
def test_init_minimal_qurl(self):
url = 'https://example.org/path?q=1'
request = WSRequest(url=QUrl(url), method='GET', handler=dummy_handler)
self.assertEqual(request.url().toString(), url)
def test_init_port_80(self):
request = WSRequest(url='http://example.org/path', method='GET', handler=dummy_handler)
self.assertEqual(request.port, 80)
def test_init_port_other(self):
request = WSRequest(url='http://example.org:666/path', method='GET', handler=dummy_handler)
self.assertEqual(request.port, 666)
def test_missing_url(self):
with self.assertRaises(AssertionError):
WSRequest(method='GET', handler=dummy_handler)
def test_missing_method(self):
with self.assertRaises(AssertionError):
WSRequest(url='http://x', handler=dummy_handler)
def test_missing_handler(self):
with self.assertRaises(AssertionError):
WSRequest(url='http://x', method='GET')
def test_invalid_method(self):
with self.assertRaises(AssertionError):
WSRequest(url='http://x', method='XXX', handler=dummy_handler)
def test_set_cacheloadcontrol(self):
request = WSRequest(
url='http://example.org/path',
method='GET',
handler=dummy_handler,
cacheloadcontrol=QNetworkRequest.CacheLoadControl.AlwaysNetwork,
)
self.assertEqual(request.cacheloadcontrol, QNetworkRequest.CacheLoadControl.AlwaysNetwork)
def test_set_parse_response_type(self):
WebService.add_parser('A', 'mime', 'parser')
request = WSRequest(
url='http://example.org/path',
method='GET',
handler=dummy_handler,
parse_response_type='A',
)
self.assertEqual(request.response_mimetype, 'mime')
self.assertEqual(request.response_parser, 'parser')
def test_set_invalid_parse_response_type(self):
WebService.add_parser('A', 'mime', 'parser')
request = WSRequest(
url='http://example.org/path',
method='GET',
handler=dummy_handler,
parse_response_type='invalid',
)
self.assertEqual(request.response_mimetype, None)
self.assertEqual(request.response_parser, None)
def test_set_mblogin_access_token(self):
request = WSRequest(
url='http://example.org/path',
method='POST',
handler=dummy_handler,
)
# setter
request.mblogin = 'test'
# getter
self.assertEqual(request.mblogin, 'test')
# auth needs a token too
self.assertFalse(request.has_auth)
# setter
request.access_token = 'token' # nosec
# getter
self.assertEqual(request.access_token, 'token')
# auth is now possible
self.assertTrue(request.has_auth)
def test_set_data(self):
request = WSRequest(
url='http://example.org/path',
method='POST',
handler=dummy_handler,
data='data',
)
self.assertEqual(request.data, 'data')
def test_set_retries_reached(self):
request = WSRequest(
url='http://example.org/path',
method='GET',
handler=dummy_handler,
)
for i in range(0, TEMP_ERRORS_RETRIES):
self.assertEqual(request.mark_for_retry(), i+1)
self.assertTrue(request.max_retries_reached())
def test_set_retries_not_reached(self):
request = WSRequest(
url='http://example.org/path',
method='GET',
handler=dummy_handler,
)
self.assertTrue(TEMP_ERRORS_RETRIES > 1)
self.assertEqual(request.mark_for_retry(), 1)
self.assertFalse(request.max_retries_reached())
def test_queryargs(self):
request = WSRequest(
url='http://example.org/path?a=1',
method='GET',
handler=dummy_handler,
queryargs={'a': 2, 'b': 'x%20x', 'c': '1+2', 'd': '&', 'e': '?'},
)
expected = 'http://example.org/path?a=1&a=2&b=x x&c=1+2&d=%26&e=?'
self.assertEqual(request.url().toString(), expected)
def test_unencoded_queryargs(self):
request = WSRequest(
url='http://example.org/path?a=1',
method='GET',
handler=dummy_handler,
unencoded_queryargs={'a': 2, 'b': 'x%20x', 'c': '1+2', 'd': '&', 'e': '?'},
)
expected = 'http://example.org/path?a=1&a=2&b=x%2520x&c=1%2B2&d=%26&e=%3F'
self.assertEqual(request.url().toString(), expected)
def test_mixed_queryargs(self):
request = WSRequest(
url='http://example.org/path?a=1',
method='GET',
handler=dummy_handler,
queryargs={'a': '2&', 'b': '1&', 'c': '&'},
unencoded_queryargs={'a': '1&', 'b': '2&', 'd': '&'},
)
expected = 'http://example.org/path?a=1&a=1%26&b=2%26&c=%26&d=%26'
self.assertEqual(request.url().toString(), expected)
class WebServiceUtilsTest(PicardTestCase):
def test_port_from_qurl_http(self):
self.assertEqual(port_from_qurl(QUrl('http://example.org')), 80)
def test_port_from_qurl_http_other(self):
self.assertEqual(port_from_qurl(QUrl('http://example.org:666')), 666)
def test_port_from_qurl_https(self):
self.assertEqual(port_from_qurl(QUrl('https://example.org')), 443)
def test_port_from_qurl_https_other(self):
self.assertEqual(port_from_qurl(QUrl('https://example.org:666')), 666)
def test_port_from_qurl_exception(self):
with self.assertRaises(AttributeError):
port_from_qurl('xxx')
def test_hostkey_from_qurl_http(self):
self.assertEqual(hostkey_from_url(QUrl('http://example.org')), ('example.org', 80))
def test_hostkey_from_url_https_other(self):
self.assertEqual(hostkey_from_url('https://example.org:666'), ('example.org', 666))
def test_host_port_to_url_http_80(self):
self.assertEqual(host_port_to_url('example.org', 80, as_string=True), 'http://example.org')
def test_host_port_to_url_http_80_qurl(self):
self.assertEqual(host_port_to_url('example.org', 80).toString(), 'http://example.org')
def test_host_port_to_url_https_443(self):
self.assertEqual(host_port_to_url('example.org', 443, as_string=True), 'https://example.org')
def test_host_port_to_url_https_scheme_80(self):
self.assertEqual(host_port_to_url('example.org', 80, scheme='https', as_string=True), 'https://example.org:80')
def test_host_port_to_url_http_666_with_path(self):
self.assertEqual(host_port_to_url('example.org', 666, path='/abc', as_string=True), 'http://example.org:666/abc')
| 21,039
|
Python
|
.py
| 478
| 35.495816
| 121
| 0.640424
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,888
|
test_const_appdirs.py
|
metabrainz_picard/test/test_const_appdirs.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import os.path
import unittest
from test.picardtestcase import PicardTestCase
from picard.const.appdirs import (
cache_folder,
config_folder,
plugin_folder,
)
from picard.const.sys import (
IS_LINUX,
IS_MACOS,
IS_WIN,
)
class AppPathsTest(PicardTestCase):
def assert_home_path_equals(self, expected, actual):
self.assertEqual(os.path.normpath(os.path.expanduser(expected)), actual)
@unittest.skipUnless(IS_WIN, "Windows test")
def test_config_folder_win(self):
self.assert_home_path_equals('~/AppData/Local/MusicBrainz/Picard', config_folder())
@unittest.skipUnless(IS_MACOS, "macOS test")
def test_config_folder_macos(self):
self.assert_home_path_equals('~/Library/Preferences/MusicBrainz/Picard', config_folder())
@unittest.skipUnless(IS_LINUX, "Linux test")
def test_config_folder_linux(self):
self.assert_home_path_equals('~/.config/MusicBrainz/Picard', config_folder())
@unittest.skipUnless(IS_WIN, "Windows test")
def test_cache_folder_win(self):
self.assert_home_path_equals('~/AppData/Local/MusicBrainz/Picard/cache', cache_folder())
@unittest.skipUnless(IS_MACOS, "macOS test")
def test_cache_folder_macos(self):
self.assert_home_path_equals('~/Library/Caches/MusicBrainz/Picard', cache_folder())
@unittest.skipUnless(IS_LINUX, "Linux test")
def test_cache_folder_linux(self):
self.assert_home_path_equals('~/.cache/MusicBrainz/Picard', cache_folder())
@unittest.skipUnless(IS_WIN, "Windows test")
def test_plugin_folder_win(self):
self.assert_home_path_equals('~/AppData/Local/MusicBrainz/Picard/plugins', plugin_folder())
@unittest.skipUnless(IS_MACOS, "macOS test")
def test_plugin_folder_macos(self):
self.assert_home_path_equals('~/Library/Preferences/MusicBrainz/Picard/plugins', plugin_folder())
@unittest.skipUnless(IS_LINUX, "Linux test")
def test_plugin_folder_linux(self):
self.assert_home_path_equals('~/.config/MusicBrainz/Picard/plugins', plugin_folder())
| 2,929
|
Python
|
.py
| 63
| 42.396825
| 105
| 0.737285
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,889
|
test_config.py
|
metabrainz_picard/test/test_config.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
# Copyright (C) 2019-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import logging
import os
import shutil
from test.picardtestcase import PicardTestCase
from picard.config import (
BoolOption,
Config,
FloatOption,
IntOption,
ListOption,
Option,
OptionError,
TextOption,
)
class TestPicardConfigCommon(PicardTestCase):
def setUp(self):
super().setUp()
self.tmp_directory = self.mktmpdir()
self.configpath = os.path.join(self.tmp_directory, 'test.ini')
shutil.copy(os.path.join('test', 'data', 'test.ini'), self.configpath)
self.addCleanup(os.remove, self.configpath)
self.config = Config.from_file(None, self.configpath)
self.addCleanup(self.cleanup_config_obj)
self.config.application["version"] = "testing"
logging.disable(logging.ERROR)
Option.registry = {}
def cleanup_config_obj(self):
# Ensure QSettings do not recreate the file on exit
self.config.sync()
del self.config
self.config = None
class TestPicardConfig(TestPicardConfigCommon):
def test_remove(self):
TextOption("setting", "text_option", "abc")
self.config.setting["text_option"] = "def"
self.assertEqual(self.config.setting["text_option"], "def")
self.config.setting.remove("text_option")
self.assertEqual(self.config.setting["text_option"], "abc")
class TestPicardConfigOption(TestPicardConfigCommon):
def test_basic_option(self):
Option("setting", "option", "abc")
self.assertEqual(self.config.setting["option"], "abc")
self.config.setting["option"] = "def"
self.assertEqual(self.config.setting["option"], "def")
def test_option_get(self):
Option("setting", "option", "abc")
opt = Option.get("setting", "option")
self.assertIsInstance(opt, Option)
self.assertEqual(opt.default, "abc")
self.assertIsNone(Option.get("setting", "not_existing_option"))
def test_option_without_title(self):
Option("setting", "option", "abc")
opt = Option.get("setting", "option")
self.assertIsNone(opt.title)
def test_option_with_title(self):
Option("setting", "option", "abc", title="Title")
opt = Option.get("setting", "option")
self.assertEqual(opt.title, "Title")
def test_option_exists(self):
Option("setting", "option", "abc")
self.assertTrue(Option.exists("setting", "option"))
self.assertFalse(Option.exists("setting", "not_option"))
def test_option_add_if_missing(self):
Option("setting", "option", "abc")
Option.add_if_missing("setting", "option", "def")
self.assertEqual(self.config.setting["option"], "abc")
Option.add_if_missing("setting", "missing_option", "def", title="TITLE")
self.assertEqual(self.config.setting["missing_option"], "def")
self.assertEqual(Option.get_title('setting', 'missing_option'), 'TITLE')
def test_double_declaration(self):
Option("setting", "option", "abc")
with self.assertRaisesRegex(OptionError, r"^Option setting/option: Already declared"):
Option("setting", "option", "def")
def test_get_default(self):
Option("setting", "option", "abc")
self.assertEqual(Option.get_default("setting", "option"), "abc")
with self.assertRaisesRegex(OptionError, "^Option setting/unknown_option: No such option"):
Option.get_default("setting", "unknown_option")
def test_get_title(self):
Option("setting", "option", "abc", title="Title")
self.assertEqual(Option.get_title("setting", "option"), "Title")
with self.assertRaisesRegex(OptionError, "^Option setting/unknown_option: No such option"):
Option.get_title("setting", "unknown_option")
class TestPicardConfigSection(TestPicardConfigCommon):
def test_as_dict(self):
TextOption("setting", "text_option", "abc")
BoolOption("setting", "bool_option", True)
IntOption("setting", "int_option", 42)
self.config.setting["int_option"] = 123
expected = {
"text_option": "abc",
"bool_option": True,
"int_option": 123,
}
self.assertEqual(expected, self.config.setting.as_dict())
class TestPicardConfigTextOption(TestPicardConfigCommon):
# TextOption
def test_text_opt_convert(self):
opt = TextOption("setting", "text_option", "abc")
self.assertEqual(opt.convert(123), "123")
def test_text_opt_no_config(self):
TextOption("setting", "text_option", "abc")
# test default, nothing in config yet
self.assertEqual(self.config.setting["text_option"], "abc")
self.assertIs(type(self.config.setting["text_option"]), str)
def test_text_opt_set_read_back(self):
TextOption("setting", "text_option", "abc")
# set option to "def", and read back
self.config.setting["text_option"] = "def"
self.assertEqual(self.config.setting["text_option"], "def")
self.assertIs(type(self.config.setting["text_option"]), str)
def test_text_opt_set_none(self):
TextOption("setting", "text_option", "abc")
# set option to None
self.config.setting["text_option"] = None
self.assertEqual(self.config.setting["text_option"], "")
def test_text_opt_set_empty(self):
TextOption("setting", "text_option", "abc")
# set option to ""
self.config.setting["text_option"] = ""
self.assertEqual(self.config.setting["text_option"], "")
def test_text_opt_invalid_value(self):
TextOption("setting", "text_option", "abc")
# store invalid value in config file directly
self.config.setValue('setting/text_option', object)
self.assertEqual(self.config.setting["text_option"], 'abc')
class TestPicardConfigBoolOption(TestPicardConfigCommon):
# BoolOption
def test_bool_opt_convert(self):
opt = BoolOption("setting", "bool_option", False)
self.assertEqual(opt.convert(1), True)
def test_bool_opt_no_config(self):
BoolOption("setting", "bool_option", True)
# test default, nothing in config yet
self.assertEqual(self.config.setting["bool_option"], True)
self.assertIs(type(self.config.setting["bool_option"]), bool)
def test_bool_opt_set_read_back(self):
BoolOption("setting", "bool_option", True)
# set option and read back
self.config.setting["bool_option"] = False
self.assertEqual(self.config.setting["bool_option"], False)
self.assertIs(type(self.config.setting["bool_option"]), bool)
def test_bool_opt_set_str(self):
BoolOption("setting", "bool_option", False)
# set option to invalid value
self.config.setting["bool_option"] = 'yes'
self.assertEqual(self.config.setting["bool_option"], True)
def test_bool_opt_set_empty_str(self):
BoolOption("setting", "bool_option", True)
# set option to empty string
self.config.setting["bool_option"] = ''
self.assertEqual(self.config.setting["bool_option"], False)
def test_bool_opt_set_none(self):
BoolOption("setting", "bool_option", True)
# set option to None value
self.config.setting["bool_option"] = None
self.assertEqual(self.config.setting["bool_option"], False)
def test_bool_opt_set_direct_str(self):
BoolOption("setting", "bool_option", False)
# store invalid bool value in config file directly
self.config.setValue('setting/bool_option', 'yes')
self.assertEqual(self.config.setting["bool_option"], True)
def test_bool_opt_set_direct_str_true(self):
BoolOption("setting", "bool_option", False)
# store 'true' directly, it should be ok, due to conversion
self.config.setValue('setting/bool_option', 'true')
self.assertEqual(self.config.setting["bool_option"], True)
class TestPicardConfigIntOption(TestPicardConfigCommon):
# IntOption
def test_int_opt_convert(self):
opt = IntOption("setting", "int_option", 666)
self.assertEqual(opt.convert("123"), 123)
def test_int_opt_no_config(self):
IntOption("setting", "int_option", 666)
# test default, nothing in config yet
self.assertEqual(self.config.setting["int_option"], 666)
self.assertIs(type(self.config.setting["int_option"]), int)
def test_int_opt_set_read_back(self):
IntOption("setting", "int_option", 666)
# set option and read back
self.config.setting["int_option"] = 333
self.assertEqual(self.config.setting["int_option"], 333)
self.assertIs(type(self.config.setting["int_option"]), int)
def test_int_opt_not_int(self):
IntOption("setting", "int_option", 666)
# set option to invalid value
self.config.setting["int_option"] = 'invalid'
self.assertEqual(self.config.setting["int_option"], 666)
def test_int_opt_set_none(self):
IntOption("setting", "int_option", 666)
# set option to None
self.config.setting["int_option"] = None
self.assertEqual(self.config.setting["int_option"], 666)
def test_int_opt_direct_invalid(self):
IntOption("setting", "int_option", 666)
# store invalid int value in config file directly
self.config.setValue('setting/int_option', 'x333')
self.assertEqual(self.config.setting["int_option"], 666)
def test_int_opt_direct_validstr(self):
IntOption("setting", "int_option", 666)
# store int as string directly, it should be ok, due to conversion
self.config.setValue('setting/int_option', '333')
self.assertEqual(self.config.setting["int_option"], 333)
class TestPicardConfigFloatOption(TestPicardConfigCommon):
# FloatOption
def test_float_opt_convert(self):
opt = FloatOption("setting", "float_option", 666.6)
self.assertEqual(opt.convert("333.3"), 333.3)
def test_float_opt_no_config(self):
FloatOption("setting", "float_option", 666.6)
# test default, nothing in config yet
self.assertEqual(self.config.setting["float_option"], 666.6)
self.assertIs(type(self.config.setting["float_option"]), float)
def test_float_opt_set_read_back(self):
FloatOption("setting", "float_option", 666.6)
# set option and read back
self.config.setting["float_option"] = 333.3
self.assertEqual(self.config.setting["float_option"], 333.3)
self.assertIs(type(self.config.setting["float_option"]), float)
def test_float_opt_not_float(self):
FloatOption("setting", "float_option", 666.6)
# set option to invalid value
self.config.setting["float_option"] = 'invalid'
self.assertEqual(self.config.setting["float_option"], 666.6)
def test_float_opt_set_none(self):
FloatOption("setting", "float_option", 666.6)
# set option to None
self.config.setting["float_option"] = None
self.assertEqual(self.config.setting["float_option"], 666.6)
def test_float_opt_direct_invalid(self):
FloatOption("setting", "float_option", 666.6)
# store invalid float value in config file directly
self.config.setValue('setting/float_option', '333.3x')
self.assertEqual(self.config.setting["float_option"], 666.6)
def test_float_opt_direct_validstr(self):
FloatOption("setting", "float_option", 666.6)
# store float as string directly, it should be ok, due to conversion
self.config.setValue('setting/float_option', '333.3')
self.assertEqual(self.config.setting["float_option"], 333.3)
class TestPicardConfigListOption(TestPicardConfigCommon):
def test_list_opt_convert(self):
opt = ListOption("setting", "list_option", [])
self.assertEqual(opt.convert(('1', '2', '3')), ['1', '2', '3'])
def test_list_opt_no_config(self):
ListOption("setting", "list_option", ["a", "b"])
# test default, nothing in config yet
self.assertEqual(self.config.setting["list_option"], ["a", "b"])
self.assertIs(type(self.config.setting["list_option"]), list)
def test_list_opt_set_read_back(self):
ListOption("setting", "list_option", ["a", "b"])
# set option and read back
self.config.setting["list_option"] = ["c", "d"]
self.assertEqual(self.config.setting["list_option"], ["c", "d"])
self.assertIs(type(self.config.setting["list_option"]), list)
def test_list_opt_not_list(self):
ListOption("setting", "list_option", ["a", "b"])
# set option to invalid value
self.config.setting["list_option"] = 'invalid'
self.assertEqual(self.config.setting["list_option"], ["a", "b"])
def test_list_opt_set_none(self):
ListOption("setting", "list_option", ["a", "b"])
# set option to None
self.config.setting["list_option"] = None
self.assertEqual(self.config.setting["list_option"], [])
def test_list_opt_set_empty(self):
ListOption("setting", "list_option", ["a", "b"])
# set option to empty list
self.config.setting["list_option"] = []
self.assertEqual(self.config.setting["list_option"], [])
def test_list_opt_direct_invalid(self):
ListOption("setting", "list_option", ["a", "b"])
# store invalid list value in config file directly
self.config.setValue('setting/list_option', 'efg')
self.assertEqual(self.config.setting["list_option"], ["a", "b"])
class TestPicardConfigVarOption(TestPicardConfigCommon):
# Option
def test_var_opt_convert(self):
opt = Option("setting", "var_option", set())
self.assertEqual(opt.convert(["a", "b", "a"]), {"a", "b"})
def test_var_opt_no_config(self):
Option("setting", "var_option", {"a", "b"})
# test default, nothing in config yet
self.assertEqual(self.config.setting["var_option"], {"a", "b"})
self.assertIs(type(self.config.setting["var_option"]), set)
def test_var_opt_set_read_back(self):
Option("setting", "var_option", {"a", "b"})
# set option to "def", and read back
self.config.setting["var_option"] = {"c", "d"}
self.assertEqual(self.config.setting["var_option"], {"c", "d"})
self.assertIs(type(self.config.setting["var_option"]), set)
def test_var_opt_set_none(self):
Option("setting", "var_option", {"a", "b"})
# set option to None
self.config.setting["var_option"] = None
self.assertEqual(self.config.setting["var_option"], {"a", "b"})
def test_var_opt_set_empty(self):
Option("setting", "var_option", {"a", "b"})
# set option to ""
self.config.setting["var_option"] = set()
self.assertEqual(self.config.setting["var_option"], set())
def test_var_opt_invalid_value(self):
Option("setting", "var_option", {"a", "b"})
# store invalid value in config file directly
self.config.setValue('setting/var_option', object)
self.assertEqual(self.config.setting["var_option"], {"a", "b"})
| 16,135
|
Python
|
.py
| 325
| 41.904615
| 99
| 0.654682
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,890
|
test_browser_addrelease.py
|
metabrainz_picard/test/test_browser_addrelease.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Laurent Monin
# Copyright (C) 2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.browser.addrelease import extract_discnumber
from picard.metadata import Metadata
class BrowserAddreleaseTest(PicardTestCase):
def test_extract_discnumber(self):
self.assertEqual(1, extract_discnumber(Metadata()))
self.assertEqual(1, extract_discnumber(Metadata({'discnumber': '1'})))
self.assertEqual(42, extract_discnumber(Metadata({'discnumber': '42'})))
self.assertEqual(3, extract_discnumber(Metadata({'discnumber': '3/12'})))
self.assertEqual(3, extract_discnumber(Metadata({'discnumber': ' 3 / 12 '})))
| 1,474
|
Python
|
.py
| 30
| 46.466667
| 85
| 0.760083
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,891
|
test_util_progresscheckpoints.py
|
metabrainz_picard/test/test_util_progresscheckpoints.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2020 Gabriel Ferreira
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.util.progresscheckpoints import ProgressCheckpoints
class ProgressCheckpointsTest(PicardTestCase):
def setUp(self):
super().setUp()
def test_empty_jobs(self):
checkpoints = ProgressCheckpoints(0, 1)
self.assertEqual(list(sorted(checkpoints._checkpoints.keys())), [])
self.assertEqual(list(sorted(checkpoints._checkpoints.values())), [])
checkpoints = ProgressCheckpoints(0, 0)
self.assertEqual(list(sorted(checkpoints._checkpoints.keys())), [])
self.assertEqual(list(sorted(checkpoints._checkpoints.values())), [])
checkpoints = ProgressCheckpoints(1, 0)
self.assertEqual(list(sorted(checkpoints._checkpoints.keys())), [])
self.assertEqual(list(sorted(checkpoints._checkpoints.values())), [])
def test_uniformly_spaced_integer_distance(self):
checkpoints = ProgressCheckpoints(100, 10)
self.assertEqual(list(sorted(checkpoints._checkpoints.keys())), [10, 20, 30, 40, 50, 60, 70, 80, 90, 99])
self.assertEqual(list(sorted(checkpoints._checkpoints.values())), [10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
def test_uniformly_spaced_fractional_distance(self):
checkpoints = ProgressCheckpoints(100, 7)
self.assertEqual(list(sorted(checkpoints._checkpoints.keys())), [14, 28, 42, 57, 71, 85, 99])
self.assertEqual(list(sorted(checkpoints._checkpoints.values())), [14, 28, 42, 57, 71, 85, 100])
checkpoints = ProgressCheckpoints(10, 20)
self.assertEqual(list(sorted(checkpoints._checkpoints.keys())), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
self.assertEqual(list(sorted(checkpoints._checkpoints.values())), [5, 15, 25, 35, 45, 55, 65, 75, 85, 100])
checkpoints = ProgressCheckpoints(5, 10)
self.assertEqual(list(sorted(checkpoints._checkpoints.keys())), [0, 1, 2, 3, 4])
self.assertEqual(list(sorted(checkpoints._checkpoints.values())), [10, 30, 50, 70, 100])
| 2,829
|
Python
|
.py
| 48
| 53.6875
| 116
| 0.710365
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,892
|
test_disc_whipper.py
|
metabrainz_picard/test/test_disc_whipper.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import (
PicardTestCase,
get_test_data_path,
)
from picard.disc.whipperlog import toc_from_file
class TestTocFromFile(PicardTestCase):
def test_toc_from_file(self):
test_log = get_test_data_path('whipper.log')
toc = toc_from_file(test_log)
self.assertEqual((1, 8, 149323, 150, 25064, 43611, 60890, 83090, 100000, 115057, 135558), toc)
| 1,222
|
Python
|
.py
| 29
| 39.689655
| 102
| 0.753159
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,893
|
test_i18n.py
|
metabrainz_picard/test/test_i18n.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019, 2023-2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify 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.
import os
import shutil
import tempfile
import unittest
from unittest.mock import (
call,
patch,
)
from test.picardtestcase import PicardTestCase
from picard.i18n import (
N_,
_try_encodings,
_try_locales,
gettext as _,
gettext_constants,
gettext_countries,
ngettext,
pgettext_attributes,
setup_gettext,
sort_key,
)
localedir = os.path.join(os.path.dirname(__file__), '..', 'locale')
class TestI18n(PicardTestCase):
def test_missing_locales(self):
tmplocaledir = tempfile.mkdtemp()
def cleanup_tmplocale():
shutil.rmtree(tmplocaledir)
self.addCleanup(cleanup_tmplocale)
locale_de = os.path.join(tmplocaledir, 'de', 'LC_MESSAGES', 'picard.mo')
self.assertFalse(os.path.exists(locale_de), 'unexpected file %s' % locale_de)
setup_gettext(tmplocaledir, 'de')
self.assertEqual('foo', _('foo'))
self.assertEqual('Country', _('Country'))
self.assertEqual('Country', N_('Country'))
self.assertEqual('%i image', ngettext('%i image', '%i images', 1))
self.assertEqual('%i images', ngettext('%i image', '%i images', 2))
self.assertEqual('Cassette', pgettext_attributes('medium_format', 'Cassette'))
self.assertEqual('French', gettext_constants('French'))
self.assertEqual('France', gettext_countries('France'))
@unittest.skipUnless(os.path.exists(os.path.join(localedir, 'de')),
'Test requires locales to be built with "python setup.py build_locales -i"')
def test_existing_locales(self):
locale_de = os.path.join(localedir, 'de', 'LC_MESSAGES', 'picard.mo')
self.assertTrue(os.path.exists(locale_de), 'expected file %s' % locale_de)
setup_gettext(localedir, 'de')
self.assertEqual('foo', _('foo'))
self.assertEqual('Land', _('Country'))
self.assertEqual('Country', N_('Country'))
self.assertEqual('%i Bild', ngettext('%i image', '%i images', 1))
self.assertEqual('%i Bilder', ngettext('%i image', '%i images', 2))
self.assertEqual('Kassette', pgettext_attributes('medium_format', 'Cassette'))
# self.assertEqual('Französisch', gettext_constants('French'))
self.assertEqual('Frankreich', gettext_countries('France'))
def test_gettext_handles_empty_string(self):
setup_gettext(localedir, 'fr')
self.assertEqual('', _(''))
def test_sort_key(self):
setup_gettext(localedir, 'de')
self.assertTrue(sort_key('√§b') < sort_key('ac'))
self.assertTrue(sort_key('foo002') < sort_key('foo1'))
self.assertTrue(sort_key('002 foo') < sort_key('1 foo'))
self.assertTrue(sort_key('1') < sort_key('C'))
self.assertTrue(sort_key('foo1', numeric=True) < sort_key('foo002', numeric=True))
self.assertTrue(sort_key('004', numeric=True) < sort_key('5', numeric=True))
self.assertTrue(sort_key('0042', numeric=True) < sort_key('50', numeric=True))
self.assertTrue(sort_key('5', numeric=True) < sort_key('0042', numeric=True))
self.assertTrue(sort_key('99', numeric=True) < sort_key('100', numeric=True))
def test_sort_key_numbers_different_scripts(self):
setup_gettext(localedir, 'en')
for four in ('4', 'ùüú', 'Ÿ§', '‡πî'):
self.assertTrue(
sort_key('3', numeric=True) < sort_key(four, numeric=True),
msg=f'3 < {four}'
)
self.assertTrue(
sort_key(four, numeric=True) < sort_key('5', numeric=True),
msg=f'{four} < 5'
)
@patch('locale.getpreferredencoding', autospec=True)
class TestTryEncodingsLocales(PicardTestCase):
def test_try_encodings_iso(self, locale_getpreferredencoding_mock):
locale_getpreferredencoding_mock.return_value = 'ISO-8859-1'
result = tuple(_try_encodings())
expected = ('ISO-8859-1', 'UTF-8', None)
self.assertEqual(expected, result)
locale_getpreferredencoding_mock.assert_called_once()
def test_try_encodings_utf8(self, locale_getpreferredencoding_mock):
locale_getpreferredencoding_mock.return_value = 'UTF-8'
result = tuple(_try_encodings())
expected = ('UTF-8', None)
self.assertEqual(expected, result)
locale_getpreferredencoding_mock.assert_called_once()
@patch('locale.normalize', autospec=True)
def test_try_locales_utf8_en(self, locale_nomalize_mock, locale_getpreferredencoding_mock):
locale_getpreferredencoding_mock.return_value = 'UTF-8'
locale_nomalize_mock.return_value = 'en_US.UTF-8'
result = tuple(_try_locales('en'))
expected = ('en_US.UTF-8', 'en')
self.assertEqual(expected, result)
locale_getpreferredencoding_mock.assert_called_once()
calls = [call('en.UTF-8')]
locale_nomalize_mock.assert_has_calls(calls)
@patch('locale.normalize', autospec=True)
def test_try_locales_iso_en(self, locale_nomalize_mock, locale_getpreferredencoding_mock):
locale_getpreferredencoding_mock.return_value = 'ISO-8859-1'
locale_nomalize_mock.side_effect = lambda x: x.lower()
result = tuple(_try_locales('EN'))
expected = ('en.iso-8859-1', 'en.utf-8', 'EN')
self.assertEqual(expected, result)
locale_getpreferredencoding_mock.assert_called_once()
calls = [call('EN.ISO-8859-1'), call('EN.UTF-8')]
locale_nomalize_mock.assert_has_calls(calls)
| 6,338
|
Python
|
.py
| 131
| 41.503817
| 95
| 0.664349
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,894
|
test_config_upgrade.py
|
metabrainz_picard/test/test_config_upgrade.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
# Copyright (C) 2019-2024 Philipp Wolfer
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Gabriel Ferreira
#
# This program is free software; you can redistribute it and/or
# modify 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.
import os
from PyQt6.QtCore import QByteArray
from test.picardtestcase import PicardTestCase
from test.test_config import TestPicardConfigCommon
from picard.config import (
BoolOption,
IntOption,
ListOption,
Option,
TextOption,
)
import picard.config_upgrade
from picard.config_upgrade import (
OLD_DEFAULT_FILE_NAMING_FORMAT_v1_3,
OLD_DEFAULT_FILE_NAMING_FORMAT_v2_1,
UpgradeHooksAutodetectError,
autodetect_upgrade_hooks,
upgrade_to_v1_0_0final0,
upgrade_to_v1_3_0dev1,
upgrade_to_v1_3_0dev2,
upgrade_to_v1_3_0dev3,
upgrade_to_v1_3_0dev4,
upgrade_to_v1_4_0dev2,
upgrade_to_v1_4_0dev3,
upgrade_to_v1_4_0dev4,
upgrade_to_v1_4_0dev6,
upgrade_to_v1_4_0dev7,
upgrade_to_v2_0_0dev3,
upgrade_to_v2_1_0dev1,
upgrade_to_v2_2_0dev3,
upgrade_to_v2_2_0dev4,
upgrade_to_v2_4_0beta3,
upgrade_to_v2_5_0dev1,
upgrade_to_v2_5_0dev2,
upgrade_to_v2_6_0beta2,
upgrade_to_v2_6_0beta3,
upgrade_to_v2_6_0dev1,
upgrade_to_v2_7_0dev3,
upgrade_to_v2_7_0dev4,
upgrade_to_v2_7_0dev5,
upgrade_to_v2_8_0dev2,
upgrade_to_v3_0_0dev3,
upgrade_to_v3_0_0dev4,
upgrade_to_v3_0_0dev5,
)
from picard.const.defaults import (
DEFAULT_FILE_NAMING_FORMAT,
DEFAULT_REPLACEMENT,
DEFAULT_SCRIPT_NAME,
)
from picard.util import unique_numbered_title
from picard.version import Version
from picard.ui.theme import UiTheme
def _upgrade_hook_ok_1_2_3_dev_1(config):
pass
def _upgrade_hook_not_ok_xxx(config):
pass
def _upgrade_hook_tricky_1_2_3_alpha_1(config):
pass
def _upgrade_hook_tricky_1_2_3_alpha1(config):
pass
def _upgrade_hook_future_9999(config):
pass
# WARNING: order of _upgrade_hook_sort_*() functions is important for tests
def _upgrade_hook_sort_2(config):
pass
def _upgrade_hook_sort_1(config):
pass
def _upgrade_hook_sort_2_0_0dev1(config):
pass
class TestPicardConfigUpgradesAutodetect(PicardTestCase):
def test_upgrade_hook_autodetect_ok(self):
hooks = autodetect_upgrade_hooks(module_name=__name__, prefix='_upgrade_hook_ok_')
expected_version = Version(major=1, minor=2, patch=3, identifier='dev', revision=1)
self.assertIn(expected_version, hooks)
self.assertEqual(hooks[expected_version], _upgrade_hook_ok_1_2_3_dev_1)
self.assertEqual(len(hooks), 1)
def test_upgrade_hook_autodetect_not_ok(self):
with self.assertRaisesRegex(
UpgradeHooksAutodetectError,
r'^Failed to extract version from _upgrade_hook_not_ok_xxx'
):
autodetect_upgrade_hooks(module_name=__name__, prefix='_upgrade_hook_not_ok_')
def test_upgrade_hook_autodetect_tricky(self):
with self.assertRaisesRegex(
UpgradeHooksAutodetectError,
r"^Conflicting functions for version 1\.2\.3\.alpha1"
):
autodetect_upgrade_hooks(module_name=__name__, prefix='_upgrade_hook_tricky_')
def test_upgrade_hook_autodetect_future(self):
with self.assertRaisesRegex(
UpgradeHooksAutodetectError,
r"^Upgrade hook _upgrade_hook_future_9999 has version 9999\.0\.0\.final0 > Picard version"
):
autodetect_upgrade_hooks(module_name=__name__, prefix='_upgrade_hook_future_')
def test_upgrade_hook_autodetect_sort(self):
hooks = autodetect_upgrade_hooks(module_name=__name__, prefix='_upgrade_hook_sort_')
expected_keys = (
Version(major=1, minor=0, patch=0, identifier='final', revision=0),
Version(major=2, minor=0, patch=0, identifier='dev', revision=1),
Version(major=2, minor=0, patch=0, identifier='final', revision=0),
)
self.assertEqual(tuple(hooks), expected_keys)
class TestPicardConfigUpgrades(TestPicardConfigCommon):
def test_upgrade_to_v1_0_0final0_A(self):
TextOption('setting', 'file_naming_format', '')
self.config.setting['va_file_naming_format'] = 'abc'
self.config.setting['use_va_format'] = True
self.assertIn('va_file_naming_format', self.config.setting)
self.assertIn('use_va_format', self.config.setting)
upgrade_to_v1_0_0final0(self.config, interactive=False, merge=True)
self.assertNotIn('va_file_naming_format', self.config.setting)
self.assertNotIn('use_va_format', self.config.setting)
self.assertIn('file_naming_format', self.config.setting)
def test_upgrade_to_v1_0_0final0_B(self):
TextOption('setting', 'file_naming_format', '')
self.config.setting['va_file_naming_format'] = 'abc'
self.config.setting['use_va_format'] = ""
self.assertIn('va_file_naming_format', self.config.setting)
self.assertIn('use_va_format', self.config.setting)
upgrade_to_v1_0_0final0(self.config, interactive=False, merge=False)
self.assertNotIn('va_file_naming_format', self.config.setting)
self.assertNotIn('use_va_format', self.config.setting)
self.assertNotIn('file_naming_format', self.config.setting)
def test_upgrade_to_v1_3_0dev1(self):
BoolOption('setting', 'windows_compatibility', False)
self.config.setting['windows_compatible_filenames'] = True
upgrade_to_v1_3_0dev1(self.config)
self.assertNotIn('windows_compatible_filenames', self.config.setting)
self.assertTrue(self.config.setting['windows_compatibility'])
def test_upgrade_to_v1_3_0dev2(self):
TextOption('setting', 'preserved_tags', '')
self.config.setting['preserved_tags'] = "a b c "
upgrade_to_v1_3_0dev2(self.config)
self.assertEqual("a,b,c", self.config.setting['preserved_tags'])
def test_upgrade_to_v1_3_0dev2_skip_list(self):
ListOption('setting', 'preserved_tags', [])
self.config.setting['preserved_tags'] = ['foo']
upgrade_to_v1_3_0dev2(self.config)
self.assertEqual(['foo'], self.config.setting['preserved_tags'])
def test_upgrade_to_v1_3_0dev3(self):
ListOption("setting", "preferred_release_countries", [])
ListOption("setting", "preferred_release_formats", [])
ListOption("setting", "enabled_plugins", [])
ListOption("setting", "caa_image_types", [])
ListOption("setting", "metadata_box_sizes", [])
self.config.setting['preferred_release_countries'] = "a b c"
self.config.setting['preferred_release_formats'] = "a b c"
self.config.setting['enabled_plugins'] = 'a b c'
self.config.setting['caa_image_types'] = 'a b c'
self.config.setting['metadata_box_sizes'] = 'a b c'
upgrade_to_v1_3_0dev3(self.config)
self.assertEqual(["a", "b", "c"], self.config.setting['preferred_release_countries'])
self.assertEqual(["a", "b", "c"], self.config.setting['preferred_release_formats'])
self.assertEqual(["a", "b", "c"], self.config.setting['enabled_plugins'])
self.assertEqual(["a", "b", "c"], self.config.setting['caa_image_types'])
self.assertEqual(["a", "b", "c"], self.config.setting['metadata_box_sizes'])
def test_upgrade_to_v1_3_0dev4(self):
ListOption("setting", "release_type_scores", [])
self.config.setting['release_type_scores'] = "a 0.1 b 0.2 c 1"
upgrade_to_v1_3_0dev4(self.config)
self.assertEqual([('a', 0.1), ('b', 0.2), ('c', 1.0)], self.config.setting['release_type_scores'])
def test_upgrade_to_v1_4_0dev2(self):
self.config.setting['username'] = 'abc'
self.config.setting['password'] = 'abc' # nosec
upgrade_to_v1_4_0dev2(self.config)
self.assertNotIn('username', self.config.setting)
self.assertNotIn('password', self.config.setting)
def test_upgrade_to_v1_4_0dev3(self):
ListOption("setting", "ca_providers", [])
self.config.setting['ca_provider_use_amazon'] = True
self.config.setting['ca_provider_use_caa'] = True
self.config.setting['ca_provider_use_whitelist'] = False
self.config.setting['ca_provider_use_caa_release_group_fallback'] = True
upgrade_to_v1_4_0dev3(self.config)
self.assertIn('ca_providers', self.config.setting)
self.assertIn(('Amazon', True), self.config.setting['ca_providers'])
self.assertIn(('Cover Art Archive', True), self.config.setting['ca_providers'])
self.assertIn(('Whitelist', False), self.config.setting['ca_providers'])
self.assertIn(('CaaReleaseGroup', True), self.config.setting['ca_providers'])
self.assertEqual(len(self.config.setting['ca_providers']), 4)
def test_upgrade_to_v1_4_0dev4(self):
TextOption("setting", "file_naming_format", "")
self.config.setting['file_naming_format'] = 'xxx'
upgrade_to_v1_4_0dev4(self.config)
self.assertEqual('xxx', self.config.setting['file_naming_format'])
self.config.setting['file_naming_format'] = OLD_DEFAULT_FILE_NAMING_FORMAT_v1_3
upgrade_to_v1_4_0dev4(self.config)
self.assertEqual(DEFAULT_FILE_NAMING_FORMAT, self.config.setting['file_naming_format'])
def test_upgrade_to_v1_4_0dev6(self):
BoolOption('setting', 'enable_tagger_scripts', False)
ListOption('setting', 'list_of_scripts', [])
self.config.setting['enable_tagger_script'] = True
self.config.setting['tagger_script'] = "abc"
upgrade_to_v1_4_0dev6(self.config)
self.assertNotIn('enable_tagger_script', self.config.setting)
self.assertNotIn('tagger_script', self.config.setting)
self.assertTrue(self.config.setting['enable_tagger_scripts'])
self.assertEqual([(0, unique_numbered_title(DEFAULT_SCRIPT_NAME, []), True, 'abc')], self.config.setting['list_of_scripts'])
def test_upgrade_to_v1_4_0dev7(self):
BoolOption('setting', 'embed_only_one_front_image', False)
self.config.setting['save_only_front_images_to_tags'] = True
upgrade_to_v1_4_0dev7(self.config)
self.assertNotIn('save_only_front_images_to_tags', self.config.setting)
self.assertTrue(self.config.setting['embed_only_one_front_image'])
def test_upgrade_to_v2_0_0dev3(self):
IntOption("setting", "caa_image_size", 500)
self.config.setting['caa_image_size'] = 0
upgrade_to_v2_0_0dev3(self.config)
self.assertEqual(250, self.config.setting['caa_image_size'])
self.config.setting['caa_image_size'] = 501
upgrade_to_v2_0_0dev3(self.config)
self.assertEqual(501, self.config.setting['caa_image_size'])
def test_upgrade_to_v2_1_0dev1(self):
BoolOption("setting", "use_genres", False)
IntOption("setting", "max_genres", 5)
IntOption("setting", "min_genre_usage", 90)
TextOption("setting", "ignore_genres", "seen live, favorites, fixme, owned")
TextOption("setting", "join_genres", "")
BoolOption("setting", "only_my_genres", False)
BoolOption("setting", "artists_genres", False)
BoolOption("setting", "folksonomy_tags", False)
self.config.setting['folksonomy_tags'] = True
self.config.setting['max_tags'] = 6
self.config.setting['min_tag_usage'] = 85
self.config.setting['ignore_tags'] = "abc"
self.config.setting['join_tags'] = "abc"
self.config.setting['only_my_tags'] = True
self.config.setting['artists_tags'] = True
upgrade_to_v2_1_0dev1(self.config)
self.assertEqual(self.config.setting['use_genres'], True)
self.assertEqual(self.config.setting['max_genres'], 6)
self.assertEqual(self.config.setting['min_genre_usage'], 85)
self.assertEqual(self.config.setting['ignore_genres'], "abc")
self.assertEqual(self.config.setting['join_genres'], "abc")
self.assertEqual(self.config.setting['only_my_genres'], True)
self.assertEqual(self.config.setting['artists_genres'], True)
self.assertIn('folksonomy_tags', self.config.setting)
self.assertNotIn('max_tags', self.config.setting)
self.assertNotIn('min_tag_usage', self.config.setting)
self.assertNotIn('ignore_tags', self.config.setting)
self.assertNotIn('join_tags', self.config.setting)
self.assertNotIn('only_my_tags', self.config.setting)
self.assertNotIn('artists_tags', self.config.setting)
def test_upgrade_to_v2_2_0dev3(self):
TextOption("setting", "ignore_genres", "")
TextOption("setting", "genres_filter", "")
self.config.setting['ignore_genres'] = "a, b,c"
upgrade_to_v2_2_0dev3(self.config)
self.assertNotIn('ignore_genres', self.config.setting)
self.assertEqual(self.config.setting['genres_filter'], "-a\n-b\n-c")
def test_upgrade_to_v2_2_0dev4(self):
TextOption("setting", "file_naming_format", "")
self.config.setting['file_naming_format'] = 'xxx'
upgrade_to_v2_2_0dev4(self.config)
self.assertEqual('xxx', self.config.setting['file_naming_format'])
self.config.setting['file_naming_format'] = OLD_DEFAULT_FILE_NAMING_FORMAT_v2_1
upgrade_to_v2_2_0dev4(self.config)
self.assertEqual(DEFAULT_FILE_NAMING_FORMAT, self.config.setting['file_naming_format'])
def test_upgrade_to_v2_4_0beta3(self):
ListOption("setting", "preserved_tags", [])
self.config.setting['preserved_tags'] = 'foo,bar'
upgrade_to_v2_4_0beta3(self.config)
self.assertEqual(['foo', 'bar'], self.config.setting['preserved_tags'])
def test_upgrade_to_v2_4_0beta3_already_done(self):
ListOption("setting", "preserved_tags", [])
self.config.setting['preserved_tags'] = ['foo', 'bar']
upgrade_to_v2_4_0beta3(self.config)
self.assertEqual(['foo', 'bar'], self.config.setting['preserved_tags'])
def test_upgrade_to_v2_5_0dev1(self):
ListOption("setting", "ca_providers", [])
self.config.setting['ca_providers'] = [
('Cover Art Archive', True),
('Whitelist', True),
('Local', False),
]
expected = [
('Cover Art Archive', True),
('UrlRelationships', True),
('Local', False),
]
upgrade_to_v2_5_0dev1(self.config)
self.assertEqual(expected, self.config.setting['ca_providers'])
def test_upgrade_to_v2_5_0dev2(self):
Option("persist", "splitter_state", QByteArray())
Option("persist", "bottom_splitter_state", QByteArray())
self.config.persist["splitter_state"] = b'foo'
self.config.persist["bottom_splitter_state"] = b'bar'
upgrade_to_v2_5_0dev2(self.config)
self.assertEqual(b'', self.config.persist['splitter_state'])
self.assertEqual(b'', self.config.persist['bottom_splitter_state'])
def test_upgrade_to_v2_6_0dev1(self):
TextOption("setting", "acoustid_fpcalc", "")
self.config.setting["acoustid_fpcalc"] = "/usr/bin/fpcalc"
upgrade_to_v2_6_0dev1(self.config)
self.assertEqual("/usr/bin/fpcalc", self.config.setting["acoustid_fpcalc"])
def test_upgrade_to_v2_6_0dev1_empty(self):
TextOption("setting", "acoustid_fpcalc", "")
self.config.setting["acoustid_fpcalc"] = None
upgrade_to_v2_6_0dev1(self.config)
self.assertEqual("", self.config.setting["acoustid_fpcalc"])
def test_upgrade_to_v2_6_0dev1_snap(self):
TextOption("setting", "acoustid_fpcalc", "")
self.config.setting["acoustid_fpcalc"] = "/snap/picard/221/usr/bin/fpcalc"
upgrade_to_v2_6_0dev1(self.config)
self.assertEqual("", self.config.setting["acoustid_fpcalc"])
def test_upgrade_to_v2_6_0dev1_frozen(self):
TextOption("setting", "acoustid_fpcalc", "")
self.config.setting["acoustid_fpcalc"] = r"C:\Program Files\MusicBrainz Picard\fpcalc.exe"
picard.config_upgrade.IS_FROZEN = True
upgrade_to_v2_6_0dev1(self.config)
picard.config_upgrade.IS_FROZEN = False
self.assertEqual("", self.config.setting["acoustid_fpcalc"])
def test_upgrade_to_v2_6_0beta2(self):
BoolOption('setting', 'image_type_as_filename', False)
BoolOption('setting', 'save_only_one_front_image', False)
self.config.setting['caa_image_type_as_filename'] = True
self.config.setting['caa_save_single_front_image'] = True
upgrade_to_v2_6_0beta2(self.config)
self.assertNotIn('caa_image_type_as_filename', self.config.setting)
self.assertTrue(self.config.setting['image_type_as_filename'])
self.assertNotIn('caa_save_single_front_image', self.config.setting)
self.assertTrue(self.config.setting['save_only_one_front_image'])
def test_upgrade_to_v2_6_0beta3(self):
# Legacy setting
BoolOption('setting', 'use_system_theme', False)
self.config.setting['use_system_theme'] = True
del Option.registry['setting', 'use_system_theme']
# New setting
TextOption('setting', 'ui_theme', str(UiTheme.DEFAULT))
upgrade_to_v2_6_0beta3(self.config)
self.assertNotIn('use_system_theme', self.config.setting)
self.assertIn('ui_theme', self.config.setting)
self.assertEqual(str(UiTheme.SYSTEM), self.config.setting['ui_theme'])
def test_upgrade_to_v2_7_0dev3(self):
# Legacy settings
ListOption('setting', 'file_naming_scripts', [])
self.config.setting['file_naming_scripts'] = [
'{"id": "766bb2ce-5170-45f1-900c-02e7f9bd41cb", "title": "Script 1", "script": "$noop(1)"}',
'{"id": "ab0abb63-797c-4a20-95a8-df1b9109f883", "title": "Script 2", "script": "$noop(2)"}',
]
TextOption('setting', 'file_naming_format', DEFAULT_FILE_NAMING_FORMAT)
self.config.setting['file_naming_format'] = "%title%"
del Option.registry[('setting', 'file_naming_scripts')]
del Option.registry[('setting', 'file_naming_format')]
# New settings
Option('setting', 'file_renaming_scripts', {})
TextOption('setting', 'selected_file_naming_script_id', '')
upgrade_to_v2_7_0dev3(self.config)
new_scripts = self.config.setting['file_renaming_scripts']
selected_script_id = self.config.setting['selected_file_naming_script_id']
self.assertEqual(3, len(new_scripts))
self.assertIn(selected_script_id, new_scripts)
script1 = new_scripts['766bb2ce-5170-45f1-900c-02e7f9bd41cb']
self.assertEqual('Script 1', script1['title'])
self.assertEqual('$noop(1)', script1['script'])
script2 = new_scripts['ab0abb63-797c-4a20-95a8-df1b9109f883']
self.assertEqual('Script 2', script2['title'])
self.assertEqual('$noop(2)', script2['script'])
default_script = new_scripts[selected_script_id]
self.assertEqual('Primary file naming script', default_script['title'])
self.assertEqual('%title%', default_script['script'])
def test_upgrade_to_v2_7_0dev4(self):
# Legacy settings
TextOption('setting', 'artist_script_exception', '')
TextOption('setting', 'artist_locale', '')
self.config.setting['artist_script_exception'] = 'LATIN'
self.config.setting['artist_locale'] = 'en'
del Option.registry[('setting', 'artist_script_exception')]
del Option.registry[('setting', 'artist_locale')]
# New settings
ListOption('setting', 'artist_script_exceptions', [])
ListOption('setting', 'artist_locales', ['en'])
upgrade_to_v2_7_0dev4(self.config)
self.assertEqual(['LATIN'], self.config.setting['artist_script_exceptions'])
self.assertEqual(['en'], self.config.setting['artist_locales'])
def test_upgrade_to_v2_7_0dev5(self):
# Legacy settings
ListOption('setting', 'artist_script_exceptions', [])
IntOption('setting', 'artist_script_exception_weighting', 0)
self.config.setting['artist_script_exceptions'] = ['LATIN', 'HEBREW']
self.config.setting['artist_script_exception_weighting'] = 20
del Option.registry[('setting', 'artist_script_exceptions')]
del Option.registry[('setting', 'artist_script_exception_weighting')]
# New settings
ListOption('setting', 'script_exceptions', [])
upgrade_to_v2_7_0dev5(self.config)
self.assertEqual(self.config.setting['script_exceptions'], [
('LATIN', 20),
('HEBREW', 20),
])
def test_upgrade_to_v2_8_0dev2(self):
ListOption('setting', 'toolbar_layout', [])
self.config.setting['toolbar_layout'] = [
'add_directory_action',
'extract_and_submit_acousticbrainz_features_action',
'save_action'
]
expected = ['add_directory_action', 'save_action']
upgrade_to_v2_8_0dev2(self.config)
self.assertEqual(expected, self.config.setting['toolbar_layout'])
upgrade_to_v2_8_0dev2(self.config)
self.assertEqual(expected, self.config.setting['toolbar_layout'])
def test_upgrade_to_v3_0_0dev3(self):
BoolOption('setting', 'allow_multi_dirs_selection', False)
self.config.setting['toolbar_multiselect'] = True
upgrade_to_v3_0_0dev3(self.config)
self.assertNotIn('toolbar_multiselect', self.config.setting)
self.assertTrue(self.config.setting['allow_multi_dirs_selection'])
def test_upgrade_to_v3_0_0dev4(self):
Option('persist', 'album_view_header_state', QByteArray())
Option('persist', 'file_view_header_state', QByteArray())
BoolOption('persist', 'album_view_header_locked', False)
BoolOption('persist', 'file_view_header_locked', False)
self.config.persist['album_view_header_state'] = b'foo'
self.config.persist['file_view_header_state'] = b'bar'
# test not locked, states shouldn't be modified
upgrade_to_v3_0_0dev4(self.config)
self.assertEqual(b'foo', self.config.persist['album_view_header_state'])
self.assertEqual(b'bar', self.config.persist['file_view_header_state'])
# test locked, states should be removed
self.config.persist['album_view_header_locked'] = True
self.config.persist['file_view_header_locked'] = True
upgrade_to_v3_0_0dev4(self.config)
self.assertEqual(b'', self.config.persist['album_view_header_state'])
self.assertEqual(b'', self.config.persist['file_view_header_state'])
def test_upgrade_to_v3_0_0dev5(self):
TextOption('setting', 'replace_dir_separator', DEFAULT_REPLACEMENT)
self.config.setting['replace_dir_separator'] = os.sep
upgrade_to_v3_0_0dev5(self.config)
self.assertEqual(DEFAULT_REPLACEMENT, self.config.setting['replace_dir_separator'])
if os.altsep:
self.config.setting['replace_dir_separator'] = os.altsep
upgrade_to_v3_0_0dev5(self.config)
self.assertEqual(DEFAULT_REPLACEMENT, self.config.setting['replace_dir_separator'])
| 23,975
|
Python
|
.py
| 457
| 44.564551
| 132
| 0.665813
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,895
|
test_ui_itemviews_columns.py
|
metabrainz_picard/test/test_ui_itemviews_columns.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
from test.picardtestcase import PicardTestCase
from picard.ui.itemviews.columns import (
Column,
ColumnAlign,
Columns,
ColumnSortType,
DefaultColumn,
IconColumn,
)
class ColumnTest(PicardTestCase):
def test_init_simple_column(self):
column = Column('title', 'key')
self.assertEqual(column.title, 'title')
self.assertEqual(column.key, 'key')
self.assertFalse(column.is_icon)
self.assertFalse(column.is_default)
self.assertEqual(column.align, ColumnAlign.LEFT)
self.assertEqual(column.sort_type, ColumnSortType.TEXT)
self.assertIsNone(column.sortkey)
expected_repr = "Column('title', 'key', size=None, align=ColumnAlign.LEFT, sort_type=ColumnSortType.TEXT, sortkey=None)"
self.assertEqual(repr(column), expected_repr)
self.assertEqual(str(column), expected_repr)
def test_init_column_align_sort_type(self):
def dummy():
pass
column = Column('title', 'key', align=ColumnAlign.RIGHT, sort_type=ColumnSortType.SORTKEY, sortkey=dummy)
self.assertEqual(column.align, ColumnAlign.RIGHT)
self.assertEqual(column.sort_type, ColumnSortType.SORTKEY)
self.assertEqual(column.sortkey, dummy)
def test_init_column_invalid_sortkey(self):
with self.assertRaisesRegex(TypeError, 'sortkey should be a callable'):
Column('title', 'key', align=ColumnAlign.RIGHT, sort_type=ColumnSortType.SORTKEY, sortkey='invalid')
def test_default_column(self):
column = DefaultColumn('title', 'key')
self.assertTrue(column.is_default)
def test_icon_column(self):
column = IconColumn('title', 'key')
self.assertTrue(column.is_icon)
column.header_icon_func = lambda: 'icon'
self.assertEqual(column.header_icon, 'icon')
column.set_header_icon_size(10, 20, 2)
self.assertEqual(column.header_icon_size.width(), 10)
self.assertEqual(column.header_icon_size.height(), 20)
self.assertEqual(column.header_icon_size_with_border.width(), 14)
self.assertEqual(column.header_icon_size_with_border.height(), 24)
class ColumnsTest(PicardTestCase):
def test_init_columns(self):
c1 = Column('t1', 'k1')
c2 = Column('t2', 'k2')
c3 = Column('t3', 'k3')
columns = Columns([c1, c2])
self.assertEqual(columns[0], c1)
self.assertEqual(columns[1], c2)
self.assertEqual(len(columns), 2)
self.assertEqual(columns.pos('k2'), 1)
columns.append(c3)
self.assertEqual(columns[2], c3)
self.assertEqual(len(columns), 3)
self.assertEqual(columns.pos('k3'), 2)
del columns[0]
self.assertEqual(columns[0], c2)
self.assertEqual(len(columns), 2)
self.assertEqual(columns.pos('k3'), 1)
expected_repr = """Columns([
Column('t2', 'k2', size=None, align=ColumnAlign.LEFT, sort_type=ColumnSortType.TEXT, sortkey=None),
Column('t3', 'k3', size=None, align=ColumnAlign.LEFT, sort_type=ColumnSortType.TEXT, sortkey=None),
])"""
self.assertEqual(repr(columns), expected_repr)
self.assertEqual(str(columns), expected_repr)
def test_append_non_column(self):
columns = Columns()
with self.assertRaisesRegex(TypeError, "^Not an instance of Column$"):
columns.append('x')
def test_set_non_column(self):
columns = Columns([Column('t1', 'k1')])
with self.assertRaisesRegex(TypeError, "^Not an instance of Column$"):
columns[0] = 'x'
| 4,400
|
Python
|
.py
| 96
| 39.239583
| 128
| 0.686727
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,896
|
test_disc.py
|
metabrainz_picard/test/test_disc.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2020-2022 Philipp Wolfer
# Copyright (C) 2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
import unittest
from unittest.mock import (
Mock,
patch,
)
from test.picardtestcase import PicardTestCase
import picard.disc
test_toc = [1, 11, 242457, 150, 44942, 61305, 72755, 96360, 130485, 147315, 164275, 190702, 205412, 220437]
class MockDisc:
id = 'lSOVc5h6IXSuzcamJS1Gp4_tRuA-'
mcn = '5029343070452'
tracks = list(range(0, 11))
toc_string = ' '.join(str(i) for i in test_toc)
submission_url = 'https://musicbrainz.org/cdtoc/attach?id=lSOVc5h6IXSuzcamJS1Gp4_tRuA-&tracks=11&toc=1+11+242457+150+44942+61305+72755+96360+130485+147315+164275+190702+205412+220437'
class DiscTest(PicardTestCase):
@unittest.skipUnless(picard.disc.discid, "discid not available")
def test_raise_disc_error(self):
disc = picard.disc.Disc()
self.assertRaises(picard.disc.discid.DiscError, disc.read, 'notadevice')
def test_init_with_id(self):
discid = 'theId'
disc = picard.disc.Disc(id=discid)
self.assertEqual(discid, disc.id)
self.assertEqual(0, disc.tracks)
self.assertIsNone(disc.toc_string)
self.assertIsNone(disc.submission_url)
@patch.object(picard.disc, 'discid')
def test_read(self, mock_discid):
self.set_config_values(setting={
'server_host': 'musicbrainz.org',
'server_port': 443,
'use_server_for_submission': False,
})
mock_discid.read = Mock(return_value=MockDisc())
device = '/dev/cdrom1'
disc = picard.disc.Disc()
self.assertEqual(None, disc.id)
self.assertEqual(None, disc.mcn)
self.assertEqual(0, disc.tracks)
self.assertEqual(None, disc.toc_string)
self.assertEqual(None, disc.submission_url)
disc.read(device)
mock_discid.read.assert_called_with(device, features=['mcn'])
self.assertEqual(MockDisc.id, disc.id)
self.assertEqual(MockDisc.mcn, disc.mcn)
self.assertEqual(11, disc.tracks)
self.assertEqual(MockDisc.toc_string, disc.toc_string)
self.assertEqual(MockDisc.submission_url, disc.submission_url)
@patch.object(picard.disc, 'discid')
def test_put(self, mock_discid):
mock_discid.put = Mock(return_value=MockDisc())
disc = picard.disc.Disc()
disc.put(test_toc)
self.assertEqual(MockDisc.id, disc.id)
@patch.object(picard.disc, 'discid')
def test_put_invalid_toc_1(self, mock_discid):
mock_discid.TOCError = Exception
disc = picard.disc.Disc()
with self.assertRaises(mock_discid.TOCError):
disc.put([1, 11])
@patch.object(picard.disc, 'discid')
def test_put_invalid_toc_2(self, mock_discid):
mock_discid.TOCError = Exception
mock_discid.put = Mock(side_effect=mock_discid.TOCError)
disc = picard.disc.Disc()
with self.assertRaises(mock_discid.TOCError):
disc.put([1, 11, 242457])
@patch.object(picard.disc, 'discid')
def test_submission_url(self, mock_discid):
self.set_config_values(setting={
'server_host': 'test.musicbrainz.org',
'server_port': 80,
'use_server_for_submission': True,
})
mock_discid.read = Mock(return_value=MockDisc())
disc = picard.disc.Disc()
disc.read()
self.assertEqual(
'http://test.musicbrainz.org/cdtoc/attach?id=lSOVc5h6IXSuzcamJS1Gp4_tRuA-&tracks=11&toc=1+11+242457+150+44942+61305+72755+96360+130485+147315+164275+190702+205412+220437',
disc.submission_url
)
| 4,418
|
Python
|
.py
| 101
| 37.188119
| 187
| 0.684419
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,897
|
dummyplugin.py
|
metabrainz_picard/test/data/testplugins/singlefile/dummyplugin.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
"""Dummy plugin for tests"""
PLUGIN_NAME = "Dummy plugin"
PLUGIN_AUTHOR = "Zas"
PLUGIN_DESCRIPTION = "Dummy plugin description"
PLUGIN_VERSION = "1.0"
PLUGIN_API_VERSIONS = ["3.0"]
PLUGIN_LICENSE = 'Dummy plugin license'
PLUGIN_LICENSE_URL = 'dummy.plugin.url'
class DummyPlugin:
pass
| 1,117
|
Python
|
.py
| 29
| 37.241379
| 80
| 0.767528
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,898
|
dummyplugin.py
|
metabrainz_picard/test/data/testplugins/importerror/dummyplugin.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
"""Dummy plugin for tests"""
PLUGIN_NAME = "Dummy plugin"
PLUGIN_AUTHOR = "Zas"
PLUGIN_DESCRIPTION = "Dummy plugin description"
PLUGIN_VERSION = "1.0"
PLUGIN_API_VERSIONS = ["2.0"]
PLUGIN_LICENSE = 'Dummy plugin license'
PLUGIN_LICENSE_URL = 'dummy.plugin.url'
raise ImportError
| 1,107
|
Python
|
.py
| 28
| 38.392857
| 80
| 0.770233
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,899
|
__init__.py
|
metabrainz_picard/test/data/testplugins/module/dummyplugin/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify 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.
"""Dummy plugin for tests"""
PLUGIN_NAME = "Dummy plugin"
PLUGIN_AUTHOR = "Zas"
PLUGIN_DESCRIPTION = "Dummy plugin description"
PLUGIN_VERSION = "1.0"
PLUGIN_API_VERSIONS = ["3.0"]
PLUGIN_LICENSE = 'Dummy plugin license'
PLUGIN_LICENSE_URL = 'dummy.plugin.url'
class DummyPlugin:
pass
| 1,117
|
Python
|
.py
| 29
| 37.241379
| 80
| 0.767528
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|