def test_complex_pattern(): pattern = r'(\d[.-])?\d{3,}[.-]\d{3,}[.-]\d{4,}' s = """ never call the number 1-800-666-1337. instead, you sould call the number 333-3737-13 but actually, that number sucks, so call "9-373-185-7242" or really just hit me up at777.777.7777 """ global tmpfile tmpfile.seek(0) tmpfile.write(s) os.fsync(tmpfile.fileno()) tmpfile.seek(0) matches = list(find_pattern_in_file(pattern=pattern, filename=tmpfile.name)) assert len(matches) == 3 for m in matches: assert m['match'].re.pattern == pattern if sys.version_info.major > 2: assert m['match'].re.flags == re.UNICODE else: assert m['match'].re.flags == 0 assert matches[0]['match'].group() == '1-800-666-1337' assert matches[1]['match'].group() == '9-373-185-7242' assert matches[2]['match'].group() == '777.777.7777'
def test_no_flags(): global tmpfile s = 'test' tmpfile.seek(0) tmpfile.write(s) os.fsync(tmpfile.fileno()) tmpfile.seek(0) pattern = s matches = list(find_pattern_in_file(pattern=pattern, filename=tmpfile.name)) assert len(matches) == 1 assert matches[0]['match'].re.pattern == pattern if sys.version_info.major > 2: assert matches[0]['match'].re.flags == re.UNICODE else: assert matches[0]['match'].re.flags == 0 assert matches[0]['match'].string == s assert matches[0]['match'].group() == s
def test_no_pattern(): global tmpfile s = 'test' tmpfile.seek(0) tmpfile.write(s) os.fsync(tmpfile.fileno()) tmpfile.seek(0) matches = list(find_pattern_in_file(flags=re.I, filename=tmpfile.name)) assert len(matches) == len(s) + 1 for idx in range(len(s) + 1): assert matches[idx]['match'].re.pattern == '' if sys.version_info.major > 2: assert matches[idx]['match'].re.flags == re.I | re.UNICODE else: assert matches[idx]['match'].re.flags == re.I assert matches[idx]['match'].string == s assert matches[idx]['match'].group() == ''
def test_non_existent_file(): list(find_pattern_in_file(filename='/this/path/does/not/exist/and/if/it/does/you/are/insane'))
def test_no_filename(): list(find_pattern_in_file(pattern='test', flags=re.I))
def test_filename_only(): list(find_pattern_in_file(__file__))
def test_flags_only(): list(find_pattern_in_file(flags=re.I))
def test_pattern_only(): list(find_pattern_in_file(pattern='test'))
def test_no_arguments(): list(find_pattern_in_file())