| 1 |
#!/usr/bin/env python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
"""Tests for the Windows Registry searcher.""" |
| 4 |
|
| 5 |
import fnmatch |
| 6 |
import unittest |
| 7 |
|
| 8 |
from dfwinreg import glob2regex |
| 9 |
|
| 10 |
from tests import test_lib |
| 11 |
|
| 12 |
|
| 13 |
class Glob2RegexTest(test_lib.BaseTestCase): |
| 14 |
"""Tests for the glob to regular expression conversion function.""" |
| 15 |
|
| 16 |
_TEST_PATTERNS = [ |
| 17 |
'plain.txt', '*.txt', 'plain?.txt', 'plain[?].txt', 'plai[nN].txt', |
| 18 |
'plai[!nN].txt', 'plai[nN.txt', 'plain.(jpg|txt)', '.^$*+?{}\\[]|()', |
| 19 |
'plai[^nN].txt', '!%&`~:', '[.^$*+?{}\\|()]', '[\\]]', '[]]'] |
| 20 |
|
| 21 |
def _Glob2Regex(self, glob_pattern): |
| 22 |
"""Converts a glob pattern to a regular expression. |
| 23 |
|
| 24 |
Args: |
| 25 |
glob_pattern (str): glob pattern. |
| 26 |
|
| 27 |
Returns: |
| 28 |
str: regular expression of the glob pattern. |
| 29 |
|
| 30 |
Raises: |
| 31 |
ValueError: if the glob pattern cannot be converted. |
| 32 |
""" |
| 33 |
# fnmatch.translate() is used to convert a glob into a regular |
| 34 |
# expression. For Python 3.5 and earlier, the resulting regular |
| 35 |
# expression has "\Z(?ms)" defined at its end, which needs to be |
| 36 |
# removed and escapes the forward slash "/", which needs to be |
| 37 |
# undone. Python 3.6 puts the options at the beginning of the |
| 38 |
# regular expression instead. |
| 39 |
|
| 40 |
fnmatch_regex = fnmatch.translate(glob_pattern) |
| 41 |
|
| 42 |
for suffix in (r'\Z(?ms)', r')\Z', r')\z'): |
| 43 |
if fnmatch_regex.endswith(suffix): |
| 44 |
fnmatch_regex = fnmatch_regex[:-len(suffix)] |
| 45 |
if fnmatch_regex.startswith('(?s:'): |
| 46 |
fnmatch_regex = fnmatch_regex[len('(?s:'):] |
| 47 |
|
| 48 |
return fnmatch_regex.replace('\\/', '/') |
| 49 |
|
| 50 |
def testGlob2Regex(self): |
| 51 |
"""Tests the Glob2Regex function.""" |
| 52 |
for glob_pattern in self._TEST_PATTERNS: |
| 53 |
regex = glob2regex.Glob2Regex(glob_pattern) |
| 54 |
expected_regex = self._Glob2Regex(glob_pattern) |
| 55 |
self.assertEqual(regex, expected_regex) |
| 56 |
|
| 57 |
with self.assertRaises(ValueError): |
| 58 |
glob2regex.Glob2Regex(None) |
| 59 |
|
| 60 |
|
| 61 |
if __name__ == '__main__': |
| 62 |
unittest.main() |